<?php
namespace App\Services;
use App\Http\Controllers\BaseController;
use App\Models\Feedback;
use App\Models\InstallPerson;
use App\Models\Orders;
use App\Models\SerInfor;
use DB;
use App\Models\OrderList;
use BlueCity\Core\Service\Service;
use App\Models\OrderMsg;
use App\Models\AdminInfor;
use App\Models\OrderTime;
use App\Models\SettlementMoney;
use App\Models\TicketList;
use App\Models\Aftersale;
use App\Models\SetmoneyType;
use App\Models\SettlementList;
use App\Models\OrderVisit;
use BlueCity\Core\Inc\ErrorInc;
use Illuminate\Database\Eloquent\Model;

class OrderListService extends Service
{
	/**
	 * 根据ＩＤ获取一条订单里的商品信息
	 * @param int $id
	 * @return array
	 * @author du 2021年7月30日下午2:20:02
	 */
	public static function getOrderMsgById($id){
		$data = OrderMsg::where('id',$id)->select('goods_id','goods_name','goods_num','goods_price','goods_brand','goods_service','goods_pic_path','category')->first()->toarray();
		if($data){
			return $data;
		}else{
			return false;
		}

	}

	/**
	 * 获取公司信息
	 * @param int $id
	 * @return string;
	 * @author du 2021年7月30日下午2:44:41
	 */
    public static function getUserHeadPhoneById($id){
    	$data = AdminInfor::where('admin_id',$id)->select('head_phone','phone','admin_principal','admin_province','admin_city','admin_county','admin_dressi')->first();
    if($data){
			return $data;
		}else{
			return '';
		}
    }

    /**
     * 获取反馈信息
     * @param  int id orderlist表的ＩＤ
     * @param string $serial_number 工单号
     * @author du 2021年7月30日下午3:29:02
     */
    public static function getOperTime($serial_number,$id=0,$category = ''){
    	$data = [];
    	$operation_time = OrderTime::where('serial_number',$serial_number)->orderBy('id','ASC')->select('create_time','is_type')->get()->toArray();
    	//反馈图片
    	if($id){
            $db = new Feedback();
            $params = ['gl_id'=>$id];
            $select = ['is_type','type','feedback_status','feedback_pic','install_name','install_time','type_name'];
            $orderBy = ['id'=>'ASC'];
            $feedAcc = CommonService::getMysqlData($db, $params,$select,$orderBy);
    		$BaseController = new BaseController();
    		if($feedAcc){
                $picName = self::getFeedPicName();
    		    foreach($feedAcc as $k => $v){
                    if(strstr($v['feedback_pic'],'http')){
                        $url = $v['feedback_pic'];
                    }else{
                        if($v['is_type']==1){
                            if($category == 3){
                                $url = $BaseController->picurl($v['feedback_pic'],$category);
                            }else {
                                $url = "http://weixin.sudianwang.com" . ltrim($v['feedback_pic'], '.');
                            }
                        }else{
                            $url = $BaseController->picurl($v['feedback_pic'],$category);
                        }
                    }
                    if($v['type_name']){
                        $pictype = $v['type_name'];
                    }else{
                        if(isset($picName[$category])){
                            $pictype = $picName[$category][$v['type']]??'';
                        }else{
                            $pictype = $picName[1][$v['type']]??'';
                        }
                    }
                    if($v['feedback_pic']){
                        $feedAcc[$k]['pictype'] = $pictype;
                        $feedAcc[$k]['url'] = $url;
                    }else{
                        $feedAcc[$k]['pictype'] = '';
                        $feedAcc[$k]['url'] = '';
                    }
    		    }
            }
    		$data['feedback'] = $feedAcc;
            $data['operation_time'] = $operation_time;
    	}else{
    	    $is_type = ['下单时间','派单时间','接单时间','任务反馈时间'];
    	    foreach($operation_time as $k => $v){
                $operation_time[$k]['is_show'] = 2;
                if(in_array($v['is_type'], $is_type)){
                    $operation_time[$k]['is_show'] = 1;
                }
    	    }
            $data = $operation_time;
        }

    	return $data;


    }
    /**
     * 根据ID获取一条数据
     * @param int $id
     * @return array
     * @author du 2021年7月31日下午1:23:57
     */
    public static function getOrderListByID($id){
    	$data = OrderList::where('id',$id)->select('id','create_time','install_id','locklist_type','sys_num','order_num','orli_type','serial_number','p_id','order_goods_id','ser_id','customer_id','stauas','pay_typel','feeds_time','category','goods_brand','manhourfee','send_sms','ol_dispamount','store_type','intall_person','intall_phone','company_id', 'agency_id')->first();
    	if($data){
    		$data = CommonService::dataToArray($data);
    		return $data;
    	}else{
    		return false;
    	}

    }

