<?php

namespace App\Http\Controllers\Mounting\BasicManage;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Mounting\Verify\BasicManage\VerifyWorkVerificationController;
use Illuminate\Support\Facades\DB;
use App\Http\Models\Api\Common;

// 作品管理
class WorkManagementController extends Controller
{
    protected $show_count = 10;

    //绩效考核列表
    public function index(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkVerificationController;
        $error_message = $verify_data->indexValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        $search_data = $request->all();
        $list_data = DB::table('wash_production_manage')
            ->where('prma_cid', $user_info->adm_cid)
            ->where('prma_shop_id', $user_info->adm_shop_id)
            ->where('prma_type', $request['prma_type'])
            ->where('prma_delete', 1)
            ->where(function($query) use($search_data) {
                if (!empty($search_data['prma_name'])) {
                    $query->where('prma_name', 'like', '%'.$search_data['prma_name'].'%' );
                }
            })
            ->where(function($query) use($search_data) {
                if (!empty($search_data['prma_state'])) {
                    $query->where('prma_state', $search_data['prma_state']);
                }
            })
            ->select('prma_id', 'prma_name', 'prma_remark', 'prma_state', 'prma_create_time')
            ->orderBy('prma_id', 'desc')
            ->paginate($this->show_count);
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $data_info['data'] = $list_data->items();                //返回数据

        // 获取当前列表下的按钮
        $list_button = getListButton($request['api_token'], $request['pri_id']);
        if($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info, 'list_button'=>$list_button]);
        }else{
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    //新增
    public function add(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkVerificationController;
        $error_message = $verify_data->addValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }
        
        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        
        $shop_id = $user_info->shop_superior_id ? $user_info->shop_superior_id : $user_info->adm_shop_id;
        if ($request['prma_type'] == 1) {
    		$hint = '作品分类';
            // 1. 判断分类名称是否存在
            $find_prma = DB::table('wash_production_manage')
                ->where('prma_delete', 1)
                ->where('prma_cid', $user_info->adm_cid)
                ->where('prma_shop_id', $user_info->adm_shop_id)
                ->where('prma_type', 1)
                ->where('prma_name', $request['prma_name'])
                ->select('prma_id')
                ->first();
            if ($find_prma) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$request['prma_name'].'分类名已存在']);
            }
        
            //新增一个分类名称
            $prma_add_data = [
                'prma_cid'=>$user_info->adm_cid,
                'prma_shop_id'=>$user_info->adm_shop_id,
                'prma_type'=>$request['prma_type'],
                'prma_name'=>$request['prma_name'],
                // 'prma_parent_id' => $request['prma_parent_id'],
                'prma_remark'=>$request->input('prma_remark', ''),
            ];
            // 新增分类名称
            $prma_res =  DB::table('wash_production_manage')->insert($prma_add_data);
    	} elseif($request['prma_type'] == 2) {
            //新增作品模块
    		$hint = '作品模块';
            //判断模块名称是否存在
            $find_prma = DB::table('wash_production_manage')
                ->where('prma_delete', 1)
                ->where('prma_cid', $user_info->adm_cid)
                ->where('prma_shop_id', $user_info->adm_shop_id)
                ->where('prma_type', 2)
                ->where('prma_name', $request['prma_name'])
                ->select('prma_id','prma_name')
                ->first();
            if ($find_prma) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$request['prma_name'].'模块名已存在']);
            }
            //新增一个模块名称
            $prma_add_data = [
                'prma_cid'=>$user_info->adm_cid,
                'prma_shop_id'=>$user_info->adm_shop_id,
                'prma_type'=>$request['prma_type'],
                'prma_name'=>$request['prma_name'],
                'prma_remark'=>$request->input('prma_remark', ''),
            ];
            // 新增模块名称
            $prma_res =  DB::table('wash_production_manage')->insert($prma_add_data);
    	} elseif($request['prma_type'] == 3) {
            //判断分类名是否存在
            $find_prma_name = DB::table('wash_production_manage')
            ->where('prma_name', $request['prma_name'])
            ->where('prma_type', 1)
            ->select('prma_id', 'prma_name')
            ->first();
            if (!$find_prma_name) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$request['prma_name'].'分类不存在']);
            }
            //新增作品
            $hint = '视频';
            //判断作品标题是否存在
            $find_prma = DB::table('wash_production_content')
            ->where('prco_delete', 1)
            ->where('prco_cid', $user_info->adm_cid)
            ->where('prco_shop_id', $user_info->adm_shop_id)
            ->where('prco_type', 1)
            ->where('prco_name', $request['prco_name'])
            ->select('prco_id','prco_name')
            ->first();
            if ($find_prma) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$request['prco_name'].'标题名已存在']);
            }
            //新增一个标题名称
            $prco_add_data = [
                'prco_cid'=>$user_info->adm_cid,
                'prco_shop_id'=>$user_info->adm_shop_id,
                'prco_name'=>$request['prco_name'],
                'prco_content'=>$request['prco_content'],
                'prco_remark'=>$request->input('prco_remark', ''),
            ];
            // 新增标题名称
            $prma_res =  DB::table('wash_production_content')->insert($prco_add_data);
        } elseif ($request['prma_type'] == 4) {
            //判断分类名是否存在
            $find_prma_name = DB::table('wash_production_manage')
            ->where('prma_name', $request['prma_name'])
            ->where('prma_type', 1)
            ->select('prma_id', 'prma_name')
            ->first();
            if (!$find_prma_name) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$request['prma_name'].'分类不存在']);
            }
            //新增图文内容
            $hint = '图文';
            //判断标题名称是否存在
            $find_prma = DB::table('wash_production_content')
                ->where('prco_delete', 1)
                ->where('prco_cid', $user_info->adm_cid)
                ->where('prco_shop_id', $user_info->adm_shop_id)
                ->where('prco_type', 1)
                ->where('prco_name', $request['prco_name'])
                ->select('prco_id','prco_name')
                ->first();
            if ($find_prma) {
                return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$request['prco_name'].'标题名已存在']);
            }
            //新增一个图文内容
            $prco_add_data = [
                'prco_cid'=>$user_info->adm_cid,
                'prco_shop_id'=>$user_info->adm_shop_id,
                'prco_name'=>$request['prco_name'],
                'prco_content'=>$request['prco_content'],
                'prco_remark'=>$request->input('prco_remark', ''),
            ];
            // 新增图文内容
            $prma_res =  DB::table('wash_production_content')->insert($prco_add_data);
        }
        if ($prma_res) {
            Common::addLog($user_info, getRealIp($request), '作品分类', '新增', '新增'.$hint.':'.$request['prma_name'].'成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'新增'.$hint.'：新增成功']);
        }else{
            return response()->json(['code'=>500,'msg'=>'error','data'=>'新增'.$hint.'：新增失败']);
        }
    }

    //编辑
    public function edit(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkVerificationController;
        $error_message = $verify_data->editValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);
        if ($request['prma_type'] == 1) {
    		$hint = '作品分类';
    	} elseif ($request['prma_type'] == 2) {
    		$hint = '作品模块';
    	}

        //判断分类名称是否存在
        $find_prma = DB::table('wash_production_manage')
            ->where('prma_id', '<>', $request['prma_id'])
            ->where('prma_delete', 1)
            ->where('prma_cid', $user_info->adm_cid)
            ->where('prma_shop_id', $user_info->adm_shop_id)
            ->where('prma_type', $request['prma_type'])
            ->where('prma_name', $request['prma_name'])
            ->select('prma_id')
            ->first();
        if ($find_prma) {
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>$request['prma_name'].'已存在']);
        }

        //编辑作品分类数据
        $prma_edit_data = [
            'prma_cid'=>$user_info->adm_cid,
            'prma_shop_id'=>$user_info->adm_shop_id,
            'prma_type'=>$request['prma_type'],
            'prma_name'=>$request['prma_name'],
            'prma_remark'=>$request->input('prma_remark', ''),
            'prma_update_time'=>date('Y-m-d H:i:s'),
        ];

        // 编辑分类数据
        $prma_res =  DB::table('wash_production_manage')
                    ->where('prma_id', $request['prma_id'])
                    ->update($prma_edit_data);

        if ($prma_res) {
            Common::addLog($user_info, getRealIp($request), '作品分类', '编辑', '编辑'.$hint.'：'.$request['prma_name'].'成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'编辑'.$hint.'：成功']);
        }else{
            return response()->json(['code'=>500,'msg'=>'error','data'=>'编辑'.$hint.'：失败']);
        }
    }

    //启用
    public function start(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkVerificationController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询信息
        $find_prma = DB::table('wash_production_manage')
                    ->whereIn('prma_id',$request['prma_id'])
                    ->select('prma_name')
                    ->get();
        foreach ($find_prma as $key => $value) {
            $prma_name[] = $value->prma_name;
        }

        // 启用
        $update_data['prma_state'] = 1;//状态1启用2停用
        $update_data['prma_update_time'] = date('Y-m-d H:i:s');
        $prma_res = DB::table('wash_production_manage')
                    ->whereIn('prma_id', $request['prma_id'])
                    ->update($update_data);
        if($prma_res) {
	    	if ($request['prma_type'] == 1) {
	    		$hint = '作品分类';
	    	} else if ($request['prma_type'] == 2) {
	    		$hint = '作品模块';
	    	}
            Common::addLog($user_info, getRealIp($request), '作品分类', '启用', $hint.'：（'.implode(',', $prma_name).'）启用成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'启用成功']);
        }else{
            return response()->json(['code'=>500,'msg'=>'error','data'=>'启用失败']);
        }
    }

    //启用(视频图文)
    public function ivstart(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkVerificationController;
        $error_message = $verify_data->ivstartValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询信息
        $find_prma = DB::table('wash_production_content')
                    ->whereIn('prco_id',$request['prco_id'])
                    ->select('prco_name')
                    ->get();
        foreach ($find_prma as $key => $value) {
            $prco_name[] = $value->prco_name;
        }

        // 启用
        $update_data['prco_state'] = 1;//状态1启用2停用
        $update_data['prco_update_time'] = date('Y-m-d H:i:s');
        $prma_res = DB::table('wash_production_content')
                    ->whereIn('prco_id', $request['prco_id'])
                    ->update($update_data);
        if($prma_res) {
	    	if ($request['prma_type'] == 3) {
	    		$hint = '视频';
	    	} else if ($request['prma_type'] == 4) {
	    		$hint = '图文';
	    	}
            Common::addLog($user_info, getRealIp($request), '作品分类', '启用', $hint.'：（'.implode(',', $prco_name).'）启用成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'启用成功']);
        }else{
            return response()->json(['code'=>500,'msg'=>'error','data'=>'启用失败']);
        }
    }
    //停用
    public function stop(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkVerificationController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询信息
        $find_prma = DB::table('wash_production_manage')
                    ->whereIn('prma_id',$request['prma_id'])
                    ->select('prma_name')
                    ->get();
        foreach ($find_prma as $key => $value) {
            $prma_name[] = $value->prma_name;
        }

        // 停用
        $update_data['prma_state'] = 2;//状态1启用2停用
        $update_data['prma_update_time'] = date('Y-m-d H:i:s');
        $prma_res = DB::table('wash_production_manage')
                    ->whereIn('prma_id', $request['prma_id'])
                    ->update($update_data);
        if($prma_res) {
            if ($request['prma_type'] == 1) {
                $hint = '作品分类';
            } else if ($request['prma_type'] == 2) {
                $hint = '作品模块';
            }
            Common::addLog($user_info, getRealIp($request), '作品分类', '停用', $hint.'：（'.implode(',', $prma_name).'）停用成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'停用成功']);
        }else{
            return response()->json(['code'=>500,'msg'=>'error','data'=>'停用失败']);
        }
    }

    //停用(视频图文)
    public function ivstop(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkVerificationController;
        $error_message = $verify_data->ivstartValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询信息
        $find_prma = DB::table('wash_production_content')
                    ->whereIn('prco_id',$request['prco_id'])
                    ->select('prco_name')
                    ->get();
        foreach ($find_prma as $key => $value) {
            $prco_name[] = $value->prco_name;
        }

        // 停用
        $update_data['prco_state'] = 2;//状态1启用2停用
        $update_data['prco_update_time'] = date('Y-m-d H:i:s');
        $prma_res = DB::table('wash_production_content')
                    ->whereIn('prco_id', $request['prco_id'])
                    ->update($update_data);
        if($prma_res) {
            if ($request['prma_type'] == 3) {
                $hint = '视频';
            } else if ($request['prma_type'] == 4) {
                $hint = '图文';
            }
            Common::addLog($user_info, getRealIp($request), '作品分类', '停用', $hint.'：（'.implode(',', $prco_name).'）停用成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'停用成功']);
        }else{
            return response()->json(['code'=>500,'msg'=>'error','data'=>'停用失败']);
        }
    }

    //删除
    public function delete(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkVerificationController;
        $error_message = $verify_data->startValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        // 获取当前操作账号信息
        $user_info = Common::getUserInfo($request['api_token']);

        // 查询信息
        $find_prma = DB::table('wash_production_manage')
                    ->whereIn('prma_id',$request['prma_id'])
                    ->select('prma_name')
                    ->get();
        foreach ($find_prma as $key => $value) {
            $prma_name[] = $value->prma_name;
        }

        // 删除
        $update_data['prma_delete'] = 2;//是否删除：1正常2已删除
        $update_data['prma_update_time'] = date('Y-m-d H:i:s');
        $prma_res = DB::table('wash_production_manage')
                    ->whereIn('prma_id', $request['prma_id'])
                    ->update($update_data);

        if($prma_res) {
            if ($request['prma_type'] == 1) {
                $hint = '作品分类';
            } else if ($request['prma_type'] == 2) {
                $hint = '作品模块';
            }

            Common::addLog($user_info, getRealIp($request), '作品分类', '删除', $hint.'：（'.implode(',', $prma_name).'）删除成功');
            return response()->json(['code'=>200,'msg'=>'success','data'=>'删除成功']);
        }else{
            return response()->json(['code'=>500,'msg'=>'error','data'=>'删除失败']);
        }
    }

    // 搜索作品管理数据
    public function searchValidateCar(Request $request)
    {
        // 验证数据
        $verify_data = new VerifyWorkVerificationController;
        $error_message = $verify_data->searchValidateCarValidator($request->all());
        if ($error_message) {
            return response()->json(['code'=> 500, 'msg'=>'error', 'data'=>'参数错误', 'error_message'=>$error_message]);
        }

        $search_data = $request->all();
        $list_data = DB::table('wash_production_manage')
            ->where('prma_shop_id', $request['shop_id'])
            ->where('prma_type', $request['prma_type'])
            ->where('prma_delete', 1)
            ->where('prma_state', 1)
            ->where(function($query) use($search_data) {
                if (!empty($search_data['prma_name'])) {
                    $query->where('prma_name', 'like', '%'.$search_data['prma_name'].'%' );
                }
            })
            ->select('prma_id', 'prma_name')
            ->orderBy('prma_id', 'asc')
            ->paginate($this->show_count);
        $data_info['current_page'] = $list_data->currentPage();  //当前页面页码
        $data_info['last_page'] = $list_data->lastPage();        //表示最后一页的页码
        $data_info['total'] = $list_data->total();               //总数据个数
        $data_info['current_number'] = $this->show_count;       //一页显示多少个
        $data_info['data'] = $list_data->items();                //返回数据
        if($list_data) {
            return response()->json(['code'=>200, 'msg'=>'success', 'data'=>$data_info]);
        }else{
            return response()->json(['code'=>500, 'msg'=>'error', 'data'=>'暂无数据']);
        }
    }

    // 图片上传
    public function imageform(Request $request)
    {
        $image = $request['images'];
        $shop_id = $request['shop_id'];
        $imageName = time() . rand(11, 99) .rand(111, 999).'png'; //产生一个随机文件名
        // 当前文件根路径
        if(!empty($image)) {
            if (strstr($image,",")){
                $image = explode(',',$image);
                $image = $image[1];
            }

            $folder = $shop_id.date('/Y/m/d');
            $path =  storage_path() . '/app/public/image/'.$folder; //获取上传图片路径

            if (!is_dir($path)){//判断目录是否存在 不存在就创建
                mkdir($path,0777,true);
            }
            $imageSrc= $path."/". $imageName;  //图片名字
            $return_path = '/app/public/image/'.$folder.$imageName; //返回图片路径
            file_put_contents($imageSrc, base64_decode($image));//返回的是字节数
            return response()->json(["code"=>200,'msg'=>'success','data'=>'图片上传成功','path'=>$imageSrc,'return_path'=>$return_path]);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'还未选择图片']);
        }
    }

    // 删除图片
    public function delimageform(Request $request)
    {
        $image =  $request['images'];
        foreach($image as $k=>$v)
        {
            if(is_file($image[$k])){
                // 修改原图片权限
                chmod($image[$k],0777);
                // 删除原图片
                unlink($image[$k]); 
            }
        }
        return response()->json(["code"=>200,'msg'=>'success','data'=>'图片删除成功']);
    }

    //视频上传
    public function Videoupload(Request $request)
    {
        $video = $request['videos'];
        $shop_id = $request['shop_id'];
        $videoName = time() . rand(11, 99) .rand(111, 999).'mp4'; //产生一个随机文件名
        // 当前文件根路径
        if(!empty($video)) {
            if (strstr($video,",")){
                $video = explode(',',$video);
                $video = $video[1];
            }

            $folder = $shop_id.date('/Y/m/d');
            $path =  storage_path() . '/app/public/video/'.$folder; //获取上传视频路径

            if (!is_dir($path)){//判断目录是否存在 不存在就创建
                mkdir($path,0777,true);
            }
            $videoSrc= $path."/". $videoName;  //视频名字
            $return_path = '/app/public/video/'.$folder.$videoName; //返回视频路径
            file_put_contents($videoSrc, base64_decode($video));//返回的是字节数
            return response()->json(["code"=>200,'msg'=>'success','data'=>'视频上传成功','path'=>$videoSrc,'return_path'=>$return_path]);
        }else{
            return response()->json(["code"=>500,'msg'=>'error','data'=>'还未选择视频']);
        }
    }

    // 删除视频
    public function delVideoupload(Request $request)
    {
        $video =  $request['videos'];
        foreach($video as $k=>$v)
        {
            if(is_file($video[$k])){
                // 修改原视频权限
                chmod($video[$k],0777);
                // 删除原视频
                unlink($video[$k]); 
            }
        }
        return response()->json(["code"=>200,'msg'=>'success','data'=>'视频删除成功']);
    }
}