<?php

namespace App\Services\Api\MobileWeb;

use App\Http\Controllers\Api\SynJdPurchaseController;
use App\Http\Controllers\Api\SynJdRapidController;
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,
    Company,
    Feedback,
    GhPrice,
    GoodsBrand,
    InstallLine,
    Management,
    Note,
    OrderList,
    OrderMsg,
    OrderRejected,
    Orders,
    InstallPerson,
    OrderTime,
    SetmoneyType,
    SettlementList,
    SettlementMoney,
    SubmitPlease,
    User};
use App\Services\{BmmcService,
    Api\OrderManage\OrdersVehicleService,
    CommonService,
    DealPicService,
    OrderService,
    TicketListService,
    UserService};
use OSS\OssClient;
use OSS\Core\OssException;
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');
        if($session['user_type']==3){
            $where['agency_id'] =$session['company_id'];//服务商id
            if(isset($request['search_company_id']) && !empty($request['search_company_id'])){//仅展示本门店
                $where['ser_id'] = $request['search_company_id'];//服务商id
            }
        }else {
            $where['ser_id'] = $session['admin_id'];//服务商id
        }
        $where['is_delete'] =1;//是否删除:1正常2删除
        if (!empty($session['install_id']) && $session['user_type'] == 1) {
            $where['install_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];
            }
        }
        if(!empty($request['keyword'])) {
            $wheres['search_searchor']['order_num_like'] = $request['keyword'];
            $wheres['search_searchor']['shr_name_like'] = $request['keyword'];
        }
        $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','install_id');
        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');
                    }
                }
                if (!empty($session['install_id']) && $session['user_type'] == 1) {
                    $list_items[$key]['goods_price'] = 0;
                }
                $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])){
                        if($session['user_type']==3 && $value['ser_id']!=$session['admin_id']){
                        }else {
                            if ($session['user_type'] != 1) {
                                $list_items[$key]['button'][] = ['action' => 'receiving', 'name' => '接单'];
                                $list_items[$key]['button'][] = ['action' => 'refuse', 'name' => '拒单'];
                            }
                            if($session['user_type']==3 && $value['ser_id']==$session['admin_id']){
                                $list_items[$key]['button'][] = ['action'=>'sendAgain','name'=>'指派门店'];
                            }
                        }
                        $list_items[$key]['button'][] = ['action'=>'copyInfo','name'=>'复制信息'];
                    }elseif($value['stauas'] == 30){
                        if($session['user_type']==3 && $value['ser_id']!=$session['admin_id']){
                            $list_items[$key]['button'][] = ['action'=>'copyInfo','name'=>'复制信息'];

                        }else {
                            if ($request['stauas'] == 2) {
                                if($session['user_type']==3 && $value['ser_id']==$session['admin_id']){
                                    $list_items[$key]['button'][] = ['action'=>'sendAgain','name'=>'指派门店'];
                                }
                                if ($session['user_type'] != 1) {
                                    $list_items[$key]['button'][] = ['action' => 'transferOfOrder', 'name' => '改派'];
                                }
                                if($value['stauas'] == 30){
                                    if (isset($installLine[$value['serial_number']]['line_state']) && $list_items[$key]['line_state']>1) {
                                        $list_items[$key]['button'][] = ['action' => 'contact', 'name' => '修改预约'];
                                    }else{
                                        $list_items[$key]['button'][] = ['action' => 'contact', 'name' => '预约时间'];
                                    }
                                }
                            }
                            if ($request['stauas'] == 3) {
                                $list_items[$key]['line_state'] = 1;
                                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;
                                    }
                                    if($list_items[$key]['line_state']==1){
                                        $list_items[$key]['button'][] = ['action' => 'contact', 'name' => '预约时间'];
                                    }else{
                                        $list_items[$key]['button'][] = ['action' => 'contact', 'name' => '修改预约'];
                                    }
                                } else {
                                    $list_items[$key]['button'][] = ['action' => 'contact', 'name' => '预约时间'];
                                }
                            }
                            $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['session'] = $session;
            $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(in_array($request['stauas'], [1,2]) && $session['user_type'] == 1){
            return ['ErrorCode' => 1, 'ErrorMessage' => '暂无数据', 'Data' => $data];
        }
        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'])
            ->where('ser_id', $session['admin_id'])
            ->where('is_delete', 1)
            ->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('ser_id', $session['admin_id'])
            ->where('is_delete', 1)
            ->first();
        if(empty($orderListArr)){
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
        $orderListArr = CommonService::dataToArray($orderListArr);
        $getJdOrderStatus = OrderService::getJdOrderStatus($orderListArr['order_num'], $orderListArr['p_id']);
        if($getJdOrderStatus['ErrorCode']!=1){
            return ['ErrorCode' => $getJdOrderStatus['ErrorCode'], 'ErrorMessage' => $getJdOrderStatus['ErrorMessage'], 'Data' => []];
        }
        // 判断是否派单是否锁定
        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","goods_num")
            ->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';
            }
        }
//        $supply_price = $supply_price*$MsgArr['goods_num'];
//        $supply_price = sprintf("%.2f", $supply_price);
        //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']=$request['receive_install_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();