    /**获取工单详细内容
     * @param string $key 查询键
     * @param string $value 查询值
     * @param string $type 查询类型
     * @param array $select 查询参数
     * @return array|mixed
     */
    public static function getOrderListBy($key , $value , $type = 'get' , $select = [] , $orderby = [])
    {
        $db = new OrderList();
        if($key == 'id'){
            $type = 'first';
        }
        if($type == 'first' && count($select) == 1){
            $type = 'value';
        }
        $list = CommonService::getMysqlData($db,[$key=>$value],$select,$orderby,$type);
        if($list){
            return $list;
        }else{
            return false;
        }
    }
    /**
     *
     * @param  $os_serial
     * @param  $os_serid
     * @param  $os_installid
     * @param  $os_parenid
     * @param  $os_ordernum
     * @param  $os_sysnum
     * @return
     * @author du 2021年7月31日下午1:57:39
     */
    public static function creatOrderSendflow($os_serial,$os_serid,$os_installid,$os_parenid,$os_ordernum,$os_sysnum){
    	$senl['os_serial'] = $os_serial;
    	$senl['os_serid'] = $os_serid;
    	$senl['os_installid'] = $os_installid;
    	$senl['os_parenid'] = $os_parenid;
    	$senl['os_ordernum'] = $os_ordernum;
    	$senl['os_sysnum'] = $os_sysnum;
    	$res = DB::table('order_sendflow')->insert($senl);
    	return $res;

    }


   /**
    *
    * @param  $line_serm
    * @param  $line_sysnum
    * @param  $line_number
    * @param  $line_status
    * @param  $line_state
    * @return
    * @author du 2021年7月31日下午1:58:08
    */
   public static function createInstallLine($line_serm,$line_sysnum,$line_number,$line_status,$line_state){
   	$install_data['line_serm'] = $line_serm;
   	$install_data['line_sysnum'] = $line_sysnum;
   	$install_data['line_number'] = $line_number;
   	$install_data['line_status'] = $line_status;
   	$install_data['line_state'] = $line_state;
   	$install_data['line_lasttime'] = date("Y-m-d H:i:s");

   	$res = DB::table('install_line')->insert($install_data);
   	return $res;
   }

   /**
    *
    * @param  $afs_statues
    * @param  $afs_order
    * @param  $afs_serial
    * @param  $afs_sales
    * @param  $afs_granid
    * @param  $afs_paid
    * @param  $afs_type
    * @param  $afs_pid
    * @param  $afs_serid
    * @param  $afs_content
    * @param  $afs_creacter
    * @param  $afs_dealer
    * @author du 2021年8月4日下午2:58:00
    */
   public static function creatAftersale($afs_statues,$afs_order,$afs_serial,$afs_sales,$afs_granid,$afs_paid,$afs_type,$afs_pid,$afs_serid,$afs_content,$afs_creacter,$afs_dealer,$company_id=1){
   	$anna['afs_statues'] = $afs_statues;
   	$anna['afs_order'] = $afs_order;
   	$anna['afs_serial'] = $afs_serial??'无';
   	$anna['afs_sales'] = $afs_sales;
   	$anna['afs_granid'] = $afs_granid;
   	$anna['afs_paid'] = $afs_paid;
   	$anna['afs_type'] = $afs_type;
   	$anna['afs_pid'] = $afs_pid;
   	$anna['afs_serid'] = $afs_serid;
   	$anna['afs_creactime'] = date('Y-m-d H:i:s');
   	$anna['asf_time'] = date('Y-m-d H:i:s');
   	$anna['afs_day'] = date('Y-m-d');
   	$anna['afs_content'] = $afs_content;
   	$anna['afs_creacter'] = $afs_creacter;
   	$anna['afs_dealer'] = $afs_dealer;
    $anna['company_id'] = $company_id??1;
   	$res = Aftersale::insert($anna);
   	return $res;
   }
   /**
    *
    * @param  $type
    * @param  $gl_id
    * @param  $install_name
    * @param  $install_phone
    * @param  $admin_id
    * @param  $company_name
    * @param  $is_type
    * @param  $feedback_status
    * @param  $feedback_pic
    * @return
    * @author du 2021年8月4日下午6:09:56
    */
   public static function createFeedback($type,$gl_id,$install_name,$install_phone,$admin_id,$company_name,$is_type,$feedback_status,$feedback_pic='',$type_name = ''){
   	$fpArr['type'] = $type;//图片类型
   	$fpArr['gl_id'] = $gl_id;//关联order_list的id
   	$fpArr['install_name'] = $install_name;//安装人
   	$fpArr['install_phone'] = $install_phone;//安装人电话
   	$fpArr['install_time'] = date("Y-m-d H:i:s");//安装日期
   	$fpArr['admin_id'] = $admin_id;//安装服务中心id
   	$fpArr['company_name'] = $company_name;//服务中心名称
   	$fpArr['sys_num'] = 'rwfk'.$gl_id;//
   	$fpArr['is_type'] = $is_type;//PC端
   	$fpArr['feedback_status'] = $feedback_status;//已安装
   	$fpArr['feedback_pic'] = $feedback_pic??'';
    $fpArr['type_name'] = $type_name;
   	$res = DB::table('feedback')->insert($fpArr);
   	return $res;
   }

