<?php
/**
 *  系统设置
 *  @author  system
 *  @version    1.0
 *  @date 2018-05-14 13:30:36
 *
 */
namespace App\Http\Controllers\Admin\Album;
use App\Http\Controllers\Admin\Controller;
use App\Models\AgentBannerModel;
use App\Models\AlbumManufacturerModel;
use App\Models\AlbumUserModel;
use App\Services\OSS;
use Illuminate\Http\Request;
use App\Repositories\Base\Criteria\OrderBy;
use App\Repositories\Album\Criteria\MultiWhere;
use App\Repositories\Album\ManufacturerRepository;

class ManufacturerController extends Controller
{
    private $repository;

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

    function list(Request $request){

        $search['keyword'] = $request->input('keyword');
        $isalbum = request('isalbum')?request('isalbum'):0;
        $query = $this->repository->pushCriteria(new MultiWhere($search));

        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']));
        }
        $list = $query->paginate(10);
        return view('admin.album.manufacturer.index',compact('list','isalbum'));
    }

    function index(Request $request)
    {
        if ($request->method() == 'POST') {
            $iscreate = AlbumManufacturerModel::where('store_id', $this->getStoreId())->first();
            if ($iscreate) {
                return $this->_updateSave();
            } else {
                return $this->_createSave();
            }

        }

        $data = AlbumManufacturerModel::where('store_id', $this->getStoreId())->first();
        if ($data) {
            $data['banner'] = json_decode($data['banner'], true);
        }
        $banner = AgentBannerModel::where([['store_id',$this->getStoreId()],['type',0]])->get();
        $imgs = array();
        foreach ($banner as $key => $val) {
            $imgs[] = $val['url'];
        }
        $data['agent_banner'] = $imgs;
        $video = AgentBannerModel::where([['store_id',$this->getStoreId()],['type',1]])->first();
        return view('admin.album.manufacturer.edit', compact('data', 'video'));
    }

    public function viewShare(Request $request)
    {
        $img = '/base/img/share.jpg';
        return view('admin.album.poster.view', compact('img'));
    }

    public function platform(Request $request)
    {
        if ($request->method() == 'POST') {
            $iscreate = AlbumManufacturerModel::where('store_id', $this->getStoreId())->first();
            if ($iscreate) {
                return $this->_updateSave();
            } else {
                return $this->_createSave();
            }
        }

        $data = AlbumManufacturerModel::where('store_id', $this->getStoreId())->first();
        if ($data) {
            $data['banner'] = json_decode($data['banner'], true);
        }
        $banner = AgentBannerModel::where([['store_id',$this->getStoreId()],['type',0]])->get();
        $imgs = array();
        foreach ($banner as $key => $val) {
            $imgs[] = $val['url'];
        }
        $data['agent_banner'] = $imgs;
        $video = AgentBannerModel::where([['store_id',$this->getStoreId()],['type',1]])->first();
        return view('admin.album.manufacturer.platform-edit', compact('data', 'video'));
    }

    public function furniturePlatform(Request $request)
    {
        if ($request->method() == 'POST') {
            $iscreate = AlbumManufacturerModel::where('store_id', $this->getStoreId())->first();
            if ($iscreate) {
                return $this->_updateSave();
            } else {
                return $this->_createSave();
            }
        }

        $data = AlbumManufacturerModel::where('store_id', $this->getStoreId())->first();
        if ($data) {
            $data['banner'] = json_decode($data['banner'], true);
        }
        return view('admin.album.manufacturer.furniture-platform', compact('data', 'video'));
    }

    public function furnitureSystem(Request $request)
    {
        if ($request->method() == 'POST') {
            $iscreate = AlbumManufacturerModel::where('store_id', $this->getStoreId())->first();
            if ($iscreate) {
                return $this->_updateSave();
            } else {
                return $this->_createSave();
            }
        }

        $data = AlbumManufacturerModel::where('store_id', $this->getStoreId())->first();
        return view('admin.album.manufacturer.furniture-system', compact('data', 'video'));
    }

    public function albumSystem(Request $request)
    {
        if ($request->method() == 'POST') {
            $iscreate = AlbumManufacturerModel::where('store_id', $this->getStoreId())->first();
            if ($iscreate) {
                return $this->_updateSave();
            } else {
                return $this->_createSave();
            }

        }

        $data = AlbumManufacturerModel::where('store_id', $this->getStoreId())->first();
        if ($data) {
            $data['banner'] = json_decode($data['banner'], true);
        }
        $banner = AgentBannerModel::where([['store_id',$this->getStoreId()],['type',0]])->get();
        $imgs = array();
        foreach ($banner as $key => $val) {
            $imgs[] = $val['url'];
        }
        $data['agent_banner'] = $imgs;
        $video = AgentBannerModel::where([['store_id',$this->getStoreId()],['type',1]])->first();
        return view('admin.album.manufacturer.album-edit', compact('data', 'video'));
    }
    
    function indexFurniture(Request $request) {
        if ($request->method() == 'POST') {
            $iscreate = AlbumManufacturerModel::where('store_id', $this->getStoreId())->first();
            if ($iscreate) {
                return $this->_updateSave();
            } else {
                return $this->_createSave();
            }

        }

        $data = AlbumManufacturerModel::where('store_id', $this->getStoreId())->first();
        if ($data) {
            $data['banner'] = json_decode($data['banner'], true);
        }
        return view('admin.album.manufacturer.edit-furniture', compact('data'));
    }

    function create(Request $request)
    {
        if ($request->method() == 'POST') {
            return $this->_createSave();
        }

        return view('admin.album.manufacturer.edit-all');
    }

    /**
     * 保存修改
     */
    private function _createSave(){
        $data = (array) request('data');
        $ma = AlbumManufacturerModel::where('id','!=',0)->orderByDesc('id')->first();

        $data['store_id'] =$ma->id+1;
        if (!empty($data['banner']['url'])) {
            foreach ($data['banner']['url'] as $key => $val) {
                $data['banner']['url'][$key] = $this->formatImgUrl($val);
            }
            $data['banner'] = json_encode($data['banner']['url']);
        }
        if (isset($data['banner_agent']['url'])) {
            $agent_banner = $data['banner_agent']['url'];
            unset($data['banner_agent']);
            if ($agent_banner) {
                foreach($agent_banner as $key => $val){
                    $add['url'] = $this->formatImgUrl($val);
                    $add['agent_id'] = request('id');
                    $add['type'] = 0;

                    AgentBannerModel::create($add);
                }
            }
        }

        if(!empty($data['avatar']))
            $data['avatar'] = $this->formatImgUrl($data['avatar']);
        if (!empty($data['logo'])) {
            $data['logo'] = $this->formatImgUrl($data['logo']);
        }
        if (!empty($data['qrcode'])) {
            $data['qrcode'] = $this->formatImgUrl($data['qrcode']);
        }
        if (!empty($data['share_image'])) {
            $data['share_image'] = $this->formatImgUrl($data['share_image']);
        }if (!empty($data['circleOfFriends'])) {
            $data['circleOfFriends'] = $this->formatImgUrl($data['circleOfFriends']);
        }
        if(!empty($data['background_pic']))
            $data['background_pic'] = $this->formatImgUrl($data['background_pic']);
        if(!empty($data['advertising_pic']))
            $data['advertising_pic'] = $this->formatImgUrl($data['advertising_pic']);
        if(!empty($data['notice_icon']))
            $data['notice_icon'] = $this->formatImgUrl($data['notice_icon']);
        if(!empty($data['furniture_ads_pic']))
            $data['furniture_ads_pic'] = $this->formatImgUrl($data['furniture_ads_pic']);

        $id = $this->repository->create($data);
        if ($id) {
            $this->showMessage('添加成功');
        } else {
            return $this->showWarning('添加失败');
        }
    }

    /**
     * 保存修改
     */
    private function _updateSave() {
        $data = (array) request('data');
       // dd($data);
        $saveData = AlbumManufacturerModel::where('store_id', $this->getStoreId())->first();
        if (!empty($data['avatar'])) {
            $data['avatar'] = $this->formatImgUrl($data['avatar']);
            //$this->deleteUrl($saveData->avatar);
        }

        $banner = AgentBannerModel::where([['store_id',$this->getStoreId()],['type',0]])->get();
        if($banner){
            foreach ($banner as $key=>$val){
                $url = str_replace(env('APP_URL'),public_path(),$val['url']);
                if(file_exists($url)) unlink($url);

            }
        }
        AgentBannerModel::where([['store_id',$this->getStoreId()],['type',0]])->delete();
        if(!empty($data['agent_banner']['url'])){
            foreach($data['agent_banner']['url'] as $key=>$val){
                $add['url'] = $this->formatImgUrl($val);
                $add['store_id'] = $this->getStoreId();
                $add['type'] = 0;
                AgentBannerModel::create($add);
            }

        }
        unset($data['agent_banner']);
        if (!empty($data['logo'])) {
            $data['logo'] = $this->formatImgUrl($data['logo']);
        }
        if (!empty($data['background_pic'])) {
            $data['background_pic'] = $this->formatImgUrl($data['background_pic']);
            //$this->deleteUrl($saveData->background_pic);
        }
        if (!empty($data['advertising_pic'])) {
            $data['advertising_pic'] = $this->formatImgUrl($data['advertising_pic']);
           // $this->deleteUrl($saveData->advertising_pic);
        }
        if (!empty($data['circleOfFriends'])) {
            $data['circleOfFriends'] = $this->formatImgUrl($data['circleOfFriends']);
           // $this->deleteUrl($saveData->advertising_pic);
        }
        if (!empty($data['share_image'])) {
            $data['share_image'] = $this->formatImgUrl($data['share_image']);
        }
        if (!empty($data['qrcode'])) {
            $data['qrcode'] = $this->formatImgUrl($data['qrcode']);
        }
        if (!empty($data['notice_icon'])) {
            $data['notice_icon'] = $this->formatImgUrl($data['notice_icon']);
           // $this->deleteUrl($saveData->notice_icon);
        }
        if (!empty($data['furniture_ads_pic'])) {
            $data['furniture_ads_pic'] = $this->formatImgUrl($data['furniture_ads_pic']);
           // $this->deleteUrl($saveData->furniture_ads_pic);
        }

        if (!empty($data['banner']['url'])) {
            foreach ($data['banner']['url'] as $key => $val) {
                $data['banner']['url'][$key] = $this->formatImgUrl($val);
            }
            $data['banner'] = json_encode($data['banner']['url']);
            /*$banner = json_decode($data['banner'], true);
            foreach ($banner as $val) {
                $this->deleteUrl($val);
            }*/
        }


        $id = $saveData->id;
        $ok = $this->repository->update($id,$data);
        if($ok) {
            return $this->showMessage('操作成功');
        }else{
            return $this->showWarning('操作失败');
        }
    }

    public function view(Request $request) {
        $data = $this->repository->find(request('id'));
        return view('admin.album.manufacturer.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'));
        if ($bool) {
            return  $this->showMessage('操作成功');
        } else {
            return  $this->showWarning("操作失败");
        }
    }

    public function uploadVideo(Request $request)
    {
        $video = $request->file('video');
// 判断图片有效性
        if (!$video) {
            return back()->withErrors('上传视频无效..');
        }
        $check = AgentBannerModel::where([['store_id',$this->getStoreId()],['type',1]])->first();
        if($check) OSS::publicDeleteObject(config('alioss.BucketName'),$check->oss_key);
// 获取图片在临时文件中的地址
        $videoPath = $video->getRealPath();

// 制作文件名
        $ex = $video->getClientOriginalExtension();
        $key = time() . rand(10000, 99999999) . '.' . $ex;
//阿里 OSS 文件上传
        $result = OSS::publicUpload(config('alioss.BucketName'), $key, $videoPath);
        if ($result) {
            $data['name'] = $video->getClientOriginalName();
            $data['type'] = 1;
            $data['store_id'] = $this->getStoreId();
            $data['oss_key'] =  $key;
            $data['url'] = config('alioss.FileUrl') . $key;
            $video = AgentBannerModel::create($data);
            if (!$video) {
                return back()->withErrors('上传视频失败..');
            }
            return  $this->showMessage('上传成功');

        } else {
            return back()->withErrors('上传视频失败..');
        }
    }
    public function videoDel(Request $request)
    {
        $check = AgentBannerModel::find($request->get('id'));
        if($check) $osskey = $check->oss_key;
        if(!$check) return  $this->showWarning("操作失败");
        $bool = AgentBannerModel::where('id',$request->get('id'))->delete();
        if($bool) {
            OSS::publicDeleteObject(config('alioss.BucketName'),$osskey);
            return  $this->showMessage('操作成功');
        }else{
            return  $this->showWarning("操作失败");
        }
    }
}