<?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,
    Orders,
    InstallPerson,
    OrderTime,
    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删除
            ->where(function ($query) use ($request) {
                // 安装人员
                if (!empty($session['install_id']) && $session['user_type'] == 1) {
                    $query->where('intall_id', $session['install_id']);
                }
                // 状态
                if (!empty($request['stauas'])) {
                    if($request['stauas']==1){
                        // 未接单
                        $query->whereIn("stauas",[10,20]);
                    }elseif($request['stauas']==2){
                        // 已接单
                        $query->where("stauas",'>',20)->where('stauas','!=',50)->where('stauas','!=',55);
                    }elseif($request['stauas']==3){
                        // 安装中
                        $query->where("stauas",30);
                    }elseif($request['stauas']==4){
                        // 已完成
                        $query->whereIn("stauas",[34,40]);
                    }
                }
            })
            ->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]['button'][] = ['action'=>'contact','name'=>'预约时间'];
                            if(isset($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;
        }

        // 查询接单的状态统计数据,改为用上面查询出来的组装就行，因为数据格式完全变了，从订单表查了,所以根据上面的状态就可以获取数量了
        $wjd_num=0;
        $yjd_num=0;
        $stauas_count=[];
        if($wjd_num > 0){
            $stauas_count[]=['count'=>$wjd_num,'stauas'=>1];
        }
        if($yjd_num > 0){
            $stauas_count[]=['count'=>$yjd_num,'stauas'=>3];
        }

        $data['stauas_count'] = $stauas_count;
        if ($data['list']) {
            return ['ErrorCode' => 1, 'ErrorMessage' => '成功', 'Data' => $data];
        } else {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, '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' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '暂无数据', 'Data' => $list];
            }else{
                return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '无可派单技师', 'Data' => $list];
            }
        }else{
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未获取订单信息', 'Data' => ''];
        }
    }

    // 接单
    public static function receiving($request)
    {
        $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']=$_POST['order_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']=$_POST['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();
        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;
            }
        }
        if($restult==1){
            Management::where('trace_code',$orderListArr['serial_number'])->update($info);
            $arr['company_id']=$orderListArr['company_id'];
            $dou=SettlementList::insertGetId($arr);
            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=M('admin')->where("`id`='".$orderListArr['ser_id']."'")->field("`admin_acc`,`company_name`,`reward`")->find();//服务中心名称
            $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=M('order_time')->where("serial_number='".$orderListArr['serial_number']."' and is_type='接单时间'")->order('id DESC')->getField('create_time');//获取奖罚起始时间
                $money_type=M('setmoney_type')->where("sety_id=17")->getField("sety_id,sety_price");//->select();
                $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;
                    $settlement_money->add($money);
                    $all_price['all_price']=$settlement_money->where("sem_slid='".$douId."'")->SUM('sem_price');
                    $settlement_list->where("id='".$douId."'")->save($all_price);
                }
            }
            //end Dong
            $content = "订单".$is_bool."(".$orderListArr['serial_number'].")";
            $this->operating_time($orderListArr['serial_number'],'接单时间',date("Y-m-d H-i-s"),$orderListArr['sys_num']);//订单操作时间
            $this->add_thistory($orderListArr['serial_number'],'tih_acceptime',date("Y-m-d H:i:s"),$orderListArr['ser_id'],2);//添加历史时间
            $this->inserting_log('接单1，',$orderListArr['sys_num'],$content,'派工单');//日志
            //同步天猫
            $pt_type = M('pt')->where("`id`='".$orderListArr['p_id']."'")->getField('pt_type');
            if($pt_type==3) {

                $arr_up['inspectionStation'] = M('admin')->where("`id`='" . $orderListArr['ser_id'] . "'")->getField('company_name');

                $arr_up['workOrderId'] = $orderListArr['order_num'];
                $arr_up['carNumber'] = $instArr['plate_num'] ? $instArr['plate_num'] : '暂无';
                $arr_up['workerName'] = $instArr['install_name'];
                $arr_up['workerMobile'] = $instArr['install_phone'];
                $arr_up['channel'] = M('tm_proprietary')->where("`order_id`='" . $orderListArr['order_num'] . "'")->getField('channel');//
                $arr_up['timestamp'] = time() . '000';

                $arr_up['appKey'] = '2024032216801';
                $arr_up['app_key'] = '2024032216801';
                $arr_up['sign'] = $this->getSign($arr_up, 'b1e5c75530052abf221bfc9f3d2a591bdfa4ed7f');
                //   $url = 'https://opengw.ncarzone.com/api/workorder/uploadworker?';
                $url = 'https://opengw.ncarzone.com/api/workorder/uploadworker';


                ksort($arr_up);
                foreach ($arr_up as $k => $v) {
                    if (strpos($v, ' ')) {
                        $urldata[] = $k . "=" . urlencode($v);
                    } else {
                        $urldata[] = $k . "=" . $v;
                    }
                }
                $urldata = implode("&", $urldata);
                $ret_up = $this->requestPost($url, $urldata);
                $file_path = "./filedata/tm_uploadworker".date("Ym").".txt";
                $myfile = fopen($file_path, "a");
                $txt = date("Y-m-d H:i:s").$ret_up.'---'.$url.'---'.$urldata."\r\n";
                fwrite($myfile, $txt);
                fclose($myfile);

            }
            echo 1;exit;
        }else{
            echo 2;exit;
        }
    }

    // 拒单
    public static function refuse($request)
    {
        // 查询工单表信息
        $find_design_order = DB::table('orders')->where('id', $request['id'])
            ->where('is_delete', 1)
            ->select('id', 'sys_num', 'order_num', 'order_status','distrib_time','orders_sertatus', 'lock_type', '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'] == 0) {
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前工单未派单！', 'Data' => []];
        }
        if ($find_design_order['orders_sertatus'] > 1) {
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前工单已接单，无法拒单！', 'Data' => []];
        }
        if ($find_design_order['lock_type'] != 1) {
            return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '当前工单已锁定，无法拒单！', 'Data' => []];
        }

        // 根据订单id，查询工单是否有完成的
        $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();
        $find_orli_data = objectToArray($find_orli_data);
        foreach ($find_orli_data as $key => $value) {
            if ($value['stauas'] == 4) {
                return ['ErrorCode' => 500, 'ErrorMessage' => '有一个工单施工已完成，无法拒单', 'Data' => []];
            }
        }

        $user_info = CommonService::webgetUserInfo($request['api_token']);

        DB::beginTransaction();
        // 更改订单表信息
        $order_data=[];
        $order_data['order_status'] = 4; //订单状态：4设计完成（服务未派单）5施工未接单（服务已派单）6施工已接单
        $order_data['ser_id'] = 0;
        $order_data['seco_id'] = 0;
        $order_data['orders_sertatus'] = 0;
        $order_data['intall_person'] = '';
        $order_data['intall_phone'] = '';
        $order_data['update_time'] = date('Y-m-d H:i:s');
        // $order_data['distrib_time'] = '';
        $ord_edit_res = Orders::where('id', $find_design_order['id'])
                            ->update($order_data);

        // 更改工单信息
        $service_data=[];
        $service_data['stauas'] = 8; //工单状态：1未接单2已接单【废弃】3安装中4完成待审核5延期审图6延期结算7已完成8已拒单9已撤销
        $service_data['is_delete'] = 2; //是否删除：1正常2删除
        $service_data['service_state'] = 3; //技师服务状态：0未派单1未接单2已接单3已拒单
        $deor_res = DB::table('order_list')
                        ->where('sys_num', $find_design_order['sys_num'])
                        ->update($service_data);

        $orre_res=true;
        $settlement_res=true;

        foreach ($find_orli_data as $key => $value) {
            // 新增拒单记录
            $orre_data=[];
            $orre_data['ors_order_num'] = $find_design_order['order_num'];
            $orre_data['ors_sys_num'] = $find_design_order['sys_num'];
            $orre_data['ors_serial_number'] = $value['serial_number'];
            $orre_data['ors_ser_id'] = $find_design_order['ser_id'];
            $orre_data['ors_pid'] = $find_design_order['p_id'];
            $orre_data['ors_year'] = date('Y');
            $orre_data['ors_month'] = date('m');
            $orre_data['ors_day'] = date('d');
            $orre_data['ors_type'] = 2; //拒单类型1设计公司拒单2服务公司拒单
            if ($find_design_order['orders_sertatus'] == 1) {
                $orre_data['ors_status'] = 1; //接单状态1接单前拒单2接单后拒单
            } else {
                $orre_data['ors_status'] = 2;

            }
            $orre_data['ors_remarks'] = $request['remarks'];
            $orre_data['ors_adm_id'] = $request['admin_id'];
            $or_res = DB::table('order_refused')->insert($orre_data);
            if(!$or_res){
                $orre_res=$or_res;
            }
            // 接单后才有结算数据，更改工单结算单数据
            $settlement_data=[];
            $settlement_data['is_delete'] = 2;
            $settlement_data['update_time'] = date('Y-m-d H:i:s');
            $settl_res = DB::table('settlement_list')
                ->where('serial_number', $value['serial_number'])
                ->update($settlement_data);
            if(!$settl_res){
                $settlement_res=$settl_res;
            }
        }

        // 备注
        $remarks = '';
        if (Request::filled('remarks')) {
            $remarks = $request['remarks'];
            $rest = CommonService::accMe($find_design_order['sys_num'], '服务工单列表拒单', "拒单：" . $remarks,'', '1', $user_info->admin_groupnew, $user_info->install_name, $user_info->admin_id); //添加备注

            if (!$rest) {
                DB::rollback();
                return ['ErrorCode' => 500, 'ErrorMessage' => '备注添加失败', 'Data' => []];
            }
        }

        if ($ord_edit_res && $deor_res && $orre_res) {
            DB::commit();
            czrzLog("拒单，", $find_design_order['sys_num'], "移动端技师拒单", "订单系统", request::ip(), $user_info->install_name);
            return ['ErrorCode' => 1, 'ErrorMessage' => '成功', 'Data' => []];
        } else {
            DB::rollback();
            return ['ErrorCode' => 500, '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;
    }
    #计算奖惩金额以及评分
    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);
    }
}