   /**
    *
    * @param  $serial_number
    * @param  $ser_id
    * @param  $istall_id
    * @param  $parenid
    * @param  $order_num
    * @param  $sys_num
    * @author du 2021年8月5日下午5:55:29
    */
   public static function createSendflow ( $serial_number,$ser_id,$istall_id,$parenid,$order_num,$sys_num)
   {
   	$senl['os_serial'] = $serial_number;
   	$senl['os_serid'] = $ser_id;
   	$senl['os_installid'] = $istall_id??'0';
   	$senl['os_parenid'] = $parenid;
   	$senl['os_ordernum'] = $order_num;
   	$senl['os_sysnum'] = $sys_num;
   	$res = DB::table('order_sendflow')->insert($senl);
   	return $res;
   }

   /**
    *
    * @param  $orsc_grade
    * @param  $orsc_sernum
    * @param  $orsc_slid
    * @param  $orsc_creacter
    * @param  $orsc_type
    * @return
    * @author du 2021年8月6日上午9:40:28
    */
   public static function createScore($orsc_grade,$orsc_sernum,$orsc_slid,$orsc_creacter,$orsc_type){
   	$scoreq['orsc_grade'] = $orsc_grade;
   	$scoreq['orsc_sernum'] = $orsc_sernum;
   	$scoreq['orsc_slid'] = $orsc_slid;
   	$scoreq['orsc_creacter'] = $orsc_creacter;
   	$scoreq['orsc_type'] = $orsc_type;
   	$res = DB::table('order_score')->insert($scoreq);
   	return $res;
   }

   /**
    *
    * @return multitype:string
    * @author du 2021年8月4日下午2:58:33
    */
   public static function getFeedPicName(){
        $data[3] = array('1' => '前挡图片', '2' => '左挡图片', '3' => '右挡图片', '4' => '后挡图片', '5' => '施工单图片', '6' => '膜桶图片');
        $data[1] = array('1' => '安装确认单', '2' => '安装后图片', '3' => '车牌号图片', '4' => '不断电安装', '5' => '生产日期', '7' => '电瓶条码');
        return $data;
   }

   /**
    * @name 计算奖惩金额及评分
    * @param int $info
    * @param array $orderListArr
    * @param float $supply_price
    * @param int $reward
    * @param float $order_price
    * @param string $admin_acc
    * @author du 2021年8月6日上午10:07:05
    */
   public static function calculates ($info,$orderListArr,$supply_price,$reward,$order_price,$admin_acc ,$category)
   {
   	if($supply_price==""){
   		$sem_price = $order_price;
   	}else{
   		$sem_price = $supply_price;
   	}
   	$sem_types = 1;
   	if($category==3){
        $sem_types = 351;
    }
    SettlementService::createSettMoney($info, $orderListArr['sys_num'], $sem_price, $admin_acc, $sem_types);
   	$payout_time = OrderTime::where(['serial_number'=>$orderListArr['serial_number'],'is_type'=>'起始时间'])->orderBy('id','DESC')->value('create_time');
   	$zero1 = time();
   	$zero2 = strtotime($payout_time);
   	$guonian = ($zero1-$zero2)/60;
   	if($guonian<=5){
   		$orsc_grade = 5;
   	}if($guonian>5 && $guonian<=10){
   		$orsc_grade = 2;
   	}if($guonian>10){
   		$orsc_grade = 1;
   	}
   	OrderListService::createScore($orsc_grade, $orderListArr['serial_number'], $info, $admin_acc, 1);
   	//默认生成平台评分十分
   	OrderListService::createScore(5, $orderListArr['serial_number'], $info, $admin_acc, 2);
   	#计算奖惩金额
   	if($reward=='1' && $category<3){
   		$sub_type = PlatformService::getBusType($orderListArr['p_id']);
   		if($sub_type != 2){
   			$money_type = SetmoneyType::whereRaw("sety_id in (2,3,8,9)")->pluck('sety_price','sety_id');
   			if($orderListArr['orli_type']==1){
   				if($guonian <= 5){
   					$sem_price = $money_type[2];
   					$sem_type = 2;
   				}if($guonian > 15){
   					$sem_price = $money_type[3];
   					$sem_type = 3;
   				}
   			}else{
   				if($orderListArr['orli_type']==10){
   					$sem_price = $money_type[9];
   					$sem_type = 9;
   				}
   				if($orderListArr['orli_type']==15 || $orderListArr['orli_type']==20 || $orderListArr['orli_type']==25 || $orderListArr['orli_type']==30){
   					$sem_price = $money_type[8];
   					$sem_type = 8;
   				}
   			}
   		}
   		if($guonian>5 && $guonian<=15 && $orderListArr['orli_type']==1){

   		}else{
   			$sub_type = PlatformService::getBusType($orderListArr['p_id']);
   			if($sub_type != 2){
   				SettlementService::createSettMoney($info, $orderListArr['sys_num'], $sem_price, $admin_acc, $sem_type);
   			}
   			$all_price['all_price'] = SettlementMoney::where('sem_slid',$info)->sum('sem_price');

   			SettlementList::where('id',$info)->update($all_price);
   		}
   	}
   }

