<?php
namespace App\Http\Controllers\Common;

use App\Models\ServiceMode;
use App\Services\CategoryService;
use App\Services\ServiceModeService;
use Illuminate\Http\Request;
use App\Models\CategoryName;
use App\Models\CategoryDetail;
use App\Services\CommonService;
use BlueCity\Core\Inc\ErrorInc;
use DB;
use App\Http\Controllers\BaseController;
//use Illuminate\Support\Facades\Redis;
use GuzzleHttp\json_encode;
use App\Services\BmmcService;
use App\Services\RedisService;
//通用方法控制器
class CategoryDetailController extends BaseController
{
	 /**
	  * 类目列表
	  * @param Request $request
	  * @author du 2021年7月15日下午2:52:42
	  */
     public function index(Request $request){
     	$page_size = (int)$request->input('page_size',20);
     	$page = (int)$request->input('page',1);
     	if($page<1){
     		$page = 1;
     	}
     	$paginate = CategoryName::orderBy('cn_id','ASC')->paginate($page_size);
     	$list = self::dataToArray($paginate->items());

     	$all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'));

     	$export = BmmcService::getTopButton('addCategoryName','', $all_button);
     	$data['button_top'] = $export['button_top']??[];//顶部按钮
     	$data['button_search'] = $export['button_search']??[];//搜索栏按钮

     	if ($list){

     		foreach ($list as $k=>$v){
     			$button = [];
     			 if ($v['cn_del_flag'] == 1){
                	$button[] = "editCategoryNameDelFlag";
                }elseif($v['cn_del_flag'] == 2){
                	$button[] = "editCategoryNameDelFlagQ";
                }
                $button[] = "editCategoryName";

     			$button = BmmcService::getListButton($button,$all_button);

     			$list[$k]['button_one'] = $button['button_one']??[];
     			$list[$k]['button_two'] = $button['button_two']??[];
     			$list[$k]['button_three'] = $button['button_three']??[];

     		}
     		//返回数据
     		$data['list'] = $list;


     		$data['page'] = [
     			'count' => $paginate->total(),
                'page'=>$paginate->currentPage(),
                'page_size'=>$page_size,
                'allPage'=>$paginate->lastPage()
     		];
     		return $this->success('获取成功', $data);
     	}else{
     		return $this->error('暂无数据', ErrorInc::DATA_EMPTY, $data);
     	}



     }

     /**
      * 添加类目
      * @param string cn_cname 类目名
      * @param string cn_remark 备注
      * @param Request $request
      * @return \BlueCity\Core\Controllers\mixed
      * @author du 2021年7月15日下午3:22:43
      */
     public function addCategoryName(Request $request){

     	if(!$request->filled('cn_cname')){
     		return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
     	}

     	$cn_name = trim($request->input('cn_cname'));

     	$exists = CategoryName::where('cn_cname',$cn_name)->value('cn_id');

     	if($exists){
     		return $this->error('已存在请重新填写', ErrorInc::MYSQL_FAILED, []);
     	}
     	if($request->filled('cn_remark')){
     		$dataArr['cn_remark'] = $request->input('cn_remark');
     	}


     	$dataArr['cn_cname'] = $cn_name;
     	$dataArr['cn_admin_id'] = $request->get('session_token')['id'];
     	$dataArr['cn_creat_time'] = date("Y-m-d H:i:s");

     	$res = CategoryName::insert($dataArr);
     	if($res){
     		//更新redis内容
     		$cnLists = $this->cnList();
     		$cnList = json_encode($cnLists);
     		RedisService::redisSet('cnList',$cnList);

     		$this->insertingLog('添加，','',$cn_name,'品类管理',$request->ip(),$request->get('session_token')['admin_acc']);

     		return $this->success('添加成功', []);
     	}else{
     		return $this->error('添加失败', ErrorInc::MYSQL_FAILED, []);
     	}

     }
     /**
      * 编辑类目
      * @param Request $request
      * @return \BlueCity\Core\Controllers\mixed
      * @author du 2021年7月15日下午5:57:01
      */
     public function editCategoryName(Request $request){
     	if(!$request->filled('cn_cname')||!$request->filled('id')){
     		return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
     	}

     	$cn_name = trim($request->input('cn_cname'));
     	$id = intval($request->input('id'));
     	$exists = CategoryName::where('cn_cname',$cn_name)->value('cn_id');

     	if($exists){
     		return $this->error('已存在请重新填写', ErrorInc::MYSQL_FAILED, []);
     	}

     	$dataArr['cn_remark'] = $request->input('cn_remark')??'';
     	$dataArr['cn_cname'] = $cn_name;
     	$dataArr['cn_admin_id'] = $request->get('session_token')['id'];

     	$res = CategoryName::where('cn_id',$id)->update($dataArr);

     	if($res){
     		//更新redis内容
     		$cnLists = $this->cnList();
     		$cnList = json_encode($cnLists);
     		RedisService::redisSet('cnList',$cnList);
     		$this->insertingLog('编辑，','',$cn_name,'品类管理',$request->ip(),$request->get('session_token')['admin_acc']);
     		return $this->success('编辑成功', []);
     	}else{
     		return $this->error('编辑失败', ErrorInc::MYSQL_FAILED, []);
     	}
     }

