<?php

namespace App\Services\Api\MobileWeb;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\DB;
use BlueCity\Core\Inc\ErrorInc;
use App\Models\{Admin,
    GhPrice,
    GoodsBrand,
    InstallLine,
    Management,
    Note,
    OrderList,
    OrderMsg,
    OrderRejected,
    Orders,
    InstallPerson,
    OrderTime,
    SetmoneyType,
    SettlementList,
    SettlementMoney,
    SubmitPlease,
    User};
use App\Services\{BmmcService, Api\OrderManage\OrdersVehicleService, CommonService};

class OrderListService extends Model
{
    // 列表查询
    public static function index($request, $show_count = 10)
    {
        $session = $request['session'];
        // 查询列表
        $list_data = DB::table('order_list as ol')
            ->leftJoin('user as u', 'ol.customer_id', '=', 'u.id');
        $where['ser_id'] =$session['admin_id'];//服务商id
        $where['is_delete'] =1;//是否删除:1正常2删除
        if (!empty($session['install_id']) && $session['user_type'] == 1) {
            $where['intall_id'] =$session['install_id'];//技师id
        }
        if (!empty($request['stauas'])) {
            if($request['stauas'] == 1){
                // 未接单
                $wheres['stauas_searchin'] = [10,20];
            }elseif($request['stauas'] == 2){
                // 已接单
                $wheres['stauas_searchin'] = [30,34,40];
            }elseif($request['stauas']==3){
                // 安装中
                $wheres['stauas'] = 30;
            }elseif($request['stauas']==4){
                // 已完成
                $wheres['stauas_searchin'] = [34,40];
            }
        }
        $wheres = array_merge($where, $wheres);
        $wheres = CommonService::jointWhere($wheres);
        $list_data = $list_data->whereRaw($wheres)
            ->select('ol.id', 'order_num', 'serial_number', 'p_id','stauas', 'locklist_type', 'ol.sys_num','manhourfee', 'intall_person', 'intall_phone', 'day_time', 'order_goods_id', 'shr_name', 'shr_phone', 'shr_sheng', 'shr_shi', 'shr_xian', 'shr_adress','company_id','ser_id','get_time');
        if($request['stauas']!=1){
            $list_data = $list_data->orderby('get_time', 'desc');
        }
        $list_data = $list_data->orderby('ol.id', 'desc');

        $list_data = $list_data->paginate($show_count);
        $page['count'] = 0;
        $page['page'] = 0;
        $page['page_size'] = $show_count;
        $page['allPage'] = 0;
        $data['list'] = [];
        $data['page'] = $page;

        //  'negotiated_price as orli_actual_price'  服务费

        $list_items = $list_data->items();
        if ($list_items) {
            $list_items = CommonService::dataToArray($list_items);
            $company_id = array_unique(array_column($list_items, 'company_id')); //派单公司id
            $good_id = array_unique(array_column($list_items, 'order_goods_id')); //订单商品表id
            $serial_number = array_unique(array_column($list_items, 'serial_number')); //工单号
            //工单商品信息
            $goods_name = OrderMsg::whereIn('id',$good_id)->select('goods_name','goods_id','goods_num','id')->get();
            if($goods_name){
                $goods_name = CommonService::dataToArray($goods_name);
                $goods_name = CommonService::jointArrayKey($goods_name, 'id');
            }
            //查询派单公司信息
            $company_data = DB::table('company')
                ->whereIn('com_id', $company_id)
                ->pluck('com_name', 'com_id')->toArray();
            $getStauasName = self::getStauasName();
            //施工节点
            $installLine = InstallLine::whereIn("line_serm",$serial_number)->select('line_serm','line_state')->get();
            if($installLine){
                $installLine = CommonService::dataToArray($installLine);
                $installLine = CommonService::jointArrayKey($installLine, 'line_serm');
            }
            foreach ($list_items as $key => $value) {
                $list_items[$key]['stauasName'] = $getStauasName[$value['stauas']]['name'];
                //派单公司
                if (isset($company_data[$value['company_id']])) {
                    $list_items[$key]['company_name'] = $company_data[$value['company_id']];
                } else {
                    $list_items[$key]['company_name'] = '';
                }
                // 获取第一个字符
                if(in_array($value['stauas'],[10,20])){
                    $list_items[$key]['shr_phone'] = substr_replace($list_items[$key]['shr_phone'], '****', 3, 4);
                }
                $list_items[$key]['carmodel']=Note::where('note_type','客户车型')->where('orders_id',$value['sys_num'])->value('note_content');//车型信息
                $list_items[$key]['goods_name']=$goods_name[$value['order_goods_id']]['goods_name'];
                $list_items[$key]['goods_num']=$goods_name[$value['order_goods_id']]['goods_num'];
                if($value['stauas']>20){
                    $list_items[$key]['goods_price'] = SettlementMoney::where('sem_synum',$value['sys_num'])->where('sem_type',1)->sum('sem_price');
                }else{
                    $list_items[$key]['goods_price'] = GhPrice::where('goods_id',$goods_name[$value['order_goods_id']]['goods_id'])->where('ser_id',$value['ser_id'])->value('supply_price');
                    if(!$list_items[$key]['goods_price']){
                        $list_items[$key]['goods_price'] = GhPrice::where('goods_id',$goods_name[$value['order_goods_id']]['goods_id'])->where('ser_id',0)->value('supply_price');
                    }
                }
                $mb_first = mb_substr($value['shr_name'], 0, 1, 'utf-8');
                $list_items[$key]['first_name'] = $mb_first;
                $list_items[$key]['button'] = [];
                if($value['locklist_type'] != 2){
                    if(in_array($value['stauas'],[10,20])){
                        $list_items[$key]['button'] = [['action'=>'receiving','name'=>'接单'],['action'=>'refuse','name'=>'拒单']];
                    }elseif($value['stauas'] == 30){
                        if($request['stauas']==2){
                            $list_items[$key]['button'][] = ['action'=>'transferOfOrder','name'=>'改派'];
                        }if($request['stauas']==3){
                            $list_items[$key]['line_state'] = 1;
                            $list_items[$key]['button'][] = ['action'=>'contact','name'=>'预约时间'];
                            if(isset($installLine[$value['serial_number']]['line_state'])){
                                $list_items[$key]['line_state'] = $installLine[$value['serial_number']]['line_state'];
                                switch ( $installLine[$value['serial_number']]['line_state'] ){
                                    case 2:
                                        $list_items[$key]['button'][] = ['action'=>'lineStart','name'=>'出发'];
                                        break;
                                    case 3:
                                        $list_items[$key]['button'][] = ['action'=>'lineArrive','name'=>'抵达'];
                                        break;
                                    case 4:
                                        $list_items[$key]['button'][] = ['action'=>'startInstall','name'=>'开始安装'];
                                        break;
                                    case 5:
                                        $list_items[$key]['button'][] = ['action'=>'installFeedback','name'=>'申请完成'];
                                        break;
                                    default:
                                        ;
                                        break;
                                }
                            }
                        }
                        $list_items[$key]['button'][] = ['action'=>'copyInfo','name'=>'复制信息'];
                    }elseif($value['stauas'] == 34 || $value['stauas'] == 40){
                        $list_items[$key]['button'] = [['action'=>'copyInfo','name'=>'复制信息']];
                    }

                }
            }
            $page['count'] = $list_data->total(); //总数据个数
            $page['page'] = $list_data->currentPage(); //当前页面页码
            $page['page_size'] = $show_count; //一页显示多少个
            $page['allPage'] = $list_data->lastPage(); //表示最后一页的页码
            $data['list'] = $list_items;
            $data['page'] = $page;
        }

        // 查询接单的状态统计数据,改为用上面查询出来的组装就行，因为数据格式完全变了，从订单表查了,所以根据上面的状态就可以获取数量了
        $where['stauas_searchin'] = [10,20,30,34,40];
        $where = CommonService::jointWhere($where);
        $data_num = DB::table('order_list as ol')
            ->leftJoin('user as u', 'ol.customer_id', '=', 'u.id')->whereRaw($where)->groupBy('stauas')->select('stauas',DB::raw('count(*) as total'))->get();
        $wjd_num = 0;
        $yjd_num = 0;
        $azz_num = 0;
        $ywc_num = 0;
        if($data_num){
            $data_num = CommonService::dataToArray($data_num);
            foreach($data_num as $k => $v){
                switch ( $v['stauas'] ){
                    case 10:
                        $wjd_num = $wjd_num + $v['total'];
                        break;
                    case 20:
                        $wjd_num = $wjd_num + $v['total'];
                        break;
                    case 30:
                        $azz_num = $azz_num + $v['total'];
                        $yjd_num = $yjd_num + $v['total'];
                        break;
                    case 34:
                        $ywc_num = $ywc_num + $v['total'];
                        $yjd_num = $yjd_num + $v['total'];
                        break;
                    case 40:
                        $ywc_num = $ywc_num + $v['total'];
                        $yjd_num = $yjd_num + $v['total'];
                        break;
                    default:
                        ;
                        break;
                }

            }
        }
        $stauas_count=[];
        $stauas_count[] = ['count'=>$wjd_num,'stauas'=>1];
        $stauas_count[] = ['count'=>$yjd_num,'stauas'=>2];
        $stauas_count[] = ['count'=>$azz_num,'stauas'=>3];
        $stauas_count[] = ['count'=>$ywc_num,'stauas'=>4];
        $data['stauas_count'] = $stauas_count;
        if ($data['list']) {
            return ['ErrorCode' => 1, 'ErrorMessage' => '成功', 'Data' => $data];
        } else {
            return ['ErrorCode' => 1, 'ErrorMessage' => '暂无数据', 'Data' => $data];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取接单技师
     * @param int $request 请求参数
     * @param int $old_install_id 老技师id
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2024/9/10 16:36
     * |---------------------------------------------------------------------------------
    */
    public static function getPerson ( $request , $old_install_id = 0 ){
        $session = $request['session'];
        $order_list = OrderList::where('id',$request['id'])->select('ser_id','customer_id')->first();
        if($order_list){
            $dress = User::where('id',$order_list['customer_id'])->select('shr_sheng','shr_shi','shr_xian','shr_adress')->first();
            $end = CommonService::jingwei($dress['shr_sheng'], $dress['shr_sheng'].$dress['shr_shi'].$dress['shr_xian'].$dress['shr_adress']);
            if(empty($old_install_id)) {
                $list = InstallPerson::where('install_is_type',1)
                    ->where('delet_y',1)
                    ->where('admin_id',$session['admin_id'])
                    ->select('id','install_name','longitude','latitude','install_province','install_city','install_cuntry','install_address')
                    ->get();
            }else{
                $list = InstallPerson::where('install_is_type',1)
                    ->where('delet_y',1)
                    ->where('admin_id',$session['admin_id'])
                    ->where('id','!=',$old_install_id)
                    ->select('id','install_name','longitude','latitude','install_province','install_city','install_cuntry','install_address')
                    ->get();
            }
            if($list){
                $list = CommonService::dataToArray($list);
                foreach( $list as $kri => $vri ){
                    if($vri['longitude'] && $vri['latitude']){
                        $start = $vri['longitude'].','.$vri['latitude'];
                    }else{
                        $start = CommonService::jingwei($vri['install_province'],$vri['install_province'].$vri['install_city'].$vri['install_cuntry'].$vri['install_address']);
                    }
                    if($vri['install_address']=='' || $start ==''){
                        $list[$kri]['juli'] = '';
                        $list[$kri]['jl'] = 100000;
                        $lists[] = $list[$kri];
                        unset($list[$kri]);continue;
                    }else{
                        $jingwei[] = $start;
                    }
                }
                if(!empty($jingwei) && !empty($end)){
                    $jingwei = implode('|', $jingwei);
                    $res = CommonService::juli($jingwei,$end,2);
                }else{
                    $res = [];
                }
                $num_ = 0;
                foreach ($list as $k => $v) {
                    if (!isset($res[$num_])) {
                        $list[$k]['juli'] = '';
                        $list[$k]['jl'] = 100000;
                    } else {
                        $list[$k]['juli'] = round($res[$num_]['distance']/1000,2) . '公里';
                        $list[$k]['jl'] = round($res[$num_]['distance']/1000,2);
                    }
                    $num_++;
                }
                if(!empty($lists) && !empty($list)) {
                    $list = array_merge($list, $lists);
                }elseif (!empty($lists)){
                    $list = $lists;
                }
                $list = CommonService::resetListKey($list);
                foreach($list as $k => $v){
                    $num[]=$v['jl'];
                    if($v['jl'] == 100000){
                        unset($list[$k]['jl']);
                    }
                }
                array_multisort($num, SORT_NUMERIC ,SORT_ASC, $list);
                return ['ErrorCode' => 1, 'ErrorMessage' => '暂无数据', 'Data' => $list];
            }else{
                return ['ErrorCode' => 1, 'ErrorMessage' => '无可派单技师', 'Data' => $list];
            }
        }else{
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未获取订单信息', 'Data' => ''];
        }
    }

    // 接单
    public static function receiving($request,$ip)
    {
        $session = $request['session'];
        // 查询服务单表信息
        $orderListArr = OrderList::where('id',$request['id'])
            ->where('is_delete', 1)
            ->first();
        if(empty($orderListArr)){
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
        $orderListArr = CommonService::dataToArray($orderListArr);

        // 判断是否派单是否锁定
        if(!in_array($orderListArr['stauas'], [10,20])){
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前服务单不是待接单状态！', 'Data' => []];
        }
        if ($orderListArr['locklist_type'] != 1) {
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前服务单已锁定，无法接单！', 'Data' => []];
        }
        $MsgArr = OrderMsg::where('id',$orderListArr['order_goods_id'])
            ->select("goods_id","goods_name","goods_brand","goods_price")
            ->first();
        $goods_name = $MsgArr['goods_name'];
        $goods_id = $MsgArr['goods_id'];
        $goods_brands = $MsgArr['goods_brand'];
        $goods_name=trim($goods_name,',');
        $goods_id=trim($goods_id,',');
        $instArr = InstallPerson::where('id',$request['receive_install_id'])
            ->select("install_name","install_phone","plate_num")
            ->first();
        if(!$instArr){
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '技师不存在！', 'Data' => []];
        }
        $supply_price = GhPrice::where('goods_id',$MsgArr['goods_id'])
            ->where('ser_id',$orderListArr['ser_id'])
            ->orderBy('id','Desc')
            ->value('supply_price');
        if(!$supply_price){
            $supply_price = GhPrice::where('goods_id',$MsgArr['goods_id'])
                ->where('ser_id',0)
                ->orderBy('id','Desc')
                ->value('supply_price');
            if(!$supply_price){
                $supply_price='0.00';
            }
        }
        //end Dong
        $arr['sys_num']=$orderListArr['sys_num']; //系统单号
        $arr['order_num']=$orderListArr['order_num']; //平台单号
        $arr['serial_number']=$request['id']; //关联的order_list_id
        $arr['msg_id']=$orderListArr['order_goods_id']; //关联msg_id
        $arr['p_id']=$orderListArr['p_id']; //平台id
        $arr['list_id']=$orderListArr['serial_number']; //派工单编号
        $arr['ser_id']=$orderListArr['ser_id']; //服务中心id
        $arr['type']=2; //出售方式
        // 上门安装
        $arr['installperson']=$request['receive_install_id']; // 安装人id
        $arr['intall_person']=$instArr['install_name'];// 安装人名称
        $arr['intall_phone']=$instArr['install_phone'];// 安装人电话
        $is_bool="到店安装";
        $info['installation']=2;//安装分类(上门安装)
        // 供货价
        $arr['order_price']=$supply_price; //供货价
        // 总金额
        $all_price=$supply_price; //Dong
        $arr['all_price']=$all_price;
        // 结算状态
        $arr['sett_status']=1;
        // 工单状态
        $arr['list_service_type']=30;
        // 客户id
        $arr['customer_id']=$orderListArr['customer_id'];
        $arr['category']=$orderListArr['category'];
        $arr['sel_type']=$orderListArr['orli_type'];
        $arr['pay_types']=$orderListArr['pay_typel'];//支付方式
        $arr['goods_brand']=$goods_brands;
        // 锁定状态
        $submit_stauas = SubmitPlease::where('submit_sys_num',$orderListArr['sys_num'])->where('msg_id',$orderListArr['order_goods_id'])->orderBy('id','DESC')->value('submit_stauas');
        if($submit_stauas==1){
            $arr['locked']=2;
        }
        /**追  溯**/
        $times=date('Y-m-d H:i:s');
        $sometime=substr(date('Y-m-d H:i:s',strtotime("$times-2 month")),0,10);//入仓时间
        $info['goods_name']=$goods_name;//产品名称
        $info['manufacturer']=GoodsBrand::where("brand_name",$MsgArr['goods_brand'])
            ->where('company_id',$orderListArr['company_id'])
            ->value('brand_remark');//生产厂家
        $info['transport']=$sometime;//入仓时间
        $info['order_time']=substr($times,0,10);//下单时间
        $info['install_one']=$instArr['install_name'];//安装人
        $info['replacing_time']=substr(date('Y-m-d H:i:s',strtotime('+2 year')),0,10);//建议更换时间
        /**派工单**/
        $post['stauas']=30;//派工单状态
        $post['install_id']=$_POST['id'];//安装人id
        $post['intall_person']=$instArr['install_name'];//安装人姓名
        $post['intall_phone']=$instArr['install_phone'];//安装人电话
        $post['goods_brand']=$goods_brands;
        $post['goods_type']=3; //接单直接到安装中，略过检验 Dong
        $post['get_time']=date("Y-m-d H:i:s");
        /**订  单**/
        $get['order_status']=30;//订单状态
        $get['intall_person']=$instArr['install_name'];//安装人姓名
        $get['intall_phone']=$instArr['install_phone'];//安装人电话
        $returncount = OrderList::where('sys_num',$orderListArr['sys_num'])
            ->where('stauas',20)
            ->count();
        DB::beginTransaction(); //开启事务
        if($returncount==1){
            $restOrderList = OrderList::where('id',$request['id'])->update($post);
            $restOrder = Orders::where('sys_num',$orderListArr['sys_num'])->update($get);
            if($restOrderList && $restOrder){
                $restult=1;
            }else{
                $restult=0;
            }
        }else{
            $restOrderList = OrderList::where('id',$request['id'])->update($post);
            if($restOrderList){
                $restult=1;
            }else{
                $restult=0;
            }
        }
        $arr['company_id']=$orderListArr['company_id'];
        $arr['agency_id']=$orderListArr['agency_id'];
        $dou=SettlementList::insertGetId($arr);
        if($restult==1 && $dou){
            DB::commit();
            Management::where('trace_code',$orderListArr['serial_number'])->update($info);
            if($dou){
                self::calculates($dou,$orderListArr,$supply_price,$supply_price,$session);//计算奖惩金额以及评分
            }
            $weixin['ser_id'] = $_POST['id'];
            $weixin['order_num'] = $orderListArr['order_num']; //平台单号
            $weixin['goods_name'] = '安装服务';//$v['goods_name'];
            $weixin['serial_number'] = $orderListArr['serial_number'];
            $weixin['install_type'] = 2;
            CommonService::requestPost('http://zptzchat.bluearp.com/m/index.php/BindingAccount/push_order', $weixin);
            //begin Dong
            $company_name = Admin::where('id',$orderListArr['ser_id'])->select("admin_acc","company_name","reward")->first();//服务中心名称
            $douId = SettlementList::where('list_id',$orderListArr['serial_number'])->value('id');
            $res = SettlementMoney::where('sem_slid',$douId)->where('sem_type',17)->first();
            if(!$res){
                $payout_time = OrderTime::where("serial_number",$orderListArr['serial_number'])->where("is_type",'接单时间')->orderBy("id",'DESC')->value('create_time');//获取奖罚起始时间
                $money_type = SetmoneyType::where("sety_id",'17')->pluck('sety_price','sety_id');
                $zero1=time();//strtotime (date("Y-m-d H:i:s")); //当前时间  ,注意H 是24小时 h是12小时
                $zero2=strtotime ($payout_time);  //过年时间，不能写2014-1-21 24:00:00  这样不对
                $guonian=($zero1-$zero2)/60; //60s*60min*24h
                if($guonian<=17 && $company_name['reward']){
                    $money['sem_slid']=$douId;
                    $money['sem_synum']=$orderListArr['sys_num'];
                    $money['sem_creacter']=$company_name['admin_acc'];
                    $money['sem_price']=$money_type[17];
                    $money['sem_type']=17;
                    SettlementMoney::insert($money);
                    $all_price['all_price'] = SettlementMoney::where('sem_slid',$douId)->sum('sem_price');
                    SettlementList::where("id",$douId)->update($all_price);
                }
            }
            //end Dong
            $content = "订单".$is_bool."(".$orderListArr['serial_number'].")";
            self::operating_time($orderListArr['serial_number'],'接单时间',date("Y-m-d H-i-s"),$orderListArr['order_num'],$session);//订单操作时间
            self::add_thistory($orderListArr['serial_number'],'tih_acceptime',date("Y-m-d H:i:s"),$orderListArr['ser_id'],2,$session);//添加历史时间
            CommonService::inserting_log('接单1，',$orderListArr['sys_num'],$content,'派工单',$session,$ip);//日志
            return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
        }else{
            DB::rollback();//回滚
            return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
        }
    }

    // 拒单
    public static function refuse($request,$ip)
    {
        $session = $request['session'];
        $orderListArr = OrderList::where('id',$request['id'])->select("order_num","sys_num","stauas","ser_id","p_id","ol_dispamount","serial_number")->first();
        $returncount = OrderList::where('sys_num',$orderListArr['sys_num'])->select("serial_number")->get();
        $returncount = CommonService::dataToArray($returncount);
        $serial_number = array_unique(array_column($returncount, 'serial_number')); //派工单号
        if($orderListArr['stauas']<>10 && $orderListArr['stauas']<>20 && $orderListArr['stauas']<>30){
            // 拒单失败！该单状态不正确！
            return ['ErrorCode' => ErrorInc::MYSQL_STEP_FAILED, 'ErrorMessage' => '订单状态错误请刷新后操作：检索码01', 'Data' => []];
        }else{
            if($orderListArr['stauas']!=$_POST['stauas']){
                return ['ErrorCode' => ErrorInc::MYSQL_STEP_FAILED, 'ErrorMessage' => '订单状态错误请刷新后操作：检索码02', 'Data' => []];
            }
        }
        if(count($returncount) > 1 && $request['refuseType'] == 1){
            // 该订单有多款商品，该工单不可拒单
            return ['ErrorCode' => 201, 'ErrorMessage' => '订单包含多个商品是否全部拒单', 'Data' => []];
        }
        DB::beginTransaction(); //开启事务
        $rest = CommonService::accMe($orderListArr['sys_num'], '派工单列表web', "拒单，".$_POST['note_content'], implode(',', $serial_number), 2, 2, $session['install_name'], $session['install_id']);
        $resultOrderList = OrderList::where("sys_num",$orderListArr['sys_num'])->delete();
        if($orderListArr['stauas']==30){
            $settListArr = SettlementList::where("sys_num",$orderListArr['sys_num'])->where("sett_status",'>',1)->first();
            if(!empty($settListArr)){
                // 该单已审核
                return ['ErrorCode' => ErrorInc::MYSQL_STEP_FAILED, 'ErrorMessage' => '存在结算工单不可拒单', 'Data' => []];
            }
            $resultsettList = SettlementList::where("sys_num",$orderListArr['sys_num'])->delete();
        }else{
            $resultsettList = true;
        }
        $data['ser_id']=0;
        $data['order_status']=10;
        $resultOrder = Orders::where("sys_num",$orderListArr['sys_num'])->update($data);
        if($resultOrderList && $rest && $resultsettList && $resultOrder){
            DB::commit();
            OrderTime::whereIn('serial_number',$serial_number)->delete();//删除工单操作时间
            SettlementMoney::where('sem_synum',$orderListArr['sys_num'])->delete();//金额信息接单后生成
//            M("settlement_count")->where("`cou_synum`='".$_POST['sys_num']."'")->delete();//评分信息接单后生成
            DB::table('order_score')->whereIn("orsc_sernum",$serial_number)->delete();//评分信息接单后生成
            Management::whereIn('trace_code',$serial_number)->delete();
            CommonService::inserting_log('拒单，',$orderListArr['sys_num'],'订单('.$orderListArr['order_num'].')','派工单web',$session,$ip);//日志
            self::operating_time($orderListArr['serial_number'],'拒单时间',date("Y-m-d H:i:s"),$orderListArr['order_num'],$session);//订单操作时间
            OrderRejected::insert(['or_order_num'=>$orderListArr['order_num'],'or_ser_id'=>$orderListArr['ser_id'],'or_creact_time'=>date("Y-m-d H:i:s"),'or_centent'=>'门店自主拒单']);
            return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
        }else{
            DB::rollback();//回滚
            return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 预约安装
     * @param int id 订单单号
     * @param string day_time 预约是啊金
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/11 0:36
     * |---------------------------------------------------------------------------------
    */
    public static function contact ( $request , $ip){
        $session = $request['session'];
        $orderListArr = OrderTime::where("id",$request['id'])->select("order_num","sys_num","stauas","ser_id","p_id","customer_id","serial_number","ol_dispamount")->first();
        if($orderListArr['stauas'] <> 30){
            // 拒单失败！该单状态不正确！
            return ['ErrorCode' => ErrorInc::MYSQL_STEP_FAILED, 'ErrorMessage' => '订单状态错误请刷新后操作：检索码01', 'Data' => []];
        }
        $data['day_time']=$request['delay_time'];
        $res = Orders::where("sys_num",$orderListArr['sys_num'])->update($data);
        $ress = OrderList::where("id",$request['id'])->update($data);
        if($res && $ress){
            self::operating_time($orderListArr['serial_number'],'安装预约时间',date("Y-m-d H-i-s"),$orderListArr['order_num'],$session);//订单操作时间
            self::updateLineSrate($request['coordinate'], 2, $orderListArr['serial_number'], $orderListArr['sys_num'], $orderListArr['order_num']);
            return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
        }else{
            return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
        }
    }
    // 检验
    public static function inspect($request)
    {
        // 查询工单表信息
        $find_design_order = DB::table('orders')->where('id', $request['id'])
            ->where('is_delete', 1)
            ->select('id', 'sys_num', 'order_num', 'order_status', 'lock_type','orders_sertatus', 'ser_id', 'p_id')
            ->first();
        // 判断是否已派单
        if (empty($find_design_order)) {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
        $find_design_order = objectToArray($find_design_order);
        if ($find_design_order['orders_sertatus'] != 2) {
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前服务单不是待检验，无法检验！', 'Data' => []];
        }
        if ($find_design_order['lock_type'] != 1) {
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前服务单已锁定，无法检验！', 'Data' => []];
        }
        $user_info = CommonService::webgetUserInfo($request['api_token']);

        DB::beginTransaction();

        $find_orli_data = DB::table('order_list')
            ->where('sys_num', $find_design_order['sys_num'])
            ->where('order_num', $find_design_order['order_num'])
            ->where('is_delete', 1)
            ->select('id', 'serial_number', 'stauas')
            ->get()->toArray();
        if (empty($find_orli_data)) {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到服务工单', 'Data' => []];
        }
        $find_orli_data = objectToArray($find_orli_data);
        // 批量添加时间节点
        foreach ($find_orli_data as $key => $val) {
            timeLog($val['serial_number'], $find_design_order['order_num'], $user_info->install_name, "检验时间", date('Y-m-d H:i:s'));
        }

        // 更改工单信息
        $service_data=[];
        $service_data['stauas'] = 3; //工单状态：1未接单2已接单3安装中
        $service_data['service_state'] = 4; //技师服务状态：0未派单1未接单2已接单(未检验)3已拒单4已检验5安装中6完成待审核
        $deor_res = DB::table('order_list')
            ->where('sys_num', $find_design_order['sys_num'])
            ->where('order_num', $find_design_order['order_num'])
            ->where('is_delete', 1)
            ->update($service_data);

        $order_res=DB::table('orders')
                    ->where('id', $request['id'])
                    ->update(['orders_sertatus'=>4]);

        if ($deor_res && $order_res) {
            DB::commit();
            sertimeLog($find_design_order['sys_num'], $find_design_order['order_num'], $user_info->install_name, "检验时间", date('Y-m-d H:i:s'),$find_design_order['ser_id']);
            return ['ErrorCode' => 1, 'ErrorMessage' => '检验成功', 'Data' => []];
        } else {
            DB::rollback();
            return ['ErrorCode' => 500, 'ErrorMessage' => '失败', 'Data' => []];
        }
    }

    // 开始安装
    public static function startInstall($request)
    {
        // 查询工单表信息
        $find_design_order = DB::table('orders')->where('id', $request['id'])
            ->where('is_delete', 1)
            ->select('id', 'sys_num', 'order_num', 'order_status', 'lock_type','orders_sertatus', 'ser_id', 'p_id')
            ->first();
        // 判断是否已派单
        if (empty($find_design_order)) {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
        $find_design_order = objectToArray($find_design_order);
        if ($find_design_order['orders_sertatus'] != 4) {
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前服务单未检验！', 'Data' => []];
        }
        if ($find_design_order['lock_type'] != 1) {
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前服务单已锁定，无法拒单！', 'Data' => []];
        }
        $user_info = CommonService::webgetUserInfo($request['api_token']);

        DB::beginTransaction();

        $find_orli_data = DB::table('order_list')
            ->where('sys_num', $find_design_order['sys_num'])
            ->where('order_num', $find_design_order['order_num'])
            ->where('is_delete', 1)
            ->select('id', 'serial_number', 'stauas')
            ->get()->toArray();
        if (empty($find_orli_data)) {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到服务工单', 'Data' => []];
        }
        $find_orli_data = objectToArray($find_orli_data);
        // 批量添加时间节点
        foreach ($find_orli_data as $key => $val) {
            timeLog($val['serial_number'], $find_design_order['order_num'], $user_info->install_name, "开始安装", date('Y-m-d H:i:s'));
        }

        // 更改工单信息
        $service_data=[];
        $service_data['stauas'] = 3; //工单状态：1未接单2已接单3安装中
        $service_data['service_state'] = 5; //技师服务状态：0未派单1未接单2已接单3已拒单4已检验5安装中6已安装完成
        $deor_res = DB::table('order_list')
            ->where('sys_num', $find_design_order['sys_num'])
            ->where('order_num', $find_design_order['order_num'])
            ->where('is_delete', 1)
            ->update($service_data);

        $order_res=DB::table('orders')
                    ->where('id', $request['id'])
                    ->update(['orders_sertatus'=>5]);

        if ($deor_res && $order_res) {
            DB::commit();
            // czrzLog("拒单，", $find_design_order['serial_number'], "移动端技师拒单", "订单系统", request::ip(), $user_info->install_name);
            sertimeLog($find_design_order['sys_num'], $find_design_order['order_num'], $user_info->install_name, "开始安装", date('Y-m-d H:i:s'),$find_design_order['ser_id']);
            return ['ErrorCode' => 1, 'ErrorMessage' => '已开始施工', 'Data' => []];
        } else {
            DB::rollback();
            return ['ErrorCode' => 500, 'ErrorMessage' => '开始施工失败', 'Data' => []];
        }
    }

    // 申请完成
    public static function installFeedback($request)
    {
        // 查询工单表信息
        $find_design_order = DB::table('orders')->where('id', $request['id'])
            ->where('is_delete', 1)
            ->select('id', 'sys_num', 'order_num', 'order_status', 'lock_type','orders_sertatus', 'ser_id', 'p_id')
            ->first();
        // 判断是否已派单
        if (empty($find_design_order)) {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
        $find_design_order = objectToArray($find_design_order);
        if ($find_design_order['orders_sertatus'] != 5) {
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前工单未安装！', 'Data' => []];
        }
        if ($find_design_order['lock_type'] != 1) {
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前工单已锁定，无法拒单！', 'Data' => []];
        }
        $user_info = CommonService::webgetUserInfo($request['api_token']);


        // 获取所有的工单数据
        $order_list = DB::table('order_list')
                        ->where('sys_num', $find_design_order['sys_num'])
                        ->where('is_delete', 1)
                        ->select('id', 'serial_number', 'service_state','orli_reject')
                        ->get();
        if (empty($order_list)) {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到服务工单', 'Data' => []];
        }
        $order_list = objectToArray($order_list);
        // 顺便判断一下工单状态
        foreach ($order_list as $key => $val) {
            if ($val['service_state'] != 5 && $val['service_state'] != 6) {
                return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前工单不是施工反馈状态！', 'Data' => []];
            }
        }
        DB::beginTransaction();

        // 更改工单信息
        $service_data=[];
        $service_data['stauas'] = 4; //工单状态：1未接单2已接单3安装中4待完成5已完成6已拒单7已撤销
        $service_data['service_state'] = 6; //技师服务状态：0未派单1未接单2已接单3已拒单4已检验5安装中6已安装完成
        $service_data['update_time'] = date('Y-m-d H:i:s');
        $service_data['orli_reject'] = 1;

        // 更改服务工单结算表
        $seli_edit_data=[];
        $seli_edit_data['list_service_type'] = $service_data['stauas']; //派工单状态：1未接单2已接单【废弃】3安装中4完成待审核5已完成6已拒单7已撤销8延期审图9延期结算
        $seli_edit_data['update_time'] = date('Y-m-d H:i:s'); //更新时间

        $is_edit=0;
        $is_over=0;
        $deor_res=true;
        foreach ($order_list as $key => $val) {

            if($val['service_state']==6 && $val['orli_reject']==1){
                $is_edit++;
                continue;
            }
            // 部分完成则判断是否有上传图片
            if($request['type']==1){
                // 判断是否有图片反馈
                $feed_res=Db::table('feedback')
                            ->where('gl_id',$val['id'])
                            ->where('is_delete', 1)
                            ->select("id")
                            ->get()->toArray();
                if(empty($feed_res)){
                    $is_over++;
                    continue;
                }
            }
            $is_edit++;

            // 更改工单信息
            $orli_res = DB::table('order_list')
                ->where('id', $val['id'])
                ->update($service_data);
            if(!$orli_res){
                $deor_res=$orli_res;
            }

            $seli_edit_res = DB::table('settlement_list')
                                ->where('serial_number', $val['serial_number'])
                                ->where('list_id', $val['id'])
                                ->update($seli_edit_data);
            timeLog($val['serial_number'], $find_design_order['order_num'], $user_info->install_name, "反馈时间", date('Y-m-d H:i:s'));
        }

        $order_data=[];
        $order_data['order_status'] = 8;
        $order_data['update_time'] = date('Y-m-d H:i:s');
        $order_data['orders_sertatus']=5;
        if($is_over==0){
            $order_data['orders_sertatus']=6;
        }
        // 更改订单信息
        $ord_res = DB::table('orders')
            ->where('id', $find_design_order['id'])
            ->update($order_data);

        if ($deor_res && $ord_res) {
            DB::commit();

            $str=$order_data['orders_sertatus']==5?'部分反馈':'反馈时间';

            sertimeLog($find_design_order['sys_num'], $find_design_order['order_num'], $user_info->install_name, $str, date('Y-m-d H:i:s'),$find_design_order['ser_id']);
            return ['ErrorCode' => 1, 'ErrorMessage' => '施工申请完成', 'Data' => []];
        } else {
            DB::rollback();
            return ['ErrorCode' => 500, 'ErrorMessage' => '申请完成失败', 'Data' => []];
        }
    }

    // 施工图片反馈
    public static function imageFeedback($request){
        // 查询工单表信息
        $find_design_order = DB::table('order_list')
            ->where('id', $request['id'])
            ->where('is_delete', 1)
            ->select('id', 'serial_number', 'sys_num', 'order_num', 'ord_id', 'service_state', 'lock_state', 'ser_id', 'p_id')
            ->first();

        // 判断是否已派单
        if (empty($find_design_order)) {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
        $find_design_order = objectToArray($find_design_order);
        if ($find_design_order['service_state'] != 5) {
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前工单状态错误！', 'Data' => []];
        }

        $find_inpe_data = DB::table('install_person')
            ->where('admin_id', $request['admin_id'])
            ->where('delet_y', 1)
            ->select('install_name', 'install_phone')
            ->first();
        $find_inpe_data = objectToArray($find_inpe_data);

        // 查询成员账号信息表
        $find_adm_data = DB::table('admin')
            ->where('id', $request['admin_id'])
            ->select('admin_acc', 'company_name')
            ->first();
        $find_adm_data = objectToArray($find_adm_data);

        $image_url=$request['image_url'];
        $image_id=$request['image_id'];
        $image_type=$request['image_type'];
        if($image_url =='undefined'){
            return ['ErrorCode' => 500, 'ErrorMessage' => $image_type.'上传失败请重新上传', 'Data' => []];
        }
        DB::beginTransaction();

        $edit_res=true;
        // 不是0 则为编辑
        if($image_id != 0){
            $image_data=Db::table('feedback')
                            ->where('gl_id',$request['id'])
                            ->where('is_delete', 1)
                            ->where('id',$image_id)
                            ->select('feedback_pic')
                            ->first();
            if(!empty($image_data)){
                $image_path=$image_data->feedback_pic;
                // http://3m127.bluearp.com/storage/app/public/image/2022/11/15/166848425637152.jpg

                // http://3m127.bluearp.com/storage/image/2022/11/15/166848420917354.jpg

                // url 路径里 app/public 被忽略了；
                // $image_path=str_replace('storage/image','storage/app/public/image',$image_path);
                // $image_path=substr($image_path,strpos($image_path,'storage/app'));
                $image_path=substr($image_path,strpos($image_path,'storage'));

                // dd(11);

                if(file_exists($image_path)){
                    unlink($image_path);
                }
                Db::table('feedback')
                            ->where('gl_id',$request['id'])
                            ->where('is_delete', 1)
                            ->where('id',$image_id)
                            ->delete();
            }
        }
        $add_feed=[];
        $add_feed['type'] = 1; //图片类型
        $add_feed['gl_id'] = $request['id']; //反馈关联id
        $add_feed['install_name'] = $find_inpe_data['install_name']; //安装人员姓名
        $add_feed['install_phone'] = $find_inpe_data['install_phone']; //安装电话
        $add_feed['install_remark'] = ''; //安装备注
        $add_feed['install_time'] = date('Y-m-d H:i:s'); //安装时间
        $add_feed['admin_id'] = $request['admin_id']; //所属服务中心id
        $add_feed['company_name'] = $find_adm_data['company_name']; //服务中心名称
        $add_feed['feedback_status'] = 2; //是否安装
        $add_feed['feedback_pic'] = $image_url; //凭证图片
        $add_feed['sys_num'] = 'rwfk' . $request['id']; //所属服务中心id
        $add_feed['is_type'] = 2; //1微信2第三方
        $add_feed['type_name'] = $image_type; //类型名称

        $add_feed_id = DB::table('feedback')->insertGetId($add_feed);

        if ($add_feed_id && $edit_res) {
            DB::commit();
            return ['ErrorCode' => 1, 'ErrorMessage' => '图片回传成功', 'Data' => ['feed_id'=>$add_feed_id]];
        } else {
            DB::rollback();
            return ['ErrorCode' => 500, 'ErrorMessage' => $add_feed_id.'图片回传失败'.$edit_res, 'Data' => []];
        }
    }

    // 施工时 车牌车架号反馈
    public static function LicenseFeedback($request){
        // 查询工单表信息
        $find_design_order = DB::table('orders')->where('id', $request['id'])
            ->where('is_delete', 1)
            ->select('id', 'sys_num', 'order_num', 'order_status', 'lock_type','orders_sertatus', 'ser_id', 'p_id')
            ->first();
        // 判断是否已派单
        if (empty($find_design_order)) {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
        $find_design_order = objectToArray($find_design_order);
        if ($find_design_order['orders_sertatus'] != 5) {
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前服务单状态错误！', 'Data' => []];
        }
        if ($find_design_order['lock_type'] != 1) {
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前服务单已锁定，无法反馈！', 'Data' => []];
        }

        $license_plate=$request['license_plate'];

        if($license_plate != ''){
            $repeat_res = DB::table('order_list')
                    ->where('sys_num', $find_design_order['sys_num'])
                    ->where('is_delete', 1)
                    ->where('id','<>',$request['gd_id'])
                    ->where('license_plate',$license_plate)
                    ->select('id')
                    ->get()
                    ->toArray();
            if(!empty($repeat_res)){
                return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '车牌/车架号填写重复', 'Data' => []];
            }
        }

        $res=DB::table('order_list')
                    ->where('sys_num', $find_design_order['sys_num'])
                    ->where('is_delete', 1)
                    ->where('id',$request['gd_id'])
                    ->update(['license_plate'=>(string)$license_plate,'update_time'=>date('Y-m-d H:i:s')]);

        if($res){
            return ['ErrorCode' => 1, 'ErrorMessage' => '回传车架号成功', 'Data' => []];
        }else{
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '保存车架号失败', 'Data' => []];
        }
    }


    // 获取工单反馈信息
    public static function getFeedback($request)
    {

        // 查询服务单表信息
        $orders_data = DB::table('orders')
                                ->where('id', $request['id'])
                                ->where('is_delete', 1)
                                ->select('id','sys_num')
                                ->first();
        if (empty($orders_data)) {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到服务单', 'Data' => []];
        }

        // 获取所有的工单数据
        $order_list = DB::table('order_list')
                        ->where('sys_num', $orders_data->sys_num)
                        ->where('is_delete', 1)
                        ->select('id','serial_number',"sys_num", 'license_plate','service_state','orli_reject')
                        ->orderBy('service_state')
                        ->get();
        if (empty($order_list)) {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到工单', 'Data' => []];
        }

        $order_list = objectToArray($order_list);

        $no_pic=[];
        $no_pic['gl_id'] = 0;
        $no_pic['feedback_pic'] = config('apisystem.HTTP_URL') . 'image/icon/webapp_no_pictures.png';
        $no_pic['type_name'] = '暂无图片';

        foreach ($order_list as $key => $val) {
            // 查询反馈信息
            $list_data = DB::table('feedback')
                            ->where('gl_id',$val['id'])
                            ->where('is_delete', 1)
                            ->select("id",'gl_id', 'feedback_pic', 'type_name')
                            ->orderBy('type_name','asc')
                            ->get()->toArray();
            if (empty($list_data)) {
                $list_data = [$no_pic];
            }

            $order_list[$key]['list_data']=$list_data;
        }
        return ['ErrorCode' => 1, 'ErrorMessage' => '获取信息成功', 'Data' => $order_list];
    }

    // 详情
    public static function info($request)
    {
        $find_orli_data=DB::table('orders as ol')
            ->leftJoin('user as u', 'ol.new_customer_id', '=', 'u.id')
            ->where('ol.id', $request['id'])
            ->where('is_delete', 1) //是否删除:1正常2删除
            ->select('ol.id', 'ol.sys_num',"ol.ser_id", 'order_num', 'ol.sys_num as serial_number','customer_id','ol.reminder', 'p_id', 'orders_sertatus as service_state','ol.lock_type as lock_state', 'intall_person', 'intall_phone', 'crma_id', 'ol.distrib_time as create_time', 'shr_name', 'shr_phone', 'shr_sheng', 'shr_shi', 'shr_xian', 'shr_adress','company_id','admin_id')
            ->first();

        // 查询工单表信息
            // time_consuming  接单耗时    orli_actual_price 服务总价

        // 判断是否已派单
        if (empty($find_orli_data)) {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
        $find_orli_data = objectToArray($find_orli_data);
        $find_orli_data['company_name'] = Db::table('company_data')->where("cm_id",$find_orli_data['company_id'])->value('cm_name');
        $find_orli_data['admin_phone'] = Db::table('admin_infor')->where("admin_id",$find_orli_data['admin_id'])->value('phone');
        $find_orli_data['orli_actual_price']=(float)Db::table('order_list')
                                                    ->where('sys_num',$find_orli_data['sys_num'])
                                                    ->where('ser_id', $find_orli_data['ser_id'])
                                                    ->where('is_delete', 1)
                                                    ->sum("negotiated_price");

        $find_orli_data['complete_num']=(int)Db::table('order_list')
                                                    ->where('sys_num',$find_orli_data['sys_num'])
                                                    ->where('ser_id', $find_orli_data['ser_id'])
                                                    ->where('is_delete', 1)
                                                    ->where('service_state', 6)
                                                    ->where('orli_reject', 1)
                                                    ->count();

        $consu_create_time = DB::table('orderserver_time')
                                            ->where('ser_id',$find_orli_data['ser_id'])
                                            ->where('serial_number',$find_orli_data['sys_num'])
                                            ->where('order_num',$find_orli_data['order_num'])
                                            ->where('is_type','接单时间')
                                            ->orderBy('id','desc')
                                            ->select('create_time')
                                            ->first();
        $find_orli_data['time_consuming'] = '';
        if(!empty($consu_create_time)){
            $find_orli_data['time_consuming']=calculateTimeInterval($find_orli_data['create_time'], $consu_create_time->create_time);
        }

        // 查询车辆信息
        $find_vehicle = OrdersVehicleService::getOrderVehicle($find_orli_data['sys_num']);
        $find_orli_data['orders_vehicle'] = $find_vehicle;

        // 查询贴装工艺
        $find_crma_data = DB::table('craft_manage')
            ->where('crma_id', $find_orli_data['crma_id'])
            ->select('crma_name')
            ->first();
        $find_crma_data = objectToArray($find_crma_data);
        if ($find_crma_data) {
            $find_orli_data['crma_name'] = $find_crma_data['crma_name']; //施工工艺名称
        } else {
            $find_orli_data['crma_name'] = ''; //施工工艺名称
        }
        // 查询设计图
        $find_deod_data = DB::table('design_order_detail')
            ->where('sys_num', $find_orli_data['sys_num']) //订单编号
            ->where('ord_id', $find_orli_data['id']) //订单id
            ->where('audit_state', 2) //审核状态：1已提交2已通过3已驳回
            ->where('is_delete', 1) //是否删除：1正常2删除
            ->select('sys_num', 'design_drawing')
            ->get()->toArray();
        $find_orli_data['design_order_detail'] = $find_deod_data;
        // 查询备注
        $find_note = DB::table('note')
            ->where('orders_id', $find_orli_data['sys_num'])
            ->where('is_delet', 1)
            ->select('note_content', 'note_type', 'note_time', 'note_name')
            ->orderBy('note_time', 'desc')
            ->get()->toArray();
        $find_note = objectToArray($find_note);
        $find_orli_data['orders_note'] = $find_note;
        $find_orli_data['shr_phone'] = substr_replace($find_orli_data['shr_phone'], '****', 3, 4);
        unset($find_orli_data['crma_id']);
        return ['ErrorCode' => 1, 'ErrorMessage' => '获取成功', 'Data' => $find_orli_data];
    }

    // 获取技师
    public static function getInstallPerson($request)
    {
        // 查询工单表信息
        $find_inpe_data = InstallPerson::where('delet_y', 1)
            ->where('admin_id', $request['admin_id'])
            ->where('install_is_type', 1) //状态：1启用2停用
            ->where(function ($query) use ($request) {
                if (!empty($request['install_name'])) {
                    $query->where('check_code', 'like', '%' . $request['install_name'] . '%')
                        ->orWhere('install_name', 'like', '%' . $request['install_name'] . '%');
                }
            })
            ->select('id', 'check_code', 'install_name')
            ->get()->toArray();
        return ['ErrorCode' => 1, 'ErrorMessage' => '获取成功', 'Data' => $find_inpe_data];
    }

    // 获取标签
    public static function getLabel($request)
    {
        // 查询工单表信息
        $find_sety_data = DB::table('setmoney_type')
            ->where('lt_parent_id', 694)
            ->where('lt_statues', 1)
            ->where(function ($query) use ($request) {
                if (!empty($request['sety_name'])) {
                    $query->where('sety_name', 'like', '%' . $request['sety_name'] . '%');
                }
            })
            ->select('sety_id', 'sety_name')
            ->get()->toArray();
        return ['ErrorCode' => 1, 'ErrorMessage' => '获取成功', 'Data' => $find_sety_data];
    }

    // 获取操作记录
    public static function operatingRecord($request)
    {
        // 查询操作表信息
        $find_data = DB::table('orderserver_time')
            ->where('serial_number', $request['serial_number'])
            ->where('ser_id', $request['admin_id'])
            ->select('create_time', 'is_type')
            ->orderby('id', 'desc')
            ->get()->toArray();
        return ['ErrorCode' => 1, 'ErrorMessage' => '获取成功', 'Data' => $find_data];
    }
    /**|---------------------------------------------------------------------------------
     * @name 工单状态
     * @param string $type
     * @retrun  /multitype:array
     * @author dou 2024/9/10 10:51
     * |---------------------------------------------------------------------------------
    */
    public static function getStauasName ( $type = true ){
        $stauasName = [['type'=>'10','name'=>'未接单'],['type'=>'20','name'=>'未接单'],['type'=>'30','name'=>'安装中'],['type'=>'34','name'=>'待审核'],['type'=>'40','name'=>'已完成']];
        if($type){
            $stauasName = CommonService::jointArrayKey($stauasName, 'type');
        }
        return $stauasName;
    }
    // 订单操作时间
    public static function operating_time($num,$type,$time,$order_num,$session){
        $data['serial_number']=$num;
        $data['create_name']=$session['install_name'];
        $data['is_type']=$type;
        $data['create_time']=$time;
        $data['order_num']=$order_num;
        $result = OrderTime::insert($data);
        if($result){
            return 1;
        }else{
            return 2;
        }
    }
    //添加时间戳
    public static function add_thistory ($number,$timetype,$time,$ser_id,$type,$session){
        if($type==1){
            $poss[$timetype]=strtotime($time);
            $poss['tih_serid']=$ser_id;
            $poss['tih_number']=$number;
            $poss['company_type']=$session['install_name'];
            DB::table('time_history')->insert($poss);
        }else{
            $poss[$timetype]=strtotime($time);
            DB::table('time_history')->where("tih_number",$number)->update($poss);
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 同步施工节点
     * @param string $coordinate 坐标
     * @param string $line_state 节点状态
     * @param string $line_serm 工单号
     * @param string $line_sysnum 系统单号
     * @param string $line_number 单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/11 0:45
     * |---------------------------------------------------------------------------------
    */
    public static function updateLineSrate ( $coordinate , $line_state , $line_serm , $line_sysnum , $line_number ){
          $install_line = InstallLine::where("line_serm",$line_serm)->first();
          switch ( $line_state ){
              case 2:
                  $line['line_contact'] = $coordinate;
                  $line['line_contact_time'] = date("Y-m-d H:i:s");
                  break;
              case 3:
                  $line['line_start'] = $coordinate;
                  $line['line_start_time'] = date("Y-m-d H:i:s");
                  break;
              case 4:
                  $line['line_arrive'] = $coordinate;
                  $line['line_arrive_time'] = date("Y-m-d H:i:s");
                  break;
              case 5:
                  $line['line_task'] = $coordinate;
                  $line['line_task_time'] = date("Y-m-d H:i:s");
                  break;
              case 6:
                  $line['line_end'] = $coordinate;
                  $line['line_end_time'] = date("Y-m-d H:i:s");
                  break;
              default:
                  return false;
                  break;
          }
          $line['line_lasttime'] = date("Y-m-d H:i:s");
          $line['line_state'] = $line_state;
          if(empty($install_line)){
              $line['line_serm'] = $line_serm;
              $line['line_sysnum'] = $line_sysnum;
              $line['line_number'] = $line_number;
              $line['line_serm'] = $line_serm;
              $res = InstallLine::insert($line);
          }else{
              $line_states = $line_state-1;
                if($line_states < $install_line['line_state']){
                    return false;
                }else{
                    $res = InstallLine::where("line_serm",$line_serm)->update($line);
                }
          }
        return $res;
    }
    #计算奖惩金额以及评分
    public static function calculates($dou,$orderListArr,$supply_price,$manhourfee,$session){
        #商品供货金额
        $money['sem_slid'] = $dou;
        $money['sem_synum'] = $orderListArr['sys_num'];
        $money['sem_price'] = $manhourfee;
        $money['sem_creacter'] = $session['install_name'];
        $money['sem_type'] = 1;
        $money['add_time'] = date("Y-m-d H:i:s");
        SettlementMoney::insert($money);
//        #开始计算奖惩金额以及评分
//        $payout_time = OrderTime::where('serial_number',$orderListArr['serial_number'])
//            ->where('is_type','起始时间')
//            ->orderBy('id','DESC')
//            ->value('create_time');//获取奖罚起始时间
//        $zero1 = time();
//        $zero2 = strtotime($payout_time);
//        $guonian = ($zero1-$zero2)/60;
//        #计算评分
//        if($guonian<=5){
//            $score['orsc_grade'] = 5;
//        }if($guonian>5 && $guonian<=10){
//            $score['orsc_grade'] = 2;
//        }if($guonian>10){
//            $score['orsc_grade'] = 1;
//        }
//        $score['orsc_sernum'] = $orderListArr['serial_number'];
//        $score['orsc_slid'] = $dou;
//        $score['orsc_creacter'] = $session['install_name'];
//        $score['orsc_type'] = 1;
//        DB::table("order_score")->insert($score);
//        //默认生成平台评分十分
//        $scoreq['orsc_grade'] = 5;
//        $scoreq['orsc_sernum'] = $orderListArr['serial_number'];
//        $scoreq['orsc_slid'] = $dou;
//        $scoreq['orsc_creacter'] = $session['install_name'];
//        $scoreq['orsc_type']=2;
//        DB::table("order_score")->insert($score);
    }
}