   /**
    * 安装订单回访
    * @param string $serial_number
    * @param int $type
    * @return number
    * @author du 2021年8月3日下午3:54:57
    */
   public static function editVisit($serial_number,$type)
   {
   	$data['ov_show'] = $type;
   	$res = OrderVisit::where('ov_serial',$serial_number)->update($data);
   	if($res){
   		return 1;
   	}else{
   		return 2;
   	}
   }

   /**
    *
    * @param int $ser_id
    * @param int $s_id
    * @param int $s_group
    * @return boolean
    * @author du 2021年8月4日下午2:00:54
    */
   public static function checkOrder($ser_id,$s_id,$s_group){
   	if($ser_id == $s_id || $s_group != 2){
   		return true;
   	}else{
   		return false;
   	}
   }

   /**
    * 获取列表
    * @param array $input
    * @param array $session
    * @return Ambigous <multitype:, multitype:multitype:string  multitype:string unknown  , multitype:unknown NULL >
    * @author du 2021年8月18日上午8:37:41
    */
   public static function getList($input,$session){

    $bmmc_pids = BmmcService::searchPids($session['admin_groupnew']);
   	$where = [];
   	$commonwhere = self::getCommonWhere($session);
   	foreach($commonwhere as $k => $v){
        $where[$k] = $v;
   	}
   	$flag = 1;
   	$time = date("Y-m-d",strtotime("+1 day"));
   	$Db = OrderList::leftJoin('user','user.id','=','order_list.customer_id')->leftJoin('admin','admin.id','=','order_list.ser_id');

   	//if(isset($input['shr_phone'])||isset($input['order_num'])){
        if(isset($input['shr_phone'])){
            $where['shr_phone_rlike'] = $input['shr_phone'];
        }

        if(isset($input['order_num'])){//平台单号
            $where['gone_order_list.order_num_rlike'] = $input['order_num'];
            $flag = 2;
        }
    //}else{
        if ($input['state'] == 2){  //未接单
            $where['stauas_searchin'] = [10,20];
        }elseif ($input['state'] == 3){  //安装中
            $where['stauas'] = 30;
//            $search['day_time_searchlt'] = $time;
//            $search['day_time_isnull'] = null;
//            $where['day_time_searchor'] = $search;
        }elseif ($input['state'] == 4){  //延期订单
            $where['stauas'] = 30;
            $where['day_time_searchgt'] = $time;
        }elseif ($input['state'] == 5){  //待完成
            $where['delay_status'] = 1;
            $where['stauas'] = 34;
        }elseif ($input['state'] == 6){  //已完成
            $where['stauas'] = 40;
        } elseif ($input['state'] == 7){  //未预约
            $where['day_time'] = null;
            $where['stauas'] = 30;
        }elseif ($input['state'] == 8){  //超时
            $where['day_time_searchlt'] = date("Y-m-d");
            $where['stauas'] = 30;
        }elseif($input['state']==9){ //延期审图
            $where['delay_status'] = 2;
            $where['stauas'] = 34;
        }elseif($input['state']==10){ //延期结算
            $where['delay_status'] = 3;
            $where['stauas'] = 34;
        }

        if(isset($input['shr_name'])){
            $where['shr_name_like'] = $input['shr_name'];
            $flag = 2;
        }

        if(isset($input['sys_num'])){ //系统单号
            $where['gone_order_list.sys_num_rlike'] = $input['sys_num'];
            $flag = 2;
        }
        if(isset($input['serial_num'])){//派工单号
            $where['gone_order_list.serial_number_rlike'] = $input['serial_num'];
            $flag = 2;
        }

       if(isset($input['feeds_time'])){//完成时间
           $creatData = $input['feeds_time'];
           $start_time = explode(' ',$creatData[0])[0];
           $end_time = explode(' ',$creatData[1])[0];
           $time_arr[0] = date("Y-m-d 00:00:00",strtotime($start_time));
           $time_arr[1] = date("Y-m-d 23:59:59",strtotime($end_time));
           $where['gone_order_list.feeds_time_between'] = $time_arr;
           $flag = 2;
       }

       if(isset($input['p_id'])){//派工单号
            $where['p_id'] = $input['p_id'];
        }
        if(isset($input['ser_id'])){//服务商id
            $where['ser_id'] = $input['ser_id'];
        }

        if(isset($input['creater'])){//经手人员
            $where['admin_id'] = $input['creater'];
        }

       if(isset($input['shr_sheng'])){//客户地址省 2022-2-28 新增
           $where['shr_sheng_rlike'] = $input['shr_sheng'];
       }
       if(isset($input['shr_shi'])){//市 2022-2-28 新增
           $where['shr_shi_rlike'] = str_replace('市','',$input['shr_shi']);
       }
       if(isset($input['shr_xian'])){//县 2022-2-28 新增
           $where['shr_xian_like'] = $input['shr_xian'];
       }


     /*   if(isset($input['creater'])){//经手人员
            $where['creater'] = $input['creater'];
        }*/
        if(isset($input['creatData'])){//派单时间
            $creatData = $input['creatData'];
            $start_time = explode(' ',$creatData[0])[0];
            $end_time = explode(' ',$creatData[1])[0];
            $time_arr[0] = date("Y-m-d 00:00:00",strtotime($start_time));
            $time_arr[1] = date("Y-m-d 23:59:59",strtotime($end_time));
            $where['gone_order_list.create_time_between'] = $time_arr;
        }/*else{
            if(($input['state'] == 1||$input['state'] == 6) && $flag ==1 ){
                $time_arr[0] = date("Y-m-d 00:00:00",strtotime("-6 month ",time()));
                $time_arr[1] = date("Y-m-d 23:59:59");
                $where['gone_order_list.create_time_between'] = $time_arr;
            }
        }*/
        if(isset($input['shr_code'])){
            $where['shr_code'] = $input['shr_code']; //客户识别码
        }

        if(isset($input['cd_id'])){
            $where['category'] = $input['cd_id']; //商品品类
        }

        if(isset($input['delay_status'])){
            $where['delay_status'] = $input['delay_status']; //1:正常；2：延期审图；3：延期结算
        }

   // }
       if (!in_array($session['admin_groupnew'], [2,3,4,7,8])){//管理员可以看全部
           $where['gone_order_list.company_id'] = $session['company_id'];
       }
       if (in_array($session['admin_groupnew'], [8])){//管理员可以看全部
           $where['gone_order_list.company_id_searchin'] = $session['all_companys'];
       }

   	$where = CommonService::jointWhere($where);
   	$page_size = $input['page_size']??10;
   	if($input['is_excel']==1){
        DB::connection()->enableQueryLog();#开启执行日志
    }
   	//`car_make` varchar(255) DEFAULT NULL COMMENT '品牌',
       //  `car_line` varchar(50) DEFAULT NULL COMMENT '车系',
       //  `car_model` varchar(255) DEFAULT NULL COMMENT '车型',
   	$paginate = $Db->whereRaw($where)->select('order_list.*','user.car_make','user.car_line','user.car_model','user.shr_code','user.shr_name','user.shr_phone','user.shr_sheng','user.shr_shi','user.shr_xian','user.shr_adress','admin.company_name','admin.enable','admin.mouth_pay','admin.brand_service','admin.ad_project','admin.ad_alias','ser_id');
        if (in_array($input['state'],[5,6,9,10])){
            $paginate = $paginate->orderBy('feeds_time','DESC');
        }if (in_array($input['state'],[3,4,7,8])){
           $paginate = $paginate->orderBy('get_time','DESC');
       }
       $paginate = $paginate->orderBy('orli_type','DESC')
                ->orderBy('create_time','ASC')->paginate($page_size);
       //print_r(DB::getQueryLog());
   	//导出所需语句
       $data['where'] = $where;
       $data['sqls'] = DB::getQueryLog()[1];
   		$data['show_Menu'] = [
   				['show_name'=>"全部",'status'=>'1','show_num'=>'--'],
   				['show_name'=>"未接单",'status'=>'2','show_num'=>'--'],
   				['show_name'=>"安装中",'status'=>'3','show_num'=>'--'],
   				//['show_name'=>"延期订单",'status'=>'4','show_num'=>'--'],
   				['show_name'=>"待完成",'status'=>'5','show_num'=>'--'],
//                ['show_name'=>"延期审图",'status'=>'9','show_num'=>"--"],
//                ['show_name'=>"延期结算",'status'=>'10','show_num'=>"--"],
   				['show_name'=>"已完成",'status'=>'6','show_num'=>'--'],
   				//['show_name'=>"未预约",'status'=>'7','show_num'=>"--"],
   				//['show_name'=>"超时",'status'=>'8','show_num'=>"--"],
   		];


   	$all_button = BmmcService::whereButton($input['token'],$input['Pri_id']);
   	$export = BmmcService::getTopButton('export,patch,ordersDispatchDatas,patchGetOrder','',$all_button);
   	$data['button_top'] = $export['button_top']??[];//顶部按钮
   	$data['button_search'] = $export['button_search']??[];//搜索栏按钮
   	$list = CommonService::dataToArray($paginate->items());
   	if($list){
   		$list = self::getButtonDatas($all_button, $list, $session);
   		$data['list'] = $list;
   		$data['page'] = [
   				'count' => $paginate->total(),
   				'page'=>$paginate->currentPage(),
   				'page_size'=>$page_size,
   				'allPage'=>$paginate->lastPage()
   		];
   	}else{
   		$data['list'] = [];
   	}
   	return $data;
   }

