<?php

namespace App\Services;
use App\Http\Controllers\BaseController;
use App\Models\SerInfor;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Core\Service\Service;
use DB;
use App\Models\EvaluationForm;
use App\Models\SetmoneyType;

class EvaluationFormService extends Service
{
    //private static $instance;
    private $modelMain = null;

    public function __construct()
    {
        if (!$this->modelMain) $this->modelMain = new EvaluationForm();
    }


    /**
     * 获取信息
     * @param string $key 查询键
     * @param string $value 查询值
     * @param string $type 查询类型
     * @return unknown|boolean
     * @author du 2021年8月9日上午8:52:39
     */
    public static function getInfoByKeyValue($key , $value , $type = 'get')
    {
        $db = new EvaluationForm();
        $list = CommonService::getMysqlData($db,[$key=>$value],[],[],$type);
        if($list){
            return $list;
        }else{
            return false;
        }
    }

    /**
     * 获取详细内容
     * @param string $key 查询键
     * @param string $value 查询值
     * @param array $select 待查询参数
     * @return
     * @author du 2021年8月13日上午9:03:06
     */
    public static function getInfoBy($key, $value, $select = [])
    {
    	$db = new EvaluationForm();
    	$type = 'first';
    	if(count($select) == 1){
    		$type = 'value';
    	}
    	$list = CommonService::getMysqlData($db,[$key=>$value],$select,[],$type);
    	return $list;
    }

    /**
     * 添加
     * @param  $evld_evid
     * @param  $evld_creactid
     * @param  $evld_creacter
     * @param  $evld_content
     * @param  $evld_label
     * @param  $evld_type
     * @author du 2021年8月13日上午9:44:25
     */
    public static function createEvaData($evld_evid,$evld_creactid,$evld_creacter,$evld_content,$evld_label,$evld_type,$evld_pic='',$evld_sound=''){
    	$poss['evld_evid'] = $evld_evid;
    	$poss['evld_creactid'] = $evld_creactid;
    	$poss['evld_creacter'] = $evld_creacter;
    	$poss['evld_creactime'] = date("Y-m-d H:i:s") ;
    	$poss['evld_content'] = $evld_content;
    	$poss['evld_label'] = $evld_label;
    	$poss['evld_type'] = $evld_type;
    	$poss['evld_pic'] = $evld_pic;
    	$poss['evld_sound'] = $evld_sound;
    	$res = DB::table('evaluation_data')->insert($poss);
    	return $res;
    }


