<?php
/**
 *  经销商管理
 *  @author  system
 *  @version    1.0
 *  @date 2018-05-14 13:26:07
 *
 */
namespace App\Http\Controllers\Admin\Album;
use App\Http\Controllers\Admin\Controller;
use App\Models\AgentBannerModel;
use App\Models\AlbumAgentModel;
use App\Models\AlbumProductPriceModel;
use App\Models\AlbumUserModel;
use App\Repositories\Album\Criteria\AgentWhere;
use App\Services\OSS;
use Illuminate\Http\Request;
use App\Repositories\Base\Criteria\OrderBy;
use App\Repositories\Album\Criteria\MultiWhere;
use App\Repositories\Album\AgentRepository;

class AgentController extends Controller
{
    private $repository;

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

    function index(Request $request) {
        $search['keyword'] = $request->input('keyword');
        $query = $this->repository->pushCriteria(new AgentWhere($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();
        foreach ($list as $item){
            $product = AlbumProductPriceModel::where([['agent_id',$item->id],['store_id',$this->getStoreId()]])->first();
            if(!empty($product)){
                $item->product_name = $product['mobile'];
            }

            $item->product_pic = $product['cover_pic'];
        }
        foreach ($list as $item){
            if($item->status == 0){
                $item->status = '待审核';
            }else{
                $item->status = '已审核';
            }
        }
        return view('admin.album.agent.index',compact('list'));
    }


    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.agent.check',compact('list'));
    }


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

    /**
     * 保存修改
     */
    private function _createSave(){
        $data = (array) request('data');
        $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);
            }
        }
        $id = $this->repository->create($data);
        if($id) {
            $url[] = array('url'=>U( 'Album/Agent/index'),'title'=>'返回列表');
            $url[] = array('url'=>U( 'Album/Agent/create'),'title'=>'继续添加');
            $this->showMessage('添加成功',$url);
        }else{
            $url[] = array('url'=>U( 'Album/Agent/index'),'title'=>'返回列表');
            return $this->showWarning('添加失败',$url);
        }
    }
    
    /**
     * 
     * 修改
     * 
     * 
     */
    public function update(Request $request) {
        if($request->method() == 'POST') {
            return $this->_updateSave();
        }
        $data = $this->repository->find($request->get('id'));
        $banner = AgentBannerModel::where([['agent_id',$data['id']],['type',0]])->get();
        $imgs = array();
        foreach($banner as $key=>$val){
            $imgs[] = $val['url'];
        }
        $data->agent_banner = $imgs;
        $video = AgentBannerModel::where([['agent_id',$request->get('id')],['type',1]])->first();
        return view('admin.album.agent.edit',compact('data','video'));
    }

    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("操作失败");
        }
    }
    /**
     * 保存修改
     */
    private function _updateSave() {
        $data = (array) request('data');//dd($data);
        $id = request('id');
        $banner = AgentBannerModel::where([['agent_id',$id],['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([['agent_id',$id],['type',0]])->delete();
        if(!empty($data['agent_banner']['url'])){
            foreach($data['agent_banner']['url'] as $key=>$val){
                $add['url'] = $this->formatImgUrl($val);
                $add['agent_id'] = $id;
                $add['type'] = 0;
                AgentBannerModel::create($add);
            }

        }
        unset($data['agent_banner']);
        $ok = $this->repository->update(request('id'),$data);
        if($ok) {
            $urls[] = array('url'=>U( 'Album/Agent/index'),'title'=>'返回列表');
            $this->showMessage('添加成功',$urls);
        }else{
            $urls[] = array('url'=>U( 'Album/Agent/index'),'title'=>'返回列表');
            return $this->showWarning('操作失败',$urls);
        }
    }

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


    /**
     *
     * 状态改变
     *
     */
    public function status(Request $request) {
        $ok = $this->repository->updateStatus(request('id'),request('status'));
        if(request('status')==1){
            $agent = AlbumAgentModel::find(request('id'));
            $user = AlbumUserModel::find($agent->user_id);
            $user->is_dealer = 1;
            $user->save();
        }
        if($ok) {
            return $this->showMessage('操作成功');
        }else{
            return $this->showWarning('操作失败');
        }
    }
    
    /**
     * 删除
     */
    public function destroy(Request $request) {
        $agent = AlbumAgentModel::find($request->get('id'));
        $id= $agent->user_id;
        $ok = $agent->delete();
        $save['is_dealer'] = 0;
        AlbumUserModel::where('id',$id)->update($save);
        if($ok) {
            return  $this->showMessage('操作成功');
        }else{
            return  $this->showWarning("操作失败");
        }
    }


    public function uploadVideo(Request $request)
    {
        $video = $request->file('video');
// 判断图片有效性
        if (!$video) {
            return back()->withErrors('上传视频无效..');
        }
        $agentid = $request->input('agent_id');
        $check = AgentBannerModel::where([['agent_id',$agentid],['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['agent_id'] = $agentid;
            $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('上传视频失败..');
        }
    }
}