   /**|---------------------------------------------------------------------------------
    * @name 公用条件
    * @param string ju_ordernum 订单单号
    * @retrun /multitype:array
    * @author dou 2021/9/23 16:53
    * |---------------------------------------------------------------------------------
   */
   public static function getCommonWhere ( $session ){
       $where = [];
       $where['gone_order_list.is_delete'] = 1;
       if ($session['admin_groupnew'] == 2 || $session['com_type'] ==2){
            if($session['admin_groupnew'] == 2){
                $where['gone_order_list.ser_id_searchin'] = $session['id'];
            }else{
                $where['gone_order_list.agency_id'] = $session['company_id'];
            }
       }else{
           if(!in_array($session['admin_groupnew'],[7,8])) {
               $where['p_id_searchin'] = $session['admin_pt_id'];
           }
          // $where['gone_order_list.p_id_searchin'] = $session['admin_pt_id'];
       }
       return $where;
   }

   /**
    * 获取按钮和数据
    * @param array $all_button
    * @param array $list
    * @return string
    * @author du 2021年8月18日下午3:40:48
    */
   public static function getButtonDatas($all_button,$list,$session){
        $time = date("Y-m-d",strtotime("+1 day"));
        $pts = PlatformService::getAll(true,'id');
        $orderStau = OrderService::getOrderStatusName();//获取订单状态名
       $delay_status_name = self::getDelayStatusName(true);
        $goodpic = PjBrandsService::getAllPic('name');//获取商品品牌图片 放在此处减少循环调取次数
       $pay_name = ServiceProviderService::getMouthPay(true);
       $brand_service = ServiceProviderService::getBrandService(true);
        foreach ($list as $k => $v){
            if($v['manhourfee'] == ''){
                $list[$k]['manhourfee'] = SettlementList::where('list_id',$v['serial_number'])->value('order_price')??0;
            }
            $button = [];
            //订单状态名
            $list[$k]['stauas_name'] = $orderStau[$v['stauas']]??'';
            $list[$k]['delay_status_name'] = $delay_status_name[$v['delay_status']];
            if(!in_array($v['stauas'], [50,55]) && $v['locklist_type']!=1){

            }else {
                if ($v['stauas'] == 10 || $v['stauas'] == 20) {

                    if($session['admin_groupnew']==3 && $v['ser_id']==$session['search_id']){
                        $button[] ='sendAgain';
                    }
                    $button[] = 'getOrder,refuseOrder';//day_time<'".$time
                } elseif (($v['stauas'] == 30) && (($v['day_time'] < $time) || $v['day_time'] == '')) {
                    if($session['admin_groupnew']==3 && $v['ser_id']==$session['search_id']){
                        $button[] ='sendAgain';
                    }
                    $button[] = 'refuseOrder,feedbackrefer,appointment,transferOrder,negprice';
                } elseif (($v['stauas'] == 30) && ($v['day_time'] > $time)) {
                    if($session['admin_groupnew']==3 && $v['ser_id']==$session['search_id']){
                        $button[] ='sendAgain';
                    }
                    $button[] = 'refuseOrder,feedbackrefer,negprice';
                } elseif ($v['stauas'] == 34) {
                    if($v['delay_status']==1){
                        $delay_status = ',delayStatus,auditpic';
                    }else{
                        $delay_status = ',returnDelayStatus';
                    }
                    $button[] = 'completeBohui,completeApply,negprice,getOrderPrice'.$delay_status;
                } elseif ($v['stauas'] == 40) {
                    $button[] = 'rejectedPending,logIve,getOrderPrice';
                }elseif ($v['stauas'] == 50 && $v['feeds_time'] != '') {
                    $button[] = 'logIve';
                }

                $button[] = 'updateManhourfee';

            }
            $button[] = 'addNote,sendSmsOrderListModel';
            if($session['admin_groupnew']==3 && $v['ser_id']!=$session['search_id']){
                $button = [];
            }
            $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']??[];

            if (isset($pts[$v['p_id']])){
                $list[$k]['pt_name'] = $pts[$v['p_id']]['pt_name'];
            }else{
                $list[$k]['pt_name'] = "暂无";
            }
            if($v['enable']!=1){
                $list[$k]['company_name'] = $v['company_name']."(已停用)";
            }
            $ad_project = trim($v['ad_project']);
            $ad_project = explode(',', $ad_project);
            if(in_array('3', $ad_project)) {
                if (isset($brand_service[$v['brand_service']])) {
                    $list[$k]['company_name'] = $list[$k]['company_name']."(" . $brand_service[$v['brand_service']] . ")";
                }
            }
            $list[$k]['pay_name'] = $pay_name[$v['mouth_pay']]??'未设定';

            /*if($v['reminder']==1){
                $reminder_num = OrderTime::where(['serial_number'=>$v['sys_num'],'is_type'=>'催单时间'])->count();
                $list[$k]['reminder_num'] = $reminder_num;
            }else{
                $list[$k]['reminder_num'] = 0;
            }*/



            $sin_num = SerInfor::where('sin_serial',$v['serial_number'])->value('sin_num');
            $list[$k]['reminder_num'] = $sin_num??0;

            //操作时间
            $list[$k]['ordertime'] = OrderListService::getOperTime($v['serial_number']);
            //获取负责人电话
            $cinfo = OrderListService::getUserHeadPhoneById($v['ser_id']);
            $list[$k]['head_phone'] = $cinfo['head_phone']??'';
            //获取门店地址（只有车模展示门店地址）
            if($v['category']==3){
                $ap = $cinfo['admin_province']??'';
                $ac = $cinfo['admin_city']??'';
                $acc = $cinfo['admin_county']??'';
                $add = $cinfo['admin_dressi']??'';

                $list[$k]['com_address'] = $ap.$ac.$acc.$add??'';
            }

            $list[$k]['cd_name'] = CategoryService::getNameByCdId($v['category']);
    //'shr_phone', 'shr_name', 'shr_sheng', 'shr_shi', 'shr_xian', 'shr_adress',
            $list[$k]['shr_name_jm'] = CommonService::hidePrivacy($v['shr_name'],1);
            $list[$k]['shr_phone_jm'] = CommonService::hidePrivacy($v['shr_phone'],2);
            $list[$k]['shr_adress_jm'] = '********';//CommonService::hidePrivacy($v['shr_adress'],3);
            //技师信息
            if($v['install_id']){
                $intallInfo = InstallPersonService::getInstallPersonById($v['install_id']);
                $list[$k]['intall_person'] =  $intallInfo['install_name'];
                $list[$k]['intall_phone'] = $intallInfo['install_phone'];
            }else{
                $list[$k]['intall_person'] =  '';
                $list[$k]['intall_phone'] = '';
            }

            //ordermsg表
            $msgArr = OrderService::getOrderMsg('', $goodpic,$v['order_goods_id']);
            //dump($msgArr);
            $list[$k]['goods_name'] = $msgArr['goods_name'];
            $list[$k]['goods_num'] = $msgArr['goods_num'];
            $list[$k]['goods_price'] = $msgArr['goods_price'];
            $list[$k]['goods_brand'] = $msgArr['goods_brand'];
            $list[$k]['goods_number'] = $msgArr['goods_number'];
            $list[$k]['goods_name_log'] = $msgArr['goods_name_log'];
            $list[$k]['goods_pic_path'] = $msgArr['goods_pic_path'];
            if($v['shr_code']!==''){
                $list[$k]['appoint_code'] = $v['shr_code'];
            }else {
                $list[$k]['appoint_code'] = $msgArr['appoint_code'];
            }
            unset($list[$k]['user']);
            unset($list[$k]['pt']);
            unset($list[$k]['ordermsg']);
            unset($list[$k]['admin']);
        }
        return $list;
   }