    /**
     * 获取催单列表
     * @param array $input
     * @param array $session
     * @return Ambigous <multitype:, unknown, multitype:unknown NULL >
     * @author du 2021年8月7日下午3:39:38
     */
    public static function getList($input,$session){
    	$Db = new EvaluationForm();
        $Db = $Db->leftJoin('orders', 'orders.order_num', '=', 'evaluation_form.plat_number');
    	$where = [];
    	if ($input['eva_status'] == 0) {//全部
    		$where['1'] = 1;
    	} elseif (isset($input['eva_status'])) {//新录入
    		$where['eva_status'] = $input['eva_status'];
    	}
    	if (isset($input['plat_number'])) {
    		$where['plat_number_llike'] = $input['plat_number'];
    	}
    	if (isset($input['eval_leval'])) {//评价级别
    		$where['eval_leval'] = $input['eval_leval'];
    	}
    	if (isset($input['eval_time'])) {//评价时间
    		$input['eval_time'][1] = date("Y-m-d", strtotime($input['eval_time'][1] . " +1 day"));
    		$where['eval_time_between'] = $input['eval_time'];
    	}
    	if (isset($input['ser_id'])) {
    		$where['gone_evaluation_form.ser_id'] = $input['ser_id'];
    	}
    	if($session['admin_groupnew']!=7){
    		$where['gone_orders.company_id'] = $session['company_id'];
    	}

        if (isset($input['category'])) {//类别
            $where['category'] = $input['category'];
        }
        if (isset($input['p_id'])) {//平台
            $where['p_id'] = $input['p_id'];
        }
        if (isset($input['goods_brand'])) {//品牌
            $where['goods_brand_like'] = $input['goods_brand'];
        }
        if (isset($input['eval_label'])) {//评价标签
            $where['eval_label_like'] = $input['eval_label'];
        }

    	$where = CommonService::jointWhere($where);
    	$page_size = $input['page_size']??10;
        if($input['is_excel']==1){
            DB::connection()->enableQueryLog();#开启执行日志
        }
    	$paginate = $Db->whereRaw($where)->select('evaluation_form.*','orders.category','orders.goods_brand','orders.p_id')->orderBy('eva_id','DESC')->paginate($page_size);
    	//print_r(DB::getQueryLog());
//导出所需语句
        $data['sqls'] = DB::getQueryLog()[1];

        $where1 = [];
        $where1[1] = 1;
        if ($session['admin_groupnew'] != 7) {//管理员可以看全部
            $where1['company_id'] = $session['company_id'];
        }
        $where1 = CommonService::jointWhere($where1);

        $xlr = EvaluationForm::where('eva_status',1)->whereRaw($where1)->count();
        $clz = EvaluationForm::where('eva_status',2)->whereRaw($where1)->count();
        $eva_status4 = EvaluationForm::where('eva_status',4)->whereRaw($where1)->count();
        $eva_status3 = EvaluationForm::where('eva_status',3)->whereRaw($where1)->count();
        $eva_status10 = EvaluationForm::where('eva_status',10)->whereRaw($where1)->count();
        $eva_status15 = EvaluationForm::where('eva_status',15)->whereRaw($where1)->count();
        $eva_status50 = EvaluationForm::where('eva_status',50)->whereRaw($where1)->count();
        $ssz = EvaluationForm::where('eva_status',5)->whereRaw($where1)->count();

        $data['show_Menu'] = [
            ['showname'=>"全部",'status'=>0,'shownum'=>"--"],
            ['showname'=>"新录入",'status'=>1,'shownum'=>$xlr??0],
        	['showname'=>"待处理",'status'=>4,'shownum'=>$eva_status4??0],
        	['showname'=>"商家处理",'status'=>3,'shownum'=>$eva_status3??0],
            ['showname'=>"处理中",'status'=>2,'shownum'=>$clz??0],
            ['showname'=>"申诉中",'status'=>5,'shownum'=>$ssz??0],
            ['showname'=>"已审核",'status'=>10,'shownum'=>$eva_status10??0],
            ['showname'=>"已完成",'status'=>15,'shownum'=>$eva_status15??0],
            ['showname'=>"已撤消",'status'=>50,'shownum'=>$eva_status50??0],
        ];
    	$all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);
    	$export = BmmcService::getTopButton('importEvaluation,syncEvaluation,export,fastEvaluate,matchNewToFinish','',$all_button);
    	$data['button_top'] = $export['button_top']??[];//顶部按钮
    	$data['button_search'] = $export['button_search']??[];//搜索栏按钮
    	$list = CommonService::dataToArray($paginate->items());
    	if($list){
    		$list = EvaluationFormService::getButtonDatas($all_button, $list);
    		$data['list'] = $list;
    		$data['page'] = [
    				'count' => $paginate->total(),
    				'page' => $paginate->currentPage(),
    				'page_size' => $page_size,
    				'allPage' => $paginate->lastPage()
    		];
    	}else{
    		$data['list'] = [];
    	}
    	return $data;
    }
    /**
     * 获取按钮和数据
     * @param array $all_button
     * @param array $list
     * @return string
     * @author du 2021年8月7日下午3:40:48
     */
    public static function getButtonDatas($all_button,$list){
    	$lab = array_column($list,'eval_label');
    	$sety = SetmoneyType::whereIn('sety_id', $lab)->pluck('sety_name','sety_id');

    	$orderStaus = OrderService::getOrderStatusName();
    	$stArr = EvaluationFormService::getStatusName();

    	$statNames = EvaluationFormService::getStatName();

        $pts = PlatformService::getAll(true,'id');

    	foreach ($list as $k => $v){
            $buttonData = [];
    		$list[$k]['statusName'] = $stArr[$v['eva_status']];
    		$list[$k]['orderStatusName'] = $orderStaus[$v['status']];
            $list[$k]['statName'] = $statNames[$v['state']];
            $list[$k]['cd_name'] = CategoryService::getNameByCdId($v['category']);//订单类型
            if (isset($pts[$v['p_id']])){
                $list[$k]['pt_name'] = $pts[$v['p_id']]['pt_name'];
            }else{
                $list[$k]['pt_name'] = "暂无";
            }
    		if($v['eva_status']<5){
    			$buttonData[] = 'cancle,labEvaluation,toExamine';
    		}
    		if($v['eva_status']==3){
    			$buttonData[] = 'appealEvaluation,cancle,labEvaluation,toExamine';
    		}
    		if($v['eva_status']==5){
    			$buttonData[] = 'explainEvaluation,cancle,labEvaluation,toExamine';
    		}
    		if($v['eva_status']<=2){
    			$buttonData[] = 'cancle,labEvaluation,toExamine,businessDeal';
    		}
            if($v['eva_status']==1){
                $buttonData[] = 'newToWait';
            }

    		$buttonData[] = 'listEvaluation';
    		$button = BmmcService::getListButton($buttonData,$all_button);

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

    		unset($buttonData);

    		unset($button);


    		if (isset($sety[$v['eval_label']])) {
    			$list[$k]['label_name'] = $sety[$v['eval_label']];
    		} else {
    			$list[$k]['label_name'] = '';
    		}
    	}
    	return $list;
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加评价表（evaluation_form）数据
     * @param array $input 待添加参数
     * @retrun multitype:array
     * @author dou 2021/8/18 10:24
     * |---------------------------------------------------------------------------------
    */
    public static function createEvaForm( $input ){
        $eva_id = EvaluationForm::where('plat_number',$input['plat_number'])->where('eval_content',$input['eval_content'])->value('eva_id');
        if($eva_id){
            unset($input['plat_number']);
            $res = EvaluationForm::where('eva_id',$eva_id)->update($input);
        }else {
            $res = EvaluationForm::insert($input);
        }
        return $res;
    }

    public static function getStatName(){
    	return array('1'=>'未同步','2'=>'同步成功','3'=>'单号不存在','4'=>'单号重复');
    }

    public static function getStatusName(){
        return array('1'=>'新录入','4'=>'待处理','2'=>'处理中','3'=>'商家处理','5'=>'申诉中','10'=>'已审核','15'=>'已完成','50'=>'已撤消','55'=>'同步失败');
    }

    /**|---------------------------------------------------------------------------------
     * @name 详情
     * @param int $id 数据id
     * @retrun /multitype:array
     * @author dou 2021/9/23 16:24
     * |---------------------------------------------------------------------------------
    */
    public static function listEvaluation ( $id ){
        $info = self::getInfoBy('eva_id', $id,['plat_number','goods_name','eval_content','eval_time','eval_leval']);
        $data['plat_number'] = $info['plat_number'];//平台单号
        $data['goods_name'] = $info['goods_name'];//商品名称
        $data['eval_content'] = $info['eval_content'];//评价内容
        $data['eval_time'] = $info['eval_time'];//评价时间
        $data['eval_leval'] = $info['eval_leval'];//评价级别
        $db =  DB::table('evaluation_data');
        //获取数据
        $list = CommonService::getMysqlData($db, ['evld_evid'=>$id],['evld_id','evld_creactime','evld_content','evld_type','evld_pic as pic_arr','evld_sound','evld_label'],['evld_creactime'=>'ASC']);
        if ($list) {
            foreach ($list as $k => $v) {
                if ($v['evld_type'] == 1) {
                    $list[$k]['evld_type_name'] = '解释';
                } elseif ($v['evld_type'] == 5) {
                    $labname = SetmoneyType::where('sety_id',$v['evld_label'])->value('sety_name');
                    $list[$k]['evld_type_name'] = "申诉";
                    if (isset($labname)) {
                        $list[$k]['evld_type_name'] = '申诉'.'（'.$labname.'）';
                    }
                }
                if ($v['evld_type'] == 5) {//申诉有图片
                    if ($v['pic_arr']) {
                        $pics = explode(',',$v['pic_arr']);
                        $picArr = [];
                        foreach ($pics as $ks => $vs) {
                            $picArr[] = $vs;
                        }
                        $list[$k]['pic_arr'] = $picArr;
                    } else {
                        $list[$k]['pic_arr'] = [];
                    }
                    $list[$k]['evld_sound'] = $v['evld_sound']??"";
                } else {
                    $list[$k]['pic_arr'] = [];
                    $list[$k]['evld_sound'] = "";
                }
                $list[$k]['typesd'] = 1; //前段要求多传一个字段
            }
            $data['list'] = $list;
        } else {
            $data['list'] = [];
        }
        return $data;
    }


    /**
     * @评价
     * @param $input
     * @param $session
     * @param $ip
     * @return array
     * @author du
     * @date 2022/1/4
     */
    public static function addEvaluation($input,$session,$ip)
    {
        $id = $input['id'];//订单id
        $content = $input['content'];//备注内容
        $sys_num = $input['sys_num'];
        $labs = $input['labtype'];//反馈标签
        $orderArr = OrderService::getOrderBy('id', $id,['order_num', 'order_status', 'p_id', 'ser_id','order_time','goods_name']);
        $company_name = AdminsService::getAdmins(['id'=>$orderArr['ser_id']],['company_name'],[],'value');
        $orderInfo = OrderListService::getOrderListBy('order_num', $orderArr['order_num'],'first',['serial_number','order_goods_id']);
        $goods_name = OrderService::getOrderMsgBy('id', $orderInfo['order_goods_id'],['goods_name']);
        if(empty($goods_name)){
            $goods_name = $orderArr['goods_name'];
        }
        DB::beginTransaction();

        $BaseController = new BaseController();
        /*----------------------------------------添加标签列表数据开始-------------------------------------------------*/
        $orderinfo['order_num'] = $orderArr['order_num'];
        $orderinfo['serial_number'] = $orderInfo['serial_number'];
        $orderinfo['p_id'] = $orderArr['p_id'];
        $orderinfo['ser_id'] = $orderArr['ser_id'];
        $sety_name = AfterSaleService::insertData($labs, $orderinfo, $session, $content);
        /*----------------------------------------添加标签列表数据结束-------------------------------------------------*/
        if($sety_name) {
            $contents = implode(',',$sety_name) . '-' . $content;
            $notRes = CommonService::accMe($sys_num, '评价订单', $contents, '', '', $session['admin_groupnew'], $session['admin_acc'], $session['id']);
            if ($notRes){
                /*------------------------------------添加平台评价列表开始---------------------------------------------*/
                $param = [
                    'plat_number' => $orderArr['order_num'],
                    'eval_time' => $input['eval_time'],
                    'eval_leval' => "差评",
                    'eval_content' => CommonService::restrict($content),
                    'eval_type' => 0,
                    'goods_name' => $goods_name,
                    'order_time' => $orderArr['order_time'],
                    'company_name' => $company_name,
                    'ser_id' => $orderArr['ser_id'],
                    'state' => 2,
                    'status' => $orderArr['order_status'],
                    'syn_time'=> date("Y-m-d H:i:s"),
                    'eval_content_show' => $content,
                    'eval_label' => implode(',',$sety_name),
                    'creact_id' => $session['id'],
                ];

                $param['company_id'] = $session['company_id'];
                EvaluationFormService::createEvaForm($param);
                /*------------------------------------添加平台评价列表结束---------------------------------------------*/
                DB::commit();//成功则提交
                if ($orderInfo['serial_number']) {
                    $BaseController->operatingTime($orderInfo['serial_number'], '评价订单时间', date("Y-m-d H:i:s"), $orderArr['order_num'], $session['admin_acc']);//订单操作时间
                }
                $BaseController->insertingLog('评价订单，', $sys_num, '订单' . $sys_num, '订单管理', $ip, $session['admin_acc']);//日志
                return ['Data' => [], 'ErrorMessage' => '操作成功', 'ErrorCode' => 1];
                exit;
            } else {
                DB::rollback();
                return ['Data' => [], 'ErrorMessage' => '操作失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
                exit;
            }
        }else{
            DB::rollback();
            return ['Data' => [], 'ErrorMessage' => '操作失败', 'ErrorCode' => ErrorInc::MYSQL_FAILED];
            exit;
        }
    }


}