//            if($orderListArr['p_id']=='39' || $orderListArr['p_id']=='44' || $orderListArr['p_id']=='50' || $orderListArr['order_num']=='3545412002269559'){
//                $filename = 'jdOrderEx' . date('Ym');
//                CommonService::addLog('出库', $orderListArr['p_id'], $orderListArr['order_num'], $filename);
                self::syncExpress($orderListArr['order_num'], $orderListArr['p_id']);
//            }
            Management::where('trace_code',$orderListArr['serial_number'])->update($info);
            if($dou){
                self::calculates($dou,$orderListArr,$supply_price,$supply_price,$session);//计算奖惩金额以及评分
            }
            $weixin['ser_id'] = $request['receive_install_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);
            CommonService::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'].")(".$instArr['install_name'].")";
            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,'派工单web',$session,$ip);//日志
            return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
        }else{
            DB::rollback();//回滚
            return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
        }
    }
    // 出库
    public static function syncExpress($order_num,$pt_id)
    {
        try {

            $filename = 'jdOrderEx' . date('Ym');
            $token = DB::table('jdpop_token')->where('status', 1)->where('pt_id', $pt_id)->select('app_key', 'app_secret', 'access_token', 'pt_id', 'appName', 'type')->first();
            if ($token) {
                if ($token['type'] == 1) {
                    $url_ex = "http://116.196.75.172/index.php/GetOrder/syncExpress";//出库
                    $res_ex = [];
                    $res_ex['appKey'] = $token['app_key'];    //appkey
                    $res_ex['appSecret'] = $token['app_secret'];//secret
                    $res_ex['accessToken'] = $token['access_token'];    //token
                    $res_ex['skb_bh'] = $order_num;//$vv['orderId'];
                    $res_ex['jdid'] = 1274;
                    $res_ex['kd_number'] = '';
                    $res_ex['estimateDate'] = date("Y-m-d H:i:s");
                    $result = CommonService::requestPost($url_ex, $res_ex);
                    //出库同步
                    CommonService::addLog('出库', json_encode($res_ex), $order_num, $filename);
                    $reta = json_decode($result, true);
                    if ($reta['jingdong_pop_order_shipment_responce']['sopjosshipment_result']['success'] == true) {
                        CommonService::addLog('派单成功出库', $result, $order_num, $filename);
                    } else {
                        CommonService::addLog('派单出库失败', $result, $order_num, $filename);
                    }
                }elseif ($token['type'] == 3 && $order_num=='202606301725'){
                    $data['order_num'] = $order_num;
                    $data['accessToken'] = $token['access_token'];
                    $data['appKey'] = $token['app_key'];
                    $data['appsecret'] = $token['app_secret'];
                    $SynJdPurchaseController = new SynJdPurchaseController();
                    $result = $SynJdPurchaseController->jdOrderEx($data);
                    //出库同步
                    $filename = 'jdOrderEx' . date('Ym');
                    CommonService::addLog('出库', json_encode($data), $order_num, $filename);
                    $reta = json_decode($result, true);
                    if ($reta['jingdong_purchase_order_stock_out_responce']['result']['code'] == 1) {
                        CommonService::addLog('派单成功出库', $result, $order_num, $filename);
                    } else {
                        CommonService::addLog('派单出库失败', $result, $order_num, $filename);
                    }
                }elseif ($token['type'] == 4){
                    $data['orderId'] = $order_num;
                    $data['access_token'] = $token['access_token'];
                    $data['app_key'] = $token['app_key'];
                    $data['app_secret'] = $token['app_secret'];
                    $SynJdRapidController = new SynJdRapidController();
                    $result = $SynJdRapidController->orderSerllerDelivery($data);
                    //出库同步
                    $filename = 'jdOrderEx' . date('Ym');
                    CommonService::addLog('出库', json_encode($data), $order_num, $filename);
                    $reta = json_decode($result, true);
                    if ($reta['code'] == 0) {
                        CommonService::addLog('派单成功出库', $result, $order_num, $filename);
                    } else {
                        CommonService::addLog('派单出库失败', $result, $order_num, $filename);
                    }
                }
            }
            return true;
        }catch (Exception $e)
        {
            CommonService::addLog('操作异常', $e->getMessage(), $order_num.'---'.$pt_id, $filename);
            return true;
        }
    }

    // 拒单
    public static function refuse($request,$ip)
    {
        $session = $request['session'];
        $orderListArr = OrderList::where('id',$request['id'])
            ->where('ser_id', $session['admin_id'])
            ->where('is_delete', 1)
            ->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']!=$request['stauas']){
                return ['ErrorCode' => ErrorInc::MYSQL_STEP_FAILED, 'ErrorMessage' => '订单状态错误请刷新后操作：检索码02', 'Data' => []];
            }
        }
        if(count($returncount) > 1 && $request['refuseType'] == 1){
            // 该订单有多款商品，该工单不可拒单
            return ['ErrorCode' => 201, 'ErrorMessage' => '订单包含多个商品是否全部拒单', 'Data' => []];
        }
        $compamy_name = Admin::where('id',$orderListArr['ser_id'])->value('company_name');
        DB::beginTransaction(); //开启事务
        if(isset($request['setmoney_type']) && !empty($request['setmoney_type'])) {
            $remarks = $request['setmoney_name'].';'.$request['remarks'];
        }else{
            $remarks = $request['remarks'];
        }
        $rest = CommonService::accMe($orderListArr['sys_num'], '派工单列表web', "拒单，（".$compamy_name."）".$remarks, implode(',', $serial_number), 2, 2, $session['install_name'], $session['admin_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){
            if(isset($request['setmoney_type']) && !empty($request['setmoney_type'])) {
                $labstate = SetmoneyType::where('sety_id', $request['setmoney_type'])->first();
                if (strstr((string)$labstate['sety_price'], '-')) {
                    $price = substr($labstate['sety_price'], 1);
                } else {
                    $price = $labstate['sety_price'];
                }
                if ($price > 0) {
                    $user = UserService::getUserBy('id', $orderListArr['customer_id'], ['shr_name', 'shr_phone', 'shr_sheng', 'shr_shi', 'shr_xian', 'shr_adress']);
                    $dress = $user['shr_sheng'] . " " . $user['shr_shi'] . " " . $user['shr_xian'] . " " . $user['shr_adress'];
                    TicketListService::createTicket($orderListArr['order_num'], $orderListArr['serial_number'], '', '', $orderListArr['ser_id'], $price, 1, $labstate['sety_name'], $session['install_name'], '', 1, 1, '', '', $user['shr_name'], $user['shr_phone'], $dress, $orderListArr['company_id']);
                }
                \App\Services\OrderListService::creatAftersale($labstate['lt_type'], $orderListArr['order_num'], $orderListArr['serial_number'], 2, 20, 25, $request['setmoney_type'], $orderListArr['p_id'], $orderListArr['ser_id'], $request['remarks'], $session['install_name'], $session['install_name'], $orderListArr['company_id']);
            }
            DB::commit();
            $goodid=DB::table('order_msg')->where('sys_num',$orderListArr['sys_num'])->whereNotIn('goods_service',[2,3])->select('goods_id','goods_num')->get()->toArray();
            //库存有关
            if ($goodid){
                $gsql = "";
                $sql = "INSERT INTO `gone_invenrecor`( `iv_serid`, `iv_goodid`, `iv_num`,`iv_serial`,`iv_ordernum`,`iv_company_id`) VALUES";
                foreach( $goodid as $kgi => $vgi){
                    $gsql .= "UPDATE `gone_inventory` SET `inv_num`=`inv_num`+".$vgi['goods_num']." WHERE `inv_serid`='".$orderListArr['ser_id']."' and `inv_goodid`='".$vgi['goods_id']."' and `inv_company_id`='".$orderListArr['company_id']."';";
                    $sql .= "('".$orderListArr['ser_id']."','".$vgi['goods_id']."','+".$vgi['goods_num']."','".$orderListArr['serial_number']."','".$orderListArr['order_num']."','".$orderListArr['company_id']."'),";
                }

                $sql = trim($sql,',');
                DB::insert($sql);
                DB::update($gsql);
            }
            OrderTime::whereIn('serial_number',$serial_number)->delete();//删除工单操作时间
            SettlementMoney::where('sem_synum',$orderListArr['sys_num'])->delete();//金额信息接单后生成
//            M("settlement_count")->where("`cou_synum`='".$orderListArr['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 = OrderList::where("id",$request['id'])
            ->where('ser_id', $session['admin_id'])
            ->where('is_delete', 1)
            ->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['day_time'];
        DB::beginTransaction(); //开启事务
        $res = Orders::where("sys_num",$orderListArr['sys_num'])->update($data);
        $ress = OrderList::where("id",$request['id'])->update($data);
        if($res && $ress){
            DB::commit();
            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']);
            CommonService::inserting_log('预约安装，',$orderListArr['sys_num'],'订单('.$orderListArr['serial_number'].')','派工单web',$session,$ip);//日志
            return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
        }else{
            DB::rollback();//回滚
            return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 改派
     * @param int id 订单id
     * @param int receive_install_id 接单技师id
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/11 11:50
     * |---------------------------------------------------------------------------------
    */
    public static function transferOfOrder ( $request , $ip ){
        $session = $request['session'];
        $orderListArr = OrderList::where("id",$request['id'])
            ->where('ser_id', $session['admin_id'])
            ->where('is_delete', 1)
            ->first();
        if($orderListArr) {
            if($orderListArr['stauas']<>30){
                return ['ErrorCode' => ErrorInc::MYSQL_STEP_FAILED, 'ErrorMessage' => '当前状态不可改派！', 'Data' => []];
            }
            $install_person = InstallPerson::where('id',$request['receive_install_id'])->first();
            if($install_person) {
                $orderlist['install_id'] = $install_person['id'];
                $orderlist['intall_person'] = $install_person['install_name'];
                $orderlist['intall_phone'] = $install_person['install_phone'];
                DB::beginTransaction(); //开启事务
                $res = OrderList::where("id",$request['id'])->update($orderlist);
                $order['intall_person'] = $install_person['install_name'];
                $order['intall_phone'] = $install_person['install_phone'];
                $rea = Orders::where("order_num",$orderListArr['order_num'])->update($order);
                if ($orderListArr['stauas'] > 20) {
                    $settl['intall_person'] = $install_person['install_name'];
                    $settl['intall_phone'] = $install_person['install_phone'];
                    $ree = SettlementList::where("order_num",$orderListArr['order_num'])->update($settl);
                } else {
                    $ree = true;
                }
                $install = InstallLine::where('line_serm',$orderListArr['serial_number'])->first();
                $install = CommonService::dataToArray($install);
                if(!empty($install)) {
                    if($install['line_state']>2) {
                        $req = InstallLine::where('line_serm', $orderListArr['serial_number'])->update(['line_state' => 2, 'line_lasttime' => date("Y-m-d H:i:s")]);
                    }else{
                        $req =true;
                    }
                }else {
                    $req = self::updateLineSrate('', 1, $orderListArr['serial_number'], $orderListArr['sys_num'], $orderListArr['order_num']);
                }
                if ( $res && $rea && $ree && $req ) {
                    DB::commit();
                    $content = "订单(".$orderListArr['serial_number'].")(".$install_person['install_name'].")";
                    CommonService::inserting_log('改派，',$orderListArr['sys_num'],$content,'派工单web',$session,$ip);//日志
                    return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
                } else {
                    DB::rollback();//回滚
                    return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => [$res,$rea,$ree,$req]];
                }
            }else{
                return ['ErrorCode' => ErrorInc::BUSINESS_FORBID, 'ErrorMessage' => '技师不存在！', 'Data' => []];
            }
        }else{
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 技师出发
     * @param string id 订单id
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/11 19:58
     * |---------------------------------------------------------------------------------
    */
    public static function lineStart ( $request , $ip ){
        $session = $request['session'];
        $orderListArr = OrderList::where("id",$request['id'])
            ->where('ser_id', $session['admin_id'])
            ->where('is_delete', 1)
            ->first();
        if($orderListArr) {
            if($orderListArr['stauas']<>30){
                return ['ErrorCode' => ErrorInc::MYSQL_STEP_FAILED, 'ErrorMessage' => '当前状态不可改派！', 'Data' => []];
            }
            $res = self::updateLineSrate($request['coordinate']??'', 3, $orderListArr['serial_number'], $orderListArr['sys_num'], $orderListArr['order_num']);
            if($res) {
                CommonService::inserting_log('技师出发，', $orderListArr['sys_num'], '订单(' . $orderListArr['serial_number'] . ')', '派工单web', $session, $ip);//日志
                return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
            }else{
                return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
            }
        }else{
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 技师抵达
     * @param string id 订单id
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/11 19:58
     * |---------------------------------------------------------------------------------
     */
    public static function lineArrive ( $request , $ip ){
        $session = $request['session'];
        $orderListArr = OrderList::where("id",$request['id'])
            ->where('ser_id', $session['admin_id'])
            ->where('is_delete', 1)
            ->first();
        if($orderListArr) {
            if($orderListArr['stauas']<>30){
                return ['ErrorCode' => ErrorInc::MYSQL_STEP_FAILED, 'ErrorMessage' => '当前状态不可改派！', 'Data' => []];
            }
            $res = self::updateLineSrate($request['coordinate']??'', 4, $orderListArr['serial_number'], $orderListArr['sys_num'], $orderListArr['order_num']);
            if($res) {
                CommonService::inserting_log('技师抵达，', $orderListArr['sys_num'], '订单(' . $orderListArr['serial_number'] . ')', '派工单web', $session, $ip);//日志
                return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
            }else{
                return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
            }
        }else{
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 开始作业
     * @param string id 订单id
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/11 19:58
     * |---------------------------------------------------------------------------------
     */
    public static function startInstall ( $request , $ip ){
        $session = $request['session'];
        $orderListArr = OrderList::where("id",$request['id'])
            ->where('ser_id', $session['admin_id'])
            ->where('is_delete', 1)
            ->first();
        if($orderListArr) {
            if($orderListArr['stauas']<>30){
                return ['ErrorCode' => ErrorInc::MYSQL_STEP_FAILED, 'ErrorMessage' => '当前状态不可改派！', 'Data' => []];
            }
            $res = self::updateLineSrate($request['coordinate']??'', 5, $orderListArr['serial_number'], $orderListArr['sys_num'], $orderListArr['order_num']);
            if($res) {
                CommonService::inserting_log('开始施工，', $orderListArr['sys_num'], '订单(' . $orderListArr['serial_number'] . ')', '派工单web', $session, $ip);//日志
                return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
            }else{
                return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
            }
        }else{
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
    }

    // 详情
    public static function info( $request )
    {
        $session = $request['session'];
        $orderListArr = OrderList::where("id",$request['id'])
            ->where('ser_id', $session['admin_id'])
            ->where('is_delete', 1)
            ->first();
        if($orderListArr) {
            $data['id'] = $orderListArr['id'];//订单id
            $data['sys_num'] = $orderListArr['sys_num'];//订单id
            $data['order_num'] = $orderListArr['order_num'];//订单单号
            $data['serial_number'] = $orderListArr['serial_number'];//工单号
            $data['day_time'] = $orderListArr['day_time'];//预约时间
            $data['intall_person'] = $orderListArr['intall_person'];//技师姓名
            $data['stauas'] = $orderListArr['stauas'];//工单状态
            $data['carmodel']=Note::where("note_type","客户车型")
                ->where("orders_id",$orderListArr['sys_num'])
                ->value("note_content");
            $installLine = InstallLine::where('line_serm',$orderListArr['serial_number'])->value('line_state');
            if(empty($installLine)){
                $installLine = 1;
            }
            $data['line_state'] = $installLine;//工单节点
            $orderMsg = OrderMsg::where("id",$orderListArr['order_goods_id'])->first();
            $data['goods_name'] = $orderMsg['goods_name'];//商品名称
            $data['goods_num'] = $orderMsg['goods_num'];//商品数量
            $data['locklist_type'] = $orderListArr['locklist_type'];//锁定状态
            $user = User::where("id",$orderListArr['customer_id'])->first();
            if(in_array($orderListArr['stauas'],[10,20])){
                $data['shr_phone'] = substr_replace($user['shr_phone'], '****', 3, 4);
            }else{
                $data['shr_phone'] = $user['shr_phone'];
            }
            $data['shr_name'] = $user['shr_name'];
            $mb_first = mb_substr($user['shr_name'], 0, 1, 'utf-8');
            $data['first_name'] = $mb_first;
            $data['shr_sheng'] = $user['shr_sheng'];
            $data['shr_shi'] = $user['shr_shi'];
            $data['shr_xian'] = $user['shr_xian'];
            $data['install_id'] = $orderListArr['install_id'];
            $data['shr_adress'] = $user['shr_adress'];
            $data['company_name'] = Company::where("com_id",$orderListArr['company_id'])->value('com_name');//订单id
            if($orderListArr['stauas']>20){
                $data['goods_price'] = SettlementMoney::where('sem_synum',$orderListArr['sys_num'])->where('sem_type',1)->sum('sem_price');
            }else{
                $data['goods_price'] = GhPrice::where('goods_id',$orderMsg['goods_id'])->where('ser_id',$orderListArr['ser_id'])->value('supply_price');
                if(!$data['goods_price']){
                    $data['goods_price'] = GhPrice::where('goods_id',$orderMsg['goods_id'])->where('ser_id',0)->value('supply_price');
                }
            }
            $note = Note::where('orders_id',$orderListArr['sys_num'])
                ->whereRaw("public_state = 2 and ((note_group!=2 and note_group!=3) or note_adid=".$session['admin_id'].")")
                ->select('note_content')
                ->get();
            if($note){
                $note = CommonService::dataToArray($note);
                $data['note'] = $note;//备注
                $data['note_num'] = count($note);//备注数量
            }else{
                $data['note'] = $note;//备注
                $data['note_num'] = 0;//备注数量
            }
            if($orderListArr['locklist_type'] != 2){
                if(in_array($orderListArr['stauas'],[10,20])){
                    if($session['user_type']==3 && $orderListArr['ser_id']!=$session['admin_id']){
                    }else {
                        $data['button'][] = ['action' => 'receiving', 'name' => '接单'];
                        $data['button'][] = ['action' => 'refuse', 'name' => '拒单'];
                        if($session['user_type']==3 && $orderListArr['ser_id']==$session['admin_id']){
                            $data['button'][] = ['action'=>'sendAgain','name'=>'指派门店'];
                        }
                        $data['button'][] = ['action' => 'copyInfo', 'name' => '复制信息'];
                    }
                }elseif($orderListArr['stauas'] == 30){
                    if($session['user_type']==3 && $orderListArr['ser_id']!=$session['admin_id']){
                        $data['button'][] = ['action'=>'copyInfo','name'=>'复制信息'];

                    }else {
                        if ($request['stauas'] == 2) {
                            if ($session['user_type'] != 1) {
                                $data['button'][] = ['action' => 'transferOfOrder', 'name' => '改派'];
                            }
                            if($orderListArr['stauas'] == 30){
                                if (isset($installLine) && $installLine>1) {
                                    $data['button'][] = ['action' => 'contact', 'name' => '修改预约'];
                                }else{
                                    $data['button'][] = ['action' => 'contact', 'name' => '预约时间'];
                                }
                            }

                            if($session['user_type']==3 && $orderListArr['ser_id']==$session['admin_id']){
                                $data['button'][] = ['action'=>'sendAgain','name'=>'指派门店'];
                            }
                        }
                        if ($request['stauas'] == 3) {
                            if (isset($installLine)) {
                                switch ($installLine) {
                                    case 2:
                                        $data['button'][] = ['action' => 'lineStart', 'name' => '出发'];
                                        break;
                                    case 3:
                                        $data['button'][] = ['action' => 'lineArrive', 'name' => '抵达'];
                                        break;
                                    case 4:
                                        $data['button'][] = ['action' => 'startInstall', 'name' => '开始安装'];
                                        break;
                                    case 5:
                                        $data['button'][] = ['action' => 'installFeedback', 'name' => '申请完成'];
                                        break;
                                    default:
                                        ;
                                        break;
                                }
                                if($installLine==1){
                                    $data['button'][] = ['action' => 'contact', 'name' => '预约时间'];
                                }else {
                                    $data['button'][] = ['action' => 'contact', 'name' => '修改预约'];
                                }
                            } else {
                                $data['button'][] = ['action' => 'contact', 'name' => '预约时间'];
                            }
                        }
                        $data['button'][] = ['action' => 'copyInfo', 'name' => '复制信息'];
                    }
                }elseif($orderListArr['stauas'] == 34 || $orderListArr['stauas'] == 40){
                    $data['button'] = [['action'=>'copyInfo','name'=>'复制信息']];
                }

            }else{
                $data['button'] = [['action'=>'copyInfo','name'=>'复制信息']];
            }
            $data['feedback']['feedback_pic1'] = '';
            $data['feedback']['type_name1'] = self::getPicName(1);
            $data['feedback']['feedback_pic2'] = '';
            $data['feedback']['type_name2'] = self::getPicName(2);
            $data['feedback']['feedback_pic3'] = '';
            $data['feedback']['type_name3'] = self::getPicName(3);
            $data['feedback']['feedback_pic4'] = '';
            $data['feedback']['type_name4'] = self::getPicName(4);
            $data['feedback']['feedback_pic5'] = '';
            $data['feedback']['type_name5'] = self::getPicName(5);
            $data['feedback']['feedback_pic6'] = '';
            $data['feedback']['type_name6'] = self::getPicName(6);
            $feedback = Feedback::where('gl_id',$orderListArr['id'])
                ->where('is_delect',1)
                ->select('type','type_name','feedback_pic')
                ->get();
            if($feedback){
                foreach($feedback as $k => $v){
                    if($v['type_name'] == ''){
                        $v['type_name'] = self::getPicName($v['type']);
                    }
                    switch ( $v['type'] ){
                        case 1:
                            $data['feedback']['feedback_pic1'] = $v['feedback_pic'];
                            $data['feedback']['type_name1'] = $v['type_name'];
                            break;
                        case 2:
                            $data['feedback']['feedback_pic2'] = $v['feedback_pic'];
                            $data['feedback']['type_name2'] = $v['type_name'];
                            break;
                        case 3:
                            $data['feedback']['feedback_pic3'] = $v['feedback_pic'];
                            $data['feedback']['type_name3'] = $v['type_name'];
                            break;
                        case 4:
                            $data['feedback']['feedback_pic4'] = $v['feedback_pic'];
                            $data['feedback']['type_name4'] = $v['type_name'];
                            break;
                        case 5:
                            $data['feedback']['feedback_pic5'] = $v['feedback_pic'];
                            $data['feedback']['type_name5'] = $v['type_name'];
                            break;
                        case 6:
                            $data['feedback']['feedback_pic6'] = $v['feedback_pic'];
                            $data['feedback']['type_name6'] = $v['type_name'];
                            break;
                    }
                }
            }
            return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => $data];
        }else{
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, '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' => []];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 添加图片
     * @param string id 工单id
     * @param string file 图片信息
     * @param string type 图片类型
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/12 11:56
     * |---------------------------------------------------------------------------------
    */
    public static function addPic ( $request , $ip ){
        $session = $request['session'];
        $orderListArr = OrderList::where("id",$request['id'])
            ->where('ser_id', $session['admin_id'])
            ->where('is_delete', 1)
            ->first();
        if($orderListArr) {
            $request['path']='./FeekBack/'.date('Ym');
//            $rea = DealPicService::upload($request);
            $rea = DealPicService::addPic($request['file'],$request['path'],$request['type']);
            if($rea){
                $feedback = Feedback::where('type',$request['type'])
                    ->where('gl_id',$orderListArr['id'])
                    ->where('is_delect',1)
                    ->value('id');
                if($feedback){
                    $arr['install_name'] = $orderListArr['intall_person'];
                    $arr['install_phone'] = $orderListArr['intall_phone'];
                    $streamFilename = self::picurl($rea);
                    $arr['feedback_pic'] = $streamFilename;
                    $arr['install_time'] = date("Y-m-d H:i:s");
                    $arr['type_name'] = self::getPicName($request['type']);//'1';
                    $res = Feedback::where('type',$request['type'])->where('gl_id',$orderListArr['id'])->update($arr);
                    $typename = '编辑';
                }else {
                    $resu = Admin::where("id", $orderListArr['ser_id'])->first();
                    $arr['gl_id'] = $orderListArr['id'];
                    $arr['type'] = $request['type'];//'1';
                    $arr['install_name'] = $orderListArr['intall_person'];
                    $arr['install_phone'] = $orderListArr['intall_phone'];
                    $arr['admin_id'] = $orderListArr['ser_id'];
                    $arr['company_name'] = $resu['company_name'];
                    $arr['feedback_status'] = '2';
                    $streamFilename = self::picurl($rea);
                    $arr['feedback_pic'] = $streamFilename;
                    $arr['sys_num'] = "rwfk" . $orderListArr['id'];
                    $arr['install_time'] = date("Y-m-d H:i:s");
                    $arr['is_type'] = 1;
                    $arr['type_name'] = self::getPicName($request['type']);//'1';
                    $res = Feedback::insert($arr);
                    $typename = '添加';
                }
                if($res) {
                    $typename = $typename.$arr['type_name'].'图';
                    unset($arr);
                    CommonService::inserting_log($typename, $orderListArr['sys_num'], '订单(' . $orderListArr['serial_number'] . ')', '派工单web', $session, $ip);//日志
                    return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => $rea];
                }else{
                    return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '操作失败', 'Data' => $rea];
                }
            }else{
                return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '操作失败', 'Data' => $rea];
            }
        }else{
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 删除图片
     * @param string id 工单id
     * @param string type 图片类型
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/12 11:56
     * |---------------------------------------------------------------------------------
     */
    public static function deletPic ( $request , $ip ){
        $session = $request['session'];
        $orderListArr = OrderList::where("id",$request['id'])
            ->where('ser_id', $session['admin_id'])
            ->where('is_delete', 1)
            ->first();
        if($orderListArr) {
            $feedback = Feedback::where('type',$request['type'])
                ->where('gl_id',$orderListArr['id'])
                ->where('is_delect',1)
                ->value('id');
            if($feedback){
                $res = Feedback::where('type',$request['type'])
                    ->where('gl_id',$orderListArr['id'])
                    ->update(['is_delect'=>2]);
                if($res) {
                    $arr['type_name'] = self::getPicName($request['type']);//'1';
                    $typename = '删除'.$arr['type_name'].'图';
                    CommonService::inserting_log($typename, $orderListArr['sys_num'], '订单(' . $orderListArr['serial_number'] . ')', '派工单web', $session, $ip);//日志
                    return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => $res];
                }else{
                    return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '操作失败', 'Data' => $res];
                }
            }else{
                return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
            }
        }else{
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
    }

    // 申请完成
    public static function installFeedback( $request , $ip )
    {
        $session = $request['session'];
        $orderListArr = OrderList::where("id",$request['id'])
            ->where('ser_id', $session['admin_id'])
            ->where('is_delete', 1)
            ->first();
        if($orderListArr) {
            if($orderListArr['stauas']<>30){
                return ['ErrorCode' => ErrorInc::MYSQL_STEP_FAILED, 'ErrorMessage' => '当前状态不可改派！', 'Data' => []];
            }
            require_once 'aliyunoss/autoload.php';
            $accessKeyId = "LTAI4GAhRHWDjheUxeUQCE42";//去阿里云后台获取秘钥
            $accessKeySecret = "3SYbAgutMNDIHk5c7ELEn3aBig5fUV";//去阿里云后台获取秘钥
            $endpoint = "http://oss-cn-beijing.aliyuncs.com";//你的阿里云OSS地址
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $info['goods_time'] = date("Y-m-d H:i:s");//收货时间
            $info['installation']=2;//安装方式2上门
            $info['is_type']=2;
            $resu = Admin::where("id",$orderListArr['ser_id'])->first();
            if($request['file1']){
                $info['qualification']=$request['file1'];
            }
            if($request['file2']){
                $info['installation_pictures']=$request['file2'];
            }
            if($request['file3']){
                $info['qualification_pr']=$request['file3'];
            }
            $management = Management::where('trace_code',$orderListArr['serial_number'])->update($info);
            $time=date("Y-m-d H:i:s");
            self::operating_time($orderListArr['serial_number'], '任务反馈时间', $time, $orderListArr['order_num'], $session);
            $post['stauas']='34';//派工单列表
            $post['feeds_time']=$time;//反馈时间
            $post['goods_type']=4;
            DB::beginTransaction(); //开启事务
            $rea = OrderList::where('id',$request['id'])->update($post);
            $OrderCount = OrderList::where("sys_num",$orderListArr['sys_num'])->where("stauas",34)->count();
            if($OrderCount==1){
                $orArr['order_status']='34';//订单
                $res = Orders::where("sys_num",$orderListArr['sys_num'])->update($orArr);
                DB::table('recharge_order')->where('reo_order_number',$orderListArr['order_num'])->update(['reo_sg'=>2]);
            }else{
                $res = true;
            }
            $setArr['list_service_type']='34';//结算
            $setArr['fahuo_type']=1;//已发货
            $setArr['setfeeds_time']=$time;//反馈时间
            $ree = SettlementList::where('list_id',$orderListArr['serial_number'])->update($setArr);
            $resa = self::updateLineSrate($request['coordinate']??'', 6, $orderListArr['serial_number'], $orderListArr['sys_num'], $orderListArr['order_num']);
            if ($rea && $res && $ree && $resa) {
                DB::commit();
                $content = "订单(".$orderListArr['serial_number'].")";
                CommonService::inserting_log('完成施工，',$orderListArr['sys_num'],$content,'派工单web',$session,$ip);//日志
                return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
            } else {
                DB::rollback();//回滚
                return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
            }
        }else{
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, '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];
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取服务商
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/18 15:55
     * |---------------------------------------------------------------------------------
    */
    public static function getService ( $request ){
        $session = $request['session'];
        if($session['user_type']==3){
            if(isset($request['search_type']) && $request['search_type']==1){
                $input['is_type'] = 5;
                $input['company_id'] = $session['company_id'];
                $input['sys_num'] = $request['sys_num'];
                if (isset($request['company_name']) && !empty($request['company_name'])) {
                    $input['company_name'] = $request['company_name'];
                }
                $input['sheng'] = $request['sheng'];
                $input['shi'] = $request['shi'];
                $input['xian'] = $request['xian'];
                $input['address'] = $request['address'];
                $data = OrderService::getService($input);
                return $data;
            }else {
                $list = Admin::whereIn('admin_groupnew', [2, 3])
                    ->where("company_id", $session['company_id']);
                if (isset($request['company_name']) && !empty($request['company_name'])) {
                    $list = $list->where("company_name", 'like', '%' . $request['company_name'] . '%');
                }
                $list = $list->orderBy('admin_groupnew', 'DESC')
                    ->select('id', 'company_name')
                    ->get();
            }
        }else{
            $list = [];
        }
        return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => $list];
    }
    /**|---------------------------------------------------------------------------------
     * @name 指派门店
     * @param string id 服务工单id
     * @param string ser_id 改派的服务门店
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/19 15:15
     * |---------------------------------------------------------------------------------
    */
    public static function sendAgain ( $request, $ip ){
        $session = $request['session'];
        $find_design_order = OrderList::where("id",$request['id'])
            ->where('is_delete', 1)
            ->first();
        // 判断是否已派单
        if (empty($find_design_order)) {
            return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '未查询到订单', 'Data' => []];
        }
        if ($find_design_order['stauas']!=30 && $find_design_order['stauas']!=20) {
            return ['ErrorCode' => ErrorInc::REQUEST_FORBIDDEN, 'ErrorMessage' => '当前状态不指派门店', 'Data' => []];
        }
        if($find_design_order['ser_id']!=$session['admin_id']){
            return ['ErrorCode' => ErrorInc::REQUEST_FORBIDDEN, 'ErrorMessage' => '非直属订单不可改派', 'Data' => []];
        }
        DB::beginTransaction();
        $resultOrder = Orders::where('order_num',$find_design_order['order_num'])->update(['ser_id'=>$request['ser_id'],'order_status'=>20,'intall_person'=>'','intall_phone'=>'']);
        if($find_design_order['stauas']==30){
            $settListArr = SettlementList::where("sys_num",$find_design_order['sys_num'])->where("sett_status",'>',1)->first();
            if(!empty($settListArr)){
                // 该单已审核
                return ['ErrorCode' => ErrorInc::MYSQL_STEP_FAILED, 'ErrorMessage' => '存在结算工单不可指派', 'Data' => []];
            }
            $resultsettList = SettlementList::where("sys_num",$find_design_order['sys_num'])->delete();
        }else{
            $resultsettList = true;
        }
        $rest = OrderList::where('order_num',$find_design_order['order_num'])->update(['ser_id'=>$request['ser_id'],'stauas'=>20,'ol_distype'=>3,'intall_person'=>'','install_id'=>'','intall_phone'=>'','get_time'=>'']);
        if($rest && $resultsettList && $resultOrder){
            DB::commit();
            CommonService::inserting_log('指派门店、',$find_design_order['sys_num'],'订单('.$find_design_order['order_num'].')','派工单web',$session,$ip);//日志
            self::operating_time($find_design_order['serial_number'],'指派门店',date("Y-m-d H:i:s"),$find_design_order['order_num'],$session);//订单操作时间
            return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
        }else{
            DB::rollback();//回滚
            return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
        }
    }
    // 获取技师
    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;
    }
    /**|---------------------------------------------------------------------------------
     * @name 根据公司判定图片名称
     * @param string $company_id 公司id
     * @param string $type 图片类型
     * @retrun /multitype:array
     * @author dou 2024/8/20 16:13
     * |---------------------------------------------------------------------------------
     */
    public static function getPicName ( $type ){
        switch ( $type ){
            case 1:
                $typeName='确认收货截图';
                break;
            case 2:
                $typeName='电池上车图';
                break;
            case 3:
                $typeName='车牌号图片';
                break;
            case 4:
                $typeName='批次号';
                break;
            case 5:
                $typeName='仪表盘/大众防伪码';
                break;
            case 6:
                $typeName='电子保单/大众验真';
                break;
            default:
                $typeName='其它';
        }
        return $typeName;
    }

    /**|---------------------------------------------------------------------------------
     * @name 获取图片类型
     * @param string $type 图片类型
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2024/12/27 16:49
     * |---------------------------------------------------------------------------------
    */
    //生成图片路径
    public static function creact_url(){
        $streamFileRand = date('YmdHis').rand(1000,9999);//产生一个随机文件名（因为你base64上来肯定没有文件名，这里你可以自己设置一个也行）
        $upPath='./FeekUploads/'.date('Ym');
        if(!is_dir($upPath)){
            mkdir ($upPath);
        }
        $streamFilename = $upPath."/".$streamFileRand .".png";
        if(file_exists($streamFilename)){
            self::creact_url();
        }else{
            return $streamFilename;
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 图片链接获取
     * @param $pic 问价地址链接
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/12/17 14:35>
     * |---------------------------------------------------------------------------------
     */
    public static function picurl($pic)
    {
        if(strstr($pic,'http') || $pic == ''){
            return $pic;
        }else{
            return "http://jdh.bluearp.com".ltrim($pic,'.');
        }
    }

    // 订单操作时间
    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{
                    if($line_state == 2 && $install_line['line_state']!=1){
                        return false;
                    }
                    $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);
    }

    /**|---------------------------------------------------------------------------------
     * @name 拒单（获取标签）
     * @param string ju_ordernum 订单单号
     * @retrun \Illuminate\Http\JsonResponse
     * @author dou 2025/10/11 16:41
     * |---------------------------------------------------------------------------------
     */
    public static function labtype ($request)
    {
        $session = $request['session'];
        $db = DB::table('setmoney_type');
        $params = ['lt_parent_id'=>25];
        $select = ['sety_id','sety_name','lt_parent_id','lt_group'];

        $list = CommonService::getMysqlData($db, $params,$select);

        //$list = DB::table('setmoney_type')->where('lt_parent_id','25')->select('sety_id','sety_name','lt_parent_id','lt_group')->get()->toArray();
        $group = $session['user_type'];//session('admin_group');
        if($list){
            $data = [];
            foreach ($list as $key=>$val){
                $arr = explode(',',$val['lt_group']);
                if(in_array($group,$arr)){
                    $data[] = $val;
                }
            }
            return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => $data];
        }else{
            return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '暂无数据', 'Data' => []];
        }
    }
}