     /**
      * 编辑类目启用停用
      * @param Request $request
      * @return \BlueCity\Core\Controllers\mixed
      * @author du 2021年7月16日上午11:03:51
      */
     public function editCategoryNameDelFlag(Request $request){


     	if(!$request->filled('id')){
     		return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
     	}
     	$id = intval($request->input('id'));

     	$del_flag = CategoryName::where('cn_id',$id)->value('cn_del_flag');

     	if ($del_flag == 1){
     		$poss['cn_del_flag'] = 2;
     	}elseif ($del_flag == 2){
     			$poss['cn_del_flag'] = 1;
     	}
     	$res = CategoryName::where('cn_id',$id)->update($poss);
     	if($res){
     		$this->insertingLog('编辑类目开关','',$id,'品类管理',$request->ip(),$request->get('session_token')['admin_acc']);
     		return $this->success('操作成功', []);
     	}else{
     		return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);
     	}

     }


     /**
      * 添加品类
      * @param Request $request
      * @return \BlueCity\Core\Controllers\mixed
      * @author du 2021年7月15日下午4:05:50
      */
     public function addCategoryDetali(Request $request){
     	$parameter = $request->only('cn_id','cd_pname','cd_nextlevel','sm_ids');
     	$checkKey = CommonService::checkKey(['cn_id','cd_pname'],$parameter);
     	if($checkKey['code']!=1){
     		return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);exit;
     	}

     	$cd_pname = trim($request->input('cd_pname'));

     	$exists = CategoryDetail::where('cd_pname',$cd_pname)->value('cd_id');

     	if($exists){
     		return $this->error('已存在请重新填写', ErrorInc::MYSQL_FAILED, []);
     	}
     	if($request->filled('cd_remark')){
     		$dataArr['cd_remark'] = $request->input('cd_remark');
     	}

     	$dataArr['cd_cn_id'] = $request->input('cn_id');
     	$dataArr['cd_pname'] = $cd_pname;
     	$dataArr['cd_admin_id'] = $request->get('session_token')['id'];
     	$dataArr['cd_creat_time'] = date("Y-m-d H:i:s");
     	$dataArr['cd_nextlevel'] = $parameter['cd_nextlevel']??2;//是否可添加下级1是2否
         if(is_array($parameter['sm_ids'])){
             $dataArr['sm_ids'] = implode(',', $parameter['sm_ids']);
         }else{
             $dataArr['sm_ids'] = $parameter['sm_ids'];
         }


         $res = CategoryDetail::insert($dataArr);
     	if($res){
     		//更新redis内容
//     		$cdLists = $this->cdList();
//     		$cdList = json_encode($cdLists);
//     		RedisService::redisSet('cdList',$cdList);
            CategoryService::getall([],'',false);

     		$this->insertingLog('添加品类，','',$cd_pname,'品类管理',$request->ip(),$request->get('session_token')['admin_acc']);
     		return $this->success('添加成功', []);
     	}else{
     		return $this->error('添加失败', ErrorInc::MYSQL_FAILED, []);
     	}
     }

     /**
      * 编辑品类
      * @param Request $request
      * @return \BlueCity\Core\Controllers\mixed
      * @author du 2021年7月16日上午10:18:13
      */
     public function editTegoryDetali(Request $request){
     	$parameter = $request->only('id','cd_pname','cn_id','cd_nextlevel','sm_ids');
     	$checkKey = CommonService::checkKey(['id','cd_pname','cn_id'],$parameter);
     	if($checkKey['code']!=1){
     		return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM, []);exit;
     	}

     	$id = $request->input('id');
     	$cn_id = $request->input('cn_id');
     	$cd_pname = trim($request->input('cd_pname'));

     	/*$exists = CategoryDetail::where('cd_pname',$cd_pname)->where()->value('cd_id');
     	if($exists){
     		return $this->error('已存在请重新填写', ErrorInc::MYSQL_FAILED, []);
     	}*/
     	$dataArr['cd_remark'] = $request->input('cd_remark');
     	$dataArr['cd_cn_id'] = $cn_id;
     	$dataArr['cd_pname'] = $cd_pname;
     	$dataArr['cd_admin_id'] = $request->get('session_token')['id'];
         if(is_array($parameter['sm_ids'])){
             $dataArr['sm_ids'] = implode(',', $parameter['sm_ids']);
         }else{
             $dataArr['sm_ids'] = $parameter['sm_ids'];
         }
     	if($request->filled('cd_nextlevel')){
            $dataArr['cd_nextlevel'] = $request->input('cd_nextlevel');
        }
     	$res = CategoryDetail::where('cd_id',$id)->update($dataArr);
     	if($res){
     		//更新redis内容
//     		$cdLists = $this->cdList();
//     		$cdList = json_encode($cdLists);
//     		RedisService::redisSet('cdList',$cdList);
            CategoryService::getall([],'',false);

     		$this->insertingLog('编辑品类，','',$cd_pname,'品类管理',$request->ip(),$request->get('session_token')['admin_acc']);
     		return $this->success('编辑成功', []);
     	}else{
     		return $this->error('编辑失败', ErrorInc::MYSQL_FAILED, []);
     	}

     }

     /**
      * 编辑品类启用停用
      * @param Request $request
      * @return \BlueCity\Core\Controllers\mixed
      * @author du 2021年7月16日下午1:35:30
      */
     public function editTegoryDetaliDelfalg(Request $request){
     	if(!$request->filled('id')){
     		return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
     	}
     	$id = intval($request->input('id'));

     	$del_flag = CategoryDetail::where('cd_id',$id)->value('cd_del_flag');

     	if ($del_flag == 1){
     		$poss['cd_del_flag'] = 2;
     	}elseif ($del_flag == 2){
     		$poss['cd_del_flag'] = 1;
     	}
     	$res = CategoryDetail::where('cd_id',$id)->update($poss);
     	if($res){
            CategoryService::getall([],'',false);
     		$this->insertingLog('编辑品类开关','',$id,'品类管理',$request->ip(),$request->get('session_token')['admin_acc']);
     		return $this->success('操作成功', []);
     	}else{
     		return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);
     	}
     }

    /**
     * 品类列表
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月16日上午9:55:24
     */
	public function categoryDetaliList(Request $request){
		$categoryDetali = new CategoryDetail();
		if($request->filled('cd_pname')){
			$categoryDetali = $categoryDetali->where('cd_pname','like','%'.$request->input('cd_pname').'%');
		}
		$page_size = (int)$request->input('page_size',20);
     	$page = (int)$request->input('page',1);
     	if($page<1){
     		$page = 1;
     	}
     	$categoryDetali = $categoryDetali->leftJoin('category_name','category_name.cn_id','=','category_detail.cd_cn_id');
     	$paginate = $categoryDetali->select('category_detail.*','category_name.cn_cname')->orderBy('cd_del_flag','ASC')->orderBy('cd_id','ASC')->paginate($page_size);
     	$cdList = self::dataToArray($paginate->items());

     	$all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'));
     	$export = BmmcService::getTopButton('addCategoryDetali','', $all_button);
     	$data['button_top'] = $export['button_top']??[];//顶部按钮
     	$data['button_search'] = $export['button_search']??[];//搜索栏按钮

		if($cdList){
			foreach ($cdList as $k=>$v){
                if($v['sm_ids']){
                    $arr_modes = ServiceModeService::getall(explode(',', $v['sm_ids']));

                    $cdList[$k]['sm_ids'] = CommonService::strToint(explode(',', $v['sm_ids']));

                    $cdList[$k]['service_mode_names'] = implode(',', array_column($arr_modes, 'sm_name'));
                        //ServiceMode::whereIn('sm_id',explode(',', $v['sm_ids']))->pluck('sm_name');
                }else{
                    $cdList[$k]['service_mode_names'] = '';
                }

				$button = [];
				if ($v['cd_del_flag'] == 1){
					$button[] = "editTegoryDetaliDelfalg";
				}elseif($v['cd_del_flag'] == 2){
					$button[] = "editTegoryDetaliDelfalgQ";
				}
				$button[] = "editTegoryDetali";

				$button = BmmcService::getListButton($button,$all_button);

				$cdList[$k]['button_one'] = $button['button_one']??[];
				$cdList[$k]['button_two'] = $button['button_two']??[];
				$cdList[$k]['button_three'] = $button['button_three']??[];
			}


			$data['list'] = $cdList;
			$data['page'] = [
					'count' => $paginate->total(),
					'page'=>$paginate->currentPage(),
					'page_size'=>$page_size,
					'allPage'=>$paginate->lastPage()
			];
			return $this->success('获取成功', $data);
		}else{
			return $this->error('暂无数据', ErrorInc::DATA_EMPTY, $data);
		}

     }

     /**
      * 获取品类
      * @return \BlueCity\Core\Controllers\mixed
      * @author du 2021年7月16日下午3:28:11
      */
     public function cdSearchList(){

     	if(RedisService::redisGet('cdList')){
     		//echo 1;
     		$cdList = RedisService::redisGet('cdList');
     		return $this->success('获取成功', $cdList);
     		//return $cdList;
     	}else{
     		//echo 2;
//     		$cdLists = $this->cdList();
//     		$cdList = json_encode($cdLists);
//     		RedisService::redisSet('cdList',$cdList);
            $cdLists = CategoryService::getall([],'',false);
     		return $this->success('获取成功',$cdLists);
     	}
     }

     /**
      * 所有品类数据
      * @return array
      * @author du 2021年7月16日下午3:16:43
      */
     public function cdList(){
     	$data = CategoryDetail::where('cd_del_flag',1)->select('cd_id','cd_cn_id','cd_pname','cd_nextlevel','sm_ids')->orderBy('cd_id','DESC')->get();
     	return $data;
     }
     /**
      * 获取搜索类目
      * @return \BlueCity\Core\Controllers\mixed
      * @author du 2021年7月22日下午1:41:28
      */
     public function cnListSearch(){
     	if(RedisService::redisGet('cnList')){
     		//echo 1;
     		$cnList = RedisService::redisGet('cnList');
     		return $this->success('获取成功', $cnList);

     	}else{
     		//echo 2;
     		$cnLists = $this->cnList();
     		$cnList = json_encode($cnLists);
     		RedisService::redisSet('cnList',$cnList);
     		return $this->success('获取成功',$cnLists);
     	}

     }

    /**
     * 所有类目数据
     * @return unknown
     * @author du 2021年7月22日下午1:42:05
     */
     public function cnList(){
     	$data = CategoryName::where('cn_del_flag',1)->select('cn_id','cn_cname')->orderBy('cn_id','DESC')->get();
     	return $data;
     }

}
