<?php
/**
 *  产品列表
 *  @author  system
 *  @version    1.0
 *  @date 2018-05-14 13:29:14
 *
 */
namespace App\Http\Controllers\Admin\Album;
use App\Http\Controllers\Admin\Controller;
use App\Models\AlbumCatModel;
use App\Models\AlbumProductModel;
use App\Models\AlbumProductPriceModel;
use App\Models\AlbumProductStyleModel;
use App\Repositories\Album\Criteria\ProductWhere;
use App\Services\OSS;
use Illuminate\Http\Request;
use App\Repositories\Base\Criteria\OrderBy;
use App\Repositories\Album\ProductRepository;

class ProductController extends Controller
{
    private $repository;

    /**
     * ProductController constructor.
     * @param ProductRepository $repository
     */
    public function __construct(ProductRepository $repository)
    {
        if (!$this->repository) {
            $this->repository = $repository;
        }
    }

    function index(Request $request)
    {
        $search['keyword'] = $request->input('keyword');
        $query = $this->repository->pushCriteria(new ProductWhere($search, $this->getStoreId()));


        if (isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
            $query = $query->pushCriteria(new OrderBy($request['sort_field'], $request['sort_field_by']));
        } else {
            $query = $query->pushCriteria(new OrderBy('id', 'DESC'));
        }
        $list = $query->paginate();
        //dd($list);
        return view('admin.album.product.index', compact('list'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    function check(Request $request)
    {
        $request = $request->all();
        $search['keyword'] = $request->input('keyword');
        $orderby = array();
        if (isset($request['sort_field']) && $request['sort_field'] && isset($request['sort_field_by'])) {
            $orderby[$request['sort_field']] = $request['sort_field_by'];
        }
        $list = $this->repository->search($search, $orderby);
        return view('admin.album.product.check', compact('list'));
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getSecondCategory(Request $request)
    {
        $cat_id = $request->input('cat_id');
        if (!$cat_id) {
            return response()->json(['message' => '参数不合法', 'code' => 1]);
        }
        $cat = AlbumCatModel::where([
            ['parent_id',$cat_id],['store_id',$this->getStoreId()]
        ])->orderByDesc('sort')->get()->toArray();
        if (empty($cat)) {
            $cat[] = [
                'name' => '请先添加二级分类！',
                'id'   => 0
            ];
        }

        return response()->json([
            'data' => $cat,
            'code' => 0
        ]);
    }

    /**
     * 添加
     *
     */
    public function create(Request $request)
    {
        if ($request->method() == 'POST') {
            return $this->_createSave();
        }
        $cat = AlbumCatModel::where([['store_id',$this->getStoreId()],['parent_id', 0]])->get();
        foreach ($cat as $key => $val) {
            $son = AlbumCatModel::where([['store_id',$this->getStoreId()],['parent_id', $val['id']]])->get();
            $category[] = [
                'id' => 0,
                'name' => $val['name'],
                'son' => $son
            ];
        }
        $data['cat_id'] = null;
        return view('admin.album.product.edit', compact('data', 'category', 'style'));
    }

    /**
     * 保存修改
     */
    private function _createSave()
    {
        $data = (array) request('data');
      //  dd($data);
        if (!empty(request()->file('upload_video'))) {
            $data['upload_video'] = $this->uploadVideo(request()->file('upload_video'), request('id'));
        }

        $data['store_id'] = $this->getStoreId();
        if (!empty($data['specifications_img']['url'])) {
            foreach ($data['specifications_img']['url'] as $key => $val) {
                $data['specifications_img']['url'][$key] = $this->formatImgUrl($val);
            }
            $data['specifications_img'] = json_encode($data['specifications_img']['url']);
        }
        if (!empty($data['install_img']['url'])) {
            foreach ($data['install_img']['url'] as $key => $val) {
                $data['install_img']['url'][$key] = $this->formatImgUrl($val);
            }
            $data['install_img'] = json_encode($data['install_img']['url']);
        }
        if (!empty($data['cover_pic'])) {
            $data['cover_pic'] = $this->formatImgUrl($data['cover_pic']);
        }

        if (!empty($data['thumb'])) {
            $data['thumb'] = $this->formatImgUrl($data['thumb']);
        }

        if (!empty($data['detail']['url'])) {
            foreach ($data['detail']['url'] as $key => $val) {
                $data['detail']['url'][$key] = $this->formatImgUrl($val);
            }
            $data['detail'] = json_encode($data['detail']['url']);
        }
        if (!empty($data['detail_pic'])) {
            $data['detail_pic'] = $this->formatImgUrl($data['detail_pic']);
        }

        $id = $this->repository->create($data);
        if ($id) {
            $url[] = array('url' => U('Album/Product/index'), 'title' => '返回列表');
            $url[] = array('url' => U('Album/Product/create'), 'title' => '继续添加');
            $this->showMessage('添加成功', $url);
        } else {
            $url[] = array('url' => U('Album/Product/index'), 'title' => '返回列表');
            return $this->showWarning('添加失败', $url);
        }
    }

    public function uploadVideo($video,$id)
    {
       // dd($video);
// 判断图片有效性
        if (!$video) {
            return back()->withErrors('上传视频无效..');
        }
        if ($id) {
            $check = AlbumProductModel::where([['id',$id]])->first();
            if ($check) {
                $res = json_decode($check->upload_video, true);
                if ($res) {
                    OSS::publicDeleteObject(config('alioss.BucketName'), $res['oss_key']);
                }

            }
        }

// 获取图片在临时文件中的地址
        $videoPath = $video->getRealPath();
//       / dd($video);
// 制作文件名
        $ex = $video->getClientOriginalExtension();
        $key = time() . rand(10000, 99999999) . '.' . $ex;
//阿里 OSS 文件上传

        $result = OSS::publicUpload(config('alioss.BucketName'), $key, $videoPath);
        if ($result) {
            $data['oss_key'] =  $key;
            $data['url'] = config('alioss.FileUrl') . $key;
            $data = json_encode($data);
            return $data;
        } else {
            return false;
        }
    }

    /**
     *
     * 修改
     *
     *
     */
    public function update(Request $request)
    {
        if ($request->method() == 'POST') {
            return $this->_updateSave();
        }
        $cat = AlbumCatModel::where([['store_id',$this->getStoreId()],['parent_id', 0]])->get();
        foreach ($cat as $key => $val) {
            $son = AlbumCatModel::where([['store_id',$this->getStoreId()],['parent_id', $val['id']]])->get();
            $category[] = [
                'id' => 0,
                'name' => $val['name'],
                'son' => $son
            ];
        }
        $data = $this->repository->find($request->get('id'));
        $data['install_img'] = json_decode($data['install_img']);
        $data['specifications_img'] = json_decode($data['specifications_img']);
        $data['detail'] = json_decode($data['detail']);
        $data['upload_video'] = json_decode($data['upload_video'], true);
        $data['upload_video'] = $data['upload_video']['url'];
        return view('admin.album.product.edit', compact('data', 'category', 'parent'));
    }

    /**
     * 保存修改
     */
    private function _updateSave()
    {
        $data = (array) request('data');

        if (!empty(request()->file('upload_video'))) {
            $data['upload_video'] = $this->uploadVideo(request()->file('upload_video'), request('id'));
        }

        if (!empty($data['specifications_img']['url'])) {
            foreach ($data['specifications_img']['url'] as $key => $val) {
                $data['specifications_img']['url'][$key] = $this->formatImgUrl($val);
            }
            $data['specifications_img'] = json_encode($data['specifications_img']['url']);
        }
        if (!empty($data['install_img']['url'])) {
            foreach ($data['install_img']['url'] as $key => $val) {
                $data['install_img']['url'][$key] = $this->formatImgUrl($val);
            }
            $data['install_img'] = json_encode($data['install_img']['url']);
        }
        if (!empty($data['cover_pic'])) {
            $data['cover_pic'] = $this->formatImgUrl($data['cover_pic']);
        }
        if (!empty($data['thumb'])) {
            $data['thumb'] = $this->formatImgUrl($data['thumb']);
        }

        if (!empty($data['detail']['url'])) {
            foreach ($data['detail']['url'] as $key => $val) {
                $data['detail']['url'][$key] = $this->formatImgUrl($val);
            }
            $data['detail'] = json_encode($data['detail']['url']);
        }
        if (!empty($data['detail_pic'])) {
            $data['detail_pic'] = $this->formatImgUrl($data['detail_pic']);

        }

        $price = AlbumProductPriceModel::where('product_id', request('id'))->get();
        foreach ($price as $p) {
            $p->cat_id = $data['cat_id'];
            $p->name = $data['name'];
        }
        $ok = $this->repository->update(request('id'), $data);
        if ($ok) {
            $url[] = array('url' => U('Album/Product/index'), 'title' => '返回列表');
            return $this->showMessage('操作成功', urldecode(request('_referer')));
        } else {
            $url[] = array('url' => U('Album/Product/index'), 'title' => '返回列表');
            return $this->showWarning('操作失败', $url);

        }
    }

    public function view(Request $request)
    {
        $data = $this->repository->find(request('id'));
        return view('admin.album.product.view', compact('data'));
    }


    /**
     *
     * 状态改变
     *
     */
    public function status(Request $request)
    {
        $ok = $this->repository->updateStatus(request('id'), request('status'));
        if ($ok) {
            return $this->showMessage('操作成功');
        } else {
            return $this->showWarning('操作失败');
        }
    }

    /**
     * 删除
     */
    public function destroy(Request $request)
    {
        //$bool = $this->repository->destroy($request->get('id'));
        $cat = AlbumProductModel::find($request->get('id'));
        $ok = $cat->delete();
        if ($ok) {
            return  $this->showMessage('操作成功');
        } else {
            return  $this->showWarning("操作失败");
        }
    }
}