<?php
namespace App\Http\Controllers\Common;
use App\Http\Controllers\BaseController;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\SetmoneyType;
use DB;
use Validator;
use BlueCity\Core\Inc\ErrorInc;
use App\Services\BmmcService;
use App\Services\LabtypeService;
use App\Services\CommonService;
use Illuminate\Support\Facades\Redis;
use App\Services\CategoryService;

/**
 * @name 标签管理
 * Class LabtypeController
 * @package App\Http\Controllers\Common
 */
class LabtypeController extends BaseController
{

	/**
	 * @name 列表
	 * @param cd_id   品类id
	 * @param sety_name    标签名
	 * @param lt_parent_id 父级标签
	 * @param lt_type 是否需要处理 : 1.需要 2.不需要
	 * @param Request $request
	 * @return \BlueCity\Core\Controllers\mixed
	 * @author du 2021年7月23日上午10:41:38
	 */
    public function index (Request $request)
    {
//        return self::test(0);//放在其它方法中作为启动方法使用
        $page_size = (int)$request->input('page_size',20);
        $page = (int)$request->input('page',1);
        if($page<1){
            $page = 1;
        }
        $DB = new SetmoneyType();//实例化模型
       if($request->filled('cd_id')){
       		$DB = $DB->where('cd_id',$request->input('cd_id'));
       }
       if($request->filled('lt_parent_id')){
       		$DB = $DB->where('lt_parent_id',$request->input('lt_parent_id'));
       }
       if($request->filled('lt_type')){
       		$DB = $DB->where('lt_type',$request->input('lt_type'));
       }
       if ($request->filled('sety_name')){//检验码
       		$DB = $DB->where('sety_name','like','%'.$request->input('sety_name').'%');
       }
        if($request->filled('lt_statues')){
            $DB = $DB->where('lt_statues',$request->input('lt_statues'));
        }
        //DB::connection()->enableQueryLog();
        $paginate = $DB->where('sety_type','3')->where('lt_statues',1)->where('lt_parent_id',0)->select('cd_id','sety_id','sety_name','sety_creacter','sety_time','sety_price','lt_type','lt_group','lt_ids','lt_statues','lt_parent_id')->orderBy('sety_id','DESC')->paginate($page_size);
        $list = self::dataToArray($paginate->items());
        //print_r(DB::getQueryLog());
        if ($list){
        	$all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'));
        	$export = BmmcService::getTopButton('addLab','', $all_button);
        	$data['button_top'] = $export['button_top']??[];//顶部按钮
        	$data['button_search'] = $export['button_search']??[];//搜索栏按钮

           $cdInfo = CategoryService::getall([],'cd_id');
           $alltoparray = LabtypeService::labelListTree();
           $alltoparray = CommonService::jointArrayKey($alltoparray,'sety_id');
           //dump($cdInfo);exit;

            foreach ($list as $k=>$v){
                $list[$k]['level'] = count(explode(',', $v['lt_ids']));
                $button = BmmcService::getListButton(['editLab','labtype','copyNew'],$all_button);
                $list[$k]['button_one'] = $button['button_one']??[];
                $list[$k]['button_two'] = $button['button_two']??[];
                $list[$k]['button_three'] = $button['button_three']??[];

                //品类名
                if($v['cd_id']){
                	$list[$k]['cd_name'] = $cdInfo[$v['cd_id']]['cd_pname']??'';
                }

                if ($v['lt_statues'] == 1){
                    $list[$k]['lt_statues_name'] = "显示";
                }else{
                    $list[$k]['lt_statues_name'] = "不显示";
                }
                if ($v['lt_type'] == 1){
                    $list[$k]['lt_type_name'] = "需要处理";
                }else{
                    $list[$k]['lt_type_name'] = "不需要处理";
                }
                $list[$k]['parent_names'] = '';
                if(isset($alltoparray[$v['sety_id']]['children'])){
	                $lt_children = $alltoparray[$v['sety_id']]['children'];
                	$list[$k]['children'] = LabtypeService::addButton($lt_children,$button,$cdInfo);
            	}else{
	            	$list[$k]['children'] = [];
            	}
            }

            //$list = array_slice($list,$offset,$page_size);//截取数组
          	$data['list'] = $list;
     		$data['page'] = [
     			'count' => $paginate->total(),
                'page'=>$paginate->currentPage(),
                'page_size'=>$page_size,
                'allPage'=>$paginate->lastPage()
     		];
     		return $this->success('获取成功', $data);exit;

        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY, []);exit;
        }
    }


    /**
     * @name 获取树状列表(搜索下拉用)
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年7月23日下午4:15:22
     */
    public function infoTree (Request $request)
    {
        $list = LabtypeService::labelTree();
        $where[] = array('sety_type'=>'3');
        $list = CommonService::arrayFilterFieldValue($list,$where);
        $list = CommonService::resetListKey($list);
        if($list){
        	return $this->success('获取成功',$list);exit;
        }else{
        	return $this->error('暂无数据', ErrorInc::DATA_EMPTY, []);exit;
        }

    }

    /**|---------------------------------------------------------------------------------
     * @name 获取显示范围
     * @param sety_id  id号
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
    public function getInfo (Request $request)
    {
        if ($request->filled('sety_id')){
            //$sety_id = $request->input('sety_id');
            //$Db = $Db->where('sety_id',$sety_id);
            $bmmc = SetmoneyType::where('sety_id',$request->input('sety_id'))->select('lt_group')->first();
            $lt_parent_id = SetmoneyType::where('sety_id',$request->input('sety_id'))->value('lt_parent_id');
            $sety_name = SetmoneyType::where('sety_id',$lt_parent_id)->value('sety_name');
            $data['sety_name'] = $sety_name??'顶级标签';
            $lt_group = explode(',',$bmmc['lt_group']);
            $lt_groups = [];
            foreach ($lt_group as $k => $v){
                $lt_groups[]=(int)$v;
            }
            $data['lt_group'] = $lt_groups;
        }

        $bmmc = BmmcService::getBmmc($request->get('session_token'),$request->input('Pri_id'),'list');
        $list = $bmmc['data'];
        $data['list'] = $list;
        if ($list){
            return response()->json(['Data'=>$data,'ErrorCode'=>1,'ErrorMessage'=>'成功']);exit;
        }else{
            return response()->json(['Data'=>'','ErrorCode'=>2,'ErrorMessage'=>'暂无数据']);exit;
        }
    }


    /**
     * @name 添加标签
     * @param sety_name    标签名称
     * @param lt_parent_id 父标签id号
     * @param sety_price   标签价格
     * @param lt_group     显示范围 逗号分隔　6,8,9
     * @param cd_id   品类ID
     * @param lt_score 分数
     * @param lt_statues 1:显示　2:不显示
     * @param lt_type 是否需要处理 : 1.需要 2.不需要
     * @param lt_ids 父标签id串
     * @param Request $request
     * @param gs_id   系列id
     * @return \BlueCity\Core\Controllers\mixed|\Illuminate\Http\JsonResponse
     * @author du 2021年7月23日下午4:25:18
     */
    public function addLab(Request $request)
    {
        $input = $request->only('cd_id','lt_parent_id','sety_name','lt_group','sety_price','lt_score','lt_statues','gs_id','lt_ids','sety_remark');
        $rules = [
        		'lt_parent_id' => 'required|',
        		'cd_id' => 'required|',
        		//'gs_id' => 'required|',
        		'sety_name' => 'required|string',
        		'lt_group' => 'required',

        ];
        $message = [
        		'lt_parent_id.required' => "父id不能为空",
        		'cd_id.required' => "品类ID不能为空",
        		//'gs_id.required' => "系列ID不能为空",
        		'sety_name.required' => "标签名不能为空",
        		'lt_group.required' => "部门编号不能为空",

        ];
        $Validator = Validator::make ( $input, $rules, $message );

        if ($Validator->fails ()) {
        	$error = CommonService::validatorToString($Validator);
        	return $this->error ( $error, ErrorInc::INVALID_PARAM,[]);
        	exit ();
        }

        $lt_parent_id = $request->input('lt_parent_id',0);
        $search = SetmoneyType::where('cd_id',$request->input('cd_id'))->where('lt_parent_id',$lt_parent_id)->where('sety_name',$request->input('sety_name'))->value('sety_id');
        if ($search){
            return $this->error('该标签已存在', ErrorInc::REPEAT_SUBMIT, []);exit;
        }

        $arr['cd_id'] = $input['cd_id'];//品类ＩＤ
        //$arr['gs_id'] = $input['gs_id'];//系列ＩＤ
        $arr['lt_parent_id'] = $lt_parent_id;//获取下拉列表中的sety_id
        $arr['sety_name'] = $input['sety_name'];
        $arr['sety_price'] = $input['sety_price']?? 0;
        $arr['sety_creacter'] = $request->get('session_token')['admin_acc'];
        $arr['sety_time'] = date('Y-m-d H:i:s',time());
        $arr['sety_type'] = 3;
        $arr['lt_group'] = $input['lt_group'];//部门ＩＤＳ
        $arr['lt_type'] = $input['lt_type']??2;//是否需要处理 : 1.需要 2.不需要
        $arr['lt_statues'] = $input['lt_statues']??1;//1:显示　２：　不显示
        $arr['sety_remark'] = $input['sety_remark']??'';//备注
        if($lt_parent_id==0){
        	$arr['lt_ids'] = 0;
        }else{
        	$input['lt_ids'] = $input['lt_ids']??'';
        	$arr['lt_ids'] = $lt_parent_id.','.$input['lt_ids'];
        }

        $add = SetmoneyType::insert($arr);
        if($add){
            $data = LabtypeService::getMysqlLable('labelList');
            $this->insertingLog("添加标签，","","添加标签".$request->input('sety_name'),"标签管理",$request->ip(),$request->get('session_token')['admin_acc']);//日志
            return $this->success('添加成功', []);exit;
        }else{
        	return $this->error('添加失败', ErrorInc::MYSQL_FAILED, []);exit;
        }
    }

    /**
     * @name 编辑
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月26日上午10:31:42
     */
    public function editLab (Request $request)
    {
        if (!$request->filled('sety_id')||!$request->filled('type')){
        	return $this->error('参数错误', ErrorInc::INVALID_PARAM, []);exit;
        }
        $sety_id = $request->input('sety_id');
        if ($request->input('type') == 1){
            $list = SetmoneyType::where('sety_id',$sety_id)->select('sety_id','cd_id','sety_name','sety_price','lt_group','lt_statues','lt_type','lt_parent_id')->first();
            if ($list['lt_group']){
                $list['lt_group'] = explode(',',trim($list['lt_group'],','));
            }
            if ($list){
            	return $this->success('获取成功', $list);exit;
            }else{
            	return $this->error('暂无数据', ErrorInc::DATA_EMPTY, []);exit;
            }
        }else{
        	$input = $request->only('sety_id','cd_id','lt_parent_id','sety_name','lt_group','sety_price','lt_score','lt_statues','gs_id','sety_remark','lt_type');
        	$rules = [
        			'lt_parent_id' => 'required|',
        			'cd_id' => 'required|',
        			//'gs_id' => 'required|',
        			'sety_name' => 'required|string',
        	];
        	$message = [
        			'lt_parent_id.required' => "父id不能为空",
        			'cd_id.required' => "品类ID不能为空",
        			//'gs_id.required' => "系列ID不能为空",
        			'sety_name.required' => "标签名不能为空",
        	];
        	$Validator = Validator::make ( $input, $rules, $message );
        	if ($Validator->fails ()) {
        		return $this->error ( $Validator->errors ()->first (), ErrorInc::INVALID_PARAM,[]);
        		exit ();
        	}

            $sety = SetmoneyType::where('sety_id',$input['sety_id'])->select('sety_id','sety_name')->first();
	        $lt_parent_id = $request->input('lt_parent_id');
	        $search = SetmoneyType::where('cd_id',$request->input('cd_id'))->where('lt_parent_id',$lt_parent_id)->where('sety_id','!=',$sety_id)->where('sety_name',$request->input('sety_name'))->value('sety_id');

	        if ($search){
	            return $this->error('该标签已存在', ErrorInc::REPEAT_SUBMIT, []);exit;
	        }

            $arr['lt_lastiime'] = date('Y-m-d H:i:s');
            $arr['cd_id'] = $input['cd_id'];//品类ＩＤ
	        //$arr['gs_id'] = $input['gs_id'];//系列ＩＤ
	       // $arr['lt_parent_id'] = $lt_parent_id;//获取下拉列表中的sety_id
	        $arr['sety_name'] = $input['sety_name'];
	        $arr['sety_price'] = $input['sety_price']?? 0;
	        $arr['sety_creacter'] = $request->get('session_token')['admin_acc'];
	        $arr['lt_group'] = $input['lt_group'];//部门ＩＤＳ
	        $arr['lt_type'] = $input['lt_type']??2;//是否需要处理 : 1.需要 2.不需要
	        $arr['lt_statues'] = $input['lt_statues']??1;//1:显示　２：　不显示
	        $arr['sety_remark'] = $input['sety_remark']??'';//备注
            $upRes = SetmoneyType::where('sety_id',$sety_id)->update($arr);
            if ($upRes){
                $data = LabtypeService::getMysqlLable('labelList');
                $content = "编辑标签:".$sety['sety_id']."-".$sety['sety_name']."->".$request->input('sety_name');
                $this->insertingLog("编辑，","",$content,"标签管理",$request->ip(),$request->get('session_token')['admin_acc']);
                return $this->success('编辑成功', []);exit;
            }else{
            	return $this->error('编辑失败', ErrorInc::MYSQL_FAILED, []);exit;
            }
        }
    }
    /**
     * 获取部门标签
     * @param string group 操作的部门权限
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author dou 2021/07/28
     */
	public function getBmmcLab ( Request $request )
	{
		if (!$request->filled('group')) {
			return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);
		}
		$list = LabtypeService::getBmmcLab($request->input('group'));
		$list['list'] = CommonService::resetListKey($list['list']);
		if($list['list']){
			return $this->success('成功', $list);exit;
		}else{
			return $this->error('无数据', ErrorInc::DATA_EMPTY, []);exit;
		}
	}

    /**
     * 编辑部门标签
     * @param id 数据id
     * @param group 部门id
     * @param state 选中状态 1选中  2取消选中
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月27日上午9:23:07
     */
    public function editLabByGroup (Request $request)
    {
    	if (!$request->filled('id') || !$request->filled('group') || !$request->filled('state')) {
    		return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);

    	}
    	$id = intval($request->input('id'));//部门id
    	$group = intval($request->input('group'));//标签sety_id数组
    	$state = intval($request->input('state'));//操作状态
    	if(!in_array($state,['1','2'])){
	    	return $this->error('修改状态值异常', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$result = SetmoneyType::whereRaw("FIND_IN_SET(".$id.",lt_ids)")->pluck('sety_id');
    	$result = self::dataToArray($result);
    	$id = array($id);
    	$result = array_merge($result,$id);
    	$list = SetmoneyType::whereIn('sety_id',$result)->select('sety_id','lt_group')->get()->toArray();
    	DB::beginTransaction();
    	foreach( $list as $k => $v ){
    		$lt_group = explode(',',trim($v['lt_group'],','));
    		$rea = true;
    		if($state == 1){
	    		if(!in_array($group,$lt_group)){
		    		$poss['lt_group'] = $v['lt_group'].','.$group;
    				$rea = SetmoneyType::where('sety_id',$v['sety_id'])->update($poss);
	    		}
    		}else if($state == 2){
	    		if(in_array($group,$lt_group)){
		    		unset($lt_group[array_search($group,$lt_group)]);
		    		$poss['lt_group'] = implode(',',$lt_group);
    				$rea = SetmoneyType::where('sety_id',$v['sety_id'])->update($poss);
	    		}
    		}
    		if(!$rea){
	    		DB::rollback();
            	return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);
    		}
    	}
        $data = LabtypeService::getMysqlLable('labelList');
    	DB::commit();
		return $this->success('操作成功', []);exit;
    }
	//运行lt_ids
    public function test ( $id ) {
	    //return self::test(0);//放在其它方法中作为启动方法使用
    	$res=SetmoneyType::where('sety_id','>',$id)->orderBy('sety_id')->first();
    	if($res){
	    	$res=$res->toArray();
	    	if($res['lt_parent_id']==0){
		    	$poss['lt_ids']=0;
	    	}else{
		    	$aaa=SetmoneyType::where('sety_id',$res['lt_parent_id'])->value("lt_ids");
		    	$poss['lt_ids']=$aaa.','.$res['lt_parent_id'];
	    	}
	    	$aa=SetmoneyType::where('sety_id',$res['sety_id'])->update($poss);
	    	if(!$aa){
		    	return 1111;
	    	}else{
		    	return self::test($res['sety_id']);
	    	}
    	}else{
	    	return 22222;
    	}
    }
}