    /**|---------------------------------------------------------------------------------
     * @name 获取订单详情
     * @param string $order_num 订单单号
     * @retrun /multitype:array
     * @author dou 2021/9/24 9:45
     * |---------------------------------------------------------------------------------
    */
   public static function getDetailByOrder ( $order_num ){
       	$list = self::getOrderListBy('order_num', $order_num,'get',['id','serial_number','order_goods_id','install_id','intall_person','stauas','category']);
       	$status = OrderService::getOrderStatusName();
       	if($list) {
            foreach ($list as $k => $v) {
                $list[$k]['stauas_name'] = $status[$v['stauas']];
                $list[$k]['goods_name'] = OrderService::getOrderMsgBy('id', $v['order_goods_id'], ['goods_name']);
                $getOperTime = self::getOperTime($v['serial_number'], $v['id'],$v['category']);
                $list[$k]['order_time'] = $getOperTime['operation_time'];
                $list[$k]['pic_url'] = $getOperTime['feedback'];
            }
        }
       	return $list;
   }

    /**
     * @name 获取延期状态名
     * @return string[]
     * @author du
     * @date 2021/11/19
     */
   public static function getDelayStatusName($type=false){

       $data = [['type'=>1,'name'=>'正常'],['type'=>'2','name'=>'延期审图'],['type'=>'3','name'=>'延期结算']];
       if($type){
           $data = array_column($data, 'name','type');
       }
       return $data;
   }
/**|---------------------------------------------------------------------------------
     * @name 指派门店
     * @param string id 服务工单id
     * @param string ser_id 改派的服务门店
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/19 15:15
     * |---------------------------------------------------------------------------------
    */
    public static function sendAgain ( $request, $ip, $session ){
        $find_design_order = OrderList::where("id",$request['id'])
            ->where('is_delete', 1)
            ->first();
        // 判断是否已派单
        if (empty($find_design_order)) {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
        if ($find_design_order['stauas']!=30 && $find_design_order['stauas']!=20) {
            return ['ErrorCode' => ErrorInc::REQUEST_FORBIDDEN, 'ErrorMessage' => '当前状态不指派门店', 'Data' => []];
        }
        if($find_design_order['ser_id']!=$session['search_id']){
            return ['ErrorCode' => ErrorInc::REQUEST_FORBIDDEN, 'ErrorMessage' => '非直属订单不可改派', 'Data' => []];
        }
        DB::beginTransaction();
        $resultOrder = Orders::where('order_num',$find_design_order['order_num'])->update(['ser_id'=>$request['ser_id'],'order_status'=>20,'intall_person'=>'','intall_phone'=>'']);
        if($find_design_order['stauas']==30){
            $settListArr = SettlementList::where("sys_num",$find_design_order['sys_num'])->where("sett_status",'>',1)->first();
            if(!empty($settListArr)){
                // 该单已审核
                return ['ErrorCode' => ErrorInc::MYSQL_STEP_FAILED, 'ErrorMessage' => '存在结算工单不可指派', 'Data' => []];
            }
            $resultsettList = SettlementList::where("sys_num",$find_design_order['sys_num'])->delete();
        }else{
            $resultsettList = true;
        }
        $rest = OrderList::where('order_num',$find_design_order['order_num'])->update(['ser_id'=>$request['ser_id'],'stauas'=>20,'ol_distype'=>3,'intall_person'=>'','install_id'=>'','intall_phone'=>'','get_time'=>'']);
        if($rest && $resultsettList && $resultOrder){
            DB::commit();
            $session['install_name'] = $session['admin_acc'];
            CommonService::inserting_log('指派门店、',$find_design_order['sys_num'],'订单('.$find_design_order['order_num'].')','派工单列表',$session,$ip);//日志
            \App\Services\Api\MobileWeb\OrderListService::operating_time($find_design_order['serial_number'],'指派门店',date("Y-m-d H:i:s"),$find_design_order['order_num'],$session);//订单操作时间
            return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
        }else{
            DB::rollback();//回滚
            return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
        }
    }
   /**|---------------------------------------------------------------------------------
    * @name 获取销安装商品数量
    * @param array $type 区分类型 ser_id服务商id，p_id平台id，goods_id商品id，gs_bid品牌id
    * @param array $group 区分拆分类型
    * @param int $ser_id 服务商id
    * @param int $p_id 平台id
    * @retrun /multitype:array
    * @author dou 2021/11/21 11:20
    * |---------------------------------------------------------------------------------
   */
    public static function getServiceGoodNum ( $type = [] , $groupdata = [] , $ser_id = '' , $p_id = '' ){
        $sql = 'SELECT COUNT(a.id) as num';
        $group = [];
        if(in_array('ser_id', $groupdata)){
            $group[] = 'ser_id';
        }if(in_array('p_id', $groupdata)){
            $group[] = 'p_id';
        }if(in_array('goods_id', $groupdata)){
            $group[] = 'goods_id';
        }if(in_array('gs_bid', $groupdata)){
            $group[] = 'gs_bid';
        }
        if(in_array('ser_id', $type)){
            $sql .= ',a.ser_id';
        }if(in_array('p_id', $type)){
            $sql .= ',a.p_id';
        }if(in_array('goods_id', $type)){
            $sql .= ',b.goods_id';
        }if(in_array('gs_bid', $type)){
            $sql .= ',c.gs_bid';
        }
        $sql .= '  FROM gone_order_list as a LEFT JOIN gone_order_msg as b on a.order_goods_id = b.id LEFT JOIN gone_pj_goods as c on b.goods_id = c.pg_id where stauas = 40';
        if($ser_id){
            $sql .= ' and ser_id ='.$ser_id;
        }
        if($p_id){
            $sql .= ' and p_id ='.$p_id;
        }
        if($group){
            $sql .= '  GROUP BY '.implode(',', $group);
        }
        $num = DB::select($sql);
        if($num){
            $num = CommonService::dataToArray($num);
        }
        return $num;

    }

}
