<?php
/**
 *  画册海报
 *  @author  system
 *  @version    1.0
 *  @date 2019-03-04 13:38:57
 *
 */
namespace App\Http\Controllers\Admin\Album;
use App\Http\Controllers\Admin\Controller;
use App\Repositories\Album\Criteria\PosterWhere;
use Illuminate\Http\Request;
use App\Services\OSS;
use App\Models\AlbumPosterModel;
use App\Repositories\Base\Criteria\OrderBy;
use App\Repositories\Album\Criteria\MultiWhere;
use App\Repositories\Album\PosterRepository;

class PosterController extends Controller
{
    private $repository;

    public function __construct(PosterRepository $repository)
    {
        if (!$this->repository) {
            $this->repository = $repository;
        }
    }

    function index(Request $request)
    {
        $search['keyword'] = $request->input('keyword');
        $query = $this->repository->pushCriteria(new PosterWhere($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.poster.index', compact('list'));
    }

    /**
     * 添加
     *
     */
    public function create(Request $request)
    {
        if ($request->method() == 'POST') {
            return $this->_createSave();
        }
        return view('admin.album.poster.edit');
    }

    private function _createSave()
    {
        $data = (array) request('data');
        if (request()->file('video_url')) {
            $data['video_url'] = $this->uploadVideo(request()->file('video_url'), '');
        }
        if (!empty($data['posters']['url'])) {
            foreach ($data['posters']['url'] as $key => $val) {
                $data['posters']['url'][$key] = $this->formatImgUrl($val);
            }
            $data['posters'] = json_encode($data['posters']['url']);
        }
        $data['store_id'] = $this->getStoreId();
        /*if (empty($data['qrcode'])) {
            return $this->showMessage('分享海报或者二维码不能为空！');
        }
        $data['qrcode'] = $this->formatImgUrl($data['qrcode']);*/


        $ok = $this->repository->create($data);

        if ($ok) {
            return $this->showMessage('操作成功');
        } else {
            return $this->showMessage('操作失败');
        }
    }

    /**
     * 修改
     */
    public function update(Request $request)
    {
        if ($request->method() == 'POST') {
            return $this->updateSave();
        }
        $data = $this->repository->findWhere(['id' => $request->input('id')])->toArray();
        if (!empty($data)) {
            $data = $data[0];
            $data['posters'] = json_decode($data['posters'], true);
            $data['video_url'] = json_decode($data['video_url'], true);
            $data['video_url'] = $data['video_url']['url'];
        }
        return view('admin.album.poster.edit', compact('data'));
    }

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

        if (request()->file('video_url')) {
            $data['video_url'] = $this->uploadVideo(request()->file('video_url'), request('id'));
        }
        if (!empty($data['posters']['url'])) {
            foreach ($data['posters']['url'] as $key => $val) {
                $data['posters']['url'][$key] = $this->formatImgUrl($val);
            }
            $data['posters'] = json_encode($data['posters']['url']);
        }

       /* if (empty($data['qrcode'])) {
            return $this->showMessage('分享海报或者二维码不能为空！');
        }
        $data['qrcode'] = $this->formatImgUrl($data['qrcode']);*/

        $id = request('id');

        $ok = $this->repository->update($id, $data);

        if ($ok) {
            return $this->showMessage('操作成功');
        } else {
            return $this->showMessage('操作失败');
        }
    }

    public function uploadVideo($video, $id)
    {
        // dd($video);
// 判断图片有效性
        if (!$video) {
            return back()->withErrors('上传视频无效..');
        }
        if ($id) {
            $check = AlbumPosterModel::where([['id',$id]])->first();
            if ($check) {
                $res = json_decode($check->video_url, 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 viewPoster(Request $request)
    {
        $img = '/base/img/poster.jpg';
        return view('admin.album.poster.view', compact('img'));
    }
    /**
     * 删除
     */
    public function destroy(Request $request)
    {
        //$bool = $this->repository->destroy($request->get('id'));
        $cat = AlbumPosterModel::find($request->get('id'));
        $res = json_decode($cat->video_url, true);
        if ($res != '') {
            OSS::publicDeleteObject(config('alioss.BucketName'), $res['oss_key']);
        }
        $ok = $cat->delete();
        if ($ok) {
            return  $this->showMessage('操作成功');
        } else {
            return  $this->showWarning("操作失败");
        }
    }
}