<?php

namespace App\Services\Api\MobileWeb;

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

class AftersaleOrderService extends Model
{
    /**
     * 售后列表
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-12
     * @param  [type]           $request    [description]
     * @param  integer          $show_count [description]
     * @return [type]                       [description]
     */
    public static function index($request, $show_count = 10)
    {
        $session = $request['session'];
        // 查询列表
        $list_data = DB::table('order_after as o');
        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
        }
        if (!empty($session['install_id']) && $session['user_type'] == 1) {
            $where['intall_id'] =$session['install_id'];//技师id
        }
        if (!empty($request['status'])) {
            if($request['status'] == 1){
                // 未处理
                $wheres['status_searchin'] = [1];
            }elseif($request['status'] == 2){
                // 处理中
                $wheres['status_searchin'] = [10,15];
            }elseif($request['status']==3){
                // 审核中
                $wheres['status'] = 30;
            }elseif($request['status']==4){
                // 已完成
                $wheres['status_searchin'] = [40];
            }
        }
        $wheres = array_merge($where, $wheres);
        $wheres = CommonService::jointWhere($wheres);
        $list_data = $list_data
            ->whereRaw($wheres)
            ->select('id', 'after_num', 'shr_id', 'shr_name', 'shr_phone', 'shr_address', 'shr_sheng', 'shr_shi','shr_xian', 'good_names', 'create_time', 'deal_sertime', 'finish_time', 'status', 'day_time');

        $list_data = $list_data->orderby('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);
            $getStauasName = self::getStauasName();
            foreach ($list_items as $key => $value) {
                $list_items[$key]['stauasName'] = $getStauasName[$value['status']]['name'];

                // // 获取第一个字符
                // if(in_array($value['stauas'],[10,20])){
                //     $list_items[$key]['shr_phone'] = substr_replace($list_items[$key]['shr_phone'], '****', 3, 4);
                // }

                $mb_first = mb_substr($value['shr_name'], 0, 1, 'utf-8');
                $list_items[$key]['first_name'] = $mb_first;
                $list_items[$key]['day_time'] = empty($value['day_time']) ? '--':$value['day_time'];
                $list_items[$key]['button'] = [];
                if($session['user_type']==3 && $value['ser_id']){

                }else {
                    if (in_array($value['status'], [1])) {
                        $list_items[$key]['button'] = [['action' => 'handle_ive', 'name' => '立即处理']];
                    }
                    if (in_array($value['status'], [10])) {
                        $list_items[$key]['button'] = [['action' => 'quality', 'name' => '申请完成'], ['action' => 'dailyFeedback', 'name' => '日常反馈']];
                    }
                }
            }
            $page['count'] = $list_data->total(); //总数据个数
            $page['page'] = $list_data->currentPage(); //当前页面页码
            $page['page_size'] = $show_count; //一页显示多少个
            $page['allPage'] = $list_data->lastPage(); //表示最后一页的页码
            $data['list'] = $list_items;
            $data['page'] = $page;
        }

        // 查询接单的状态统计数据,改为用上面查询出来的组装就行，因为数据格式完全变了，从订单表查了,所以根据上面的状态就可以获取数量了
        $where['status_searchin'] = [1,10,15,30,40];
        $where = CommonService::jointWhere($where);
        $data_num = DB::table('order_after')->whereRaw($where)->groupBy('status')->select('status',DB::raw('count(*) as total'))->get();
        $wcl_num = 0;
        $clz_num = 0;
        $shz_num = 0;
        $ywc_num = 0;
        if($data_num){
            $data_num = CommonService::dataToArray($data_num);
            foreach($data_num as $k => $v){
                switch ( $v['status'] ){
                    case 1:
                        $wcl_num = $wcl_num + $v['total'];
                        break;
                    case 10:
                        $clz_num = $clz_num + $v['total'];
                        break;
                    case 15:
                        $clz_num = $clz_num + $v['total'];
                        break;
                    case 30:
                        $shz_num = $shz_num + $v['total'];
                        break;
                    case 40:
                        $ywc_num = $ywc_num + $v['total'];
                        break;
                    default:
                        ;
                        break;
                }

            }
        }
        $status_count=[];
        $status_count[] = ['count'=>$wcl_num,'status'=>1];
        $status_count[] = ['count'=>$clz_num,'status'=>2];
        $status_count[] = ['count'=>$shz_num,'status'=>3];
        $status_count[] = ['count'=>$ywc_num,'status'=>4];
        $data['status_count'] = $status_count;
        if ($data['list']) {
            return ['ErrorCode' => 1, 'ErrorMessage' => '成功', 'Data' => $data];
        } else {
            return ['ErrorCode' => 1, 'ErrorMessage' => '暂无数据', 'Data' => $data];
        }
    }

    /**|---------------------------------------------------------------------------------
     * @name 立即处理
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
    public static function handle_ive ($request)
    {
        DB::beginTransaction();
        $session = $request['session'];
        $find_data = DB::table('order_after')
            ->where('id', $request['id'])
            ->first();

        $order_num = $find_data['order_num'];
        $status = $find_data['status'];
        if ($status !=1){
            return ['ErrorCode' => 2, 'ErrorMessage' => '售后状态不正确', 'Data' => ''];
        }
        $feek_time = date('Y-m-d',strtotime("+1day")).' 17:30:00'; //明天下午5:30时间
        $info['feek_time'] = $feek_time;
        $info['status'] = 10;         //改为处理中
        $info['day_time'] = $request['appoint_time'];
        $res = OrderAfter::where('id',$request['id'])->update($info);
        if ($res){
            $rest = CommonService::accMe($find_data['sys_num'],'售后列表',$request['quality_content'],$find_data['sys_num'],2,2,$session['install_name'],$session['install_id']);
            if ($rest){
                CommonService::inserting_log('售后列表',$find_data['sys_num'],'售后处理','售后列表',$session,$request['ip']);//日志
                //修改领取人
                $get_id = OrderAfter::where('id',$request['id'])->value('get_id');
                if(!$get_id){
                    OrderAfter::where('id',$request['id'])->update(['get_id'=>$session['id'],'get_time'=>date("Y-m-d H:i:s")]);
                }
                DB::commit();
                return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
            }else{
                DB::rollback();//回滚
                return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
            }
        }else{
            DB::rollback();//回滚
            return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
        }
    }

    /**
     * 日常反馈
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-12
     * @param  [type]           $data [description]
     * @return [type]                 [description]
     */
    public static function dailyFeedback($request) {
        $session = $request['session'];
        $find_data = DB::table('order_after')
            ->where('id', $request['id'])
            ->first();
        DB::beginTransaction();
        $rest = CommonService::accMe($find_data['sys_num'],'售后列表',$request['remark'],$find_data['sys_num'],2,2,$session['install_name'],$session['install_id']);
        if ($rest){
            CommonService::inserting_log('售后列表',$find_data['sys_num'],'日常反馈','售后列表',$session,$request['ip']);//日志
            DB::commit();
            return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
        }else{
            DB::rollback();//回滚
            return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
        }
    }

    /**
     * 详情
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-12
     * @param  [type]           $data [description]
     * @return [type]                 [description]
     */
    public static function info($data) {
        $session = $data['session'];
        $find_data = DB::table('order_after')
            ->where('id', $data['id'])
            ->select('id', 'after_num', 'shr_id', 'shr_name', 'shr_phone', 'shr_address', 'shr_sheng', 'shr_shi','shr_xian', 'good_names', 'create_time', 'deal_sertime', 'finish_time', 'status', 'sys_num', 'day_time', 'serial_number')
            ->first();
        $remark = CommonService::orderRemarks($find_data['sys_num'],'',2,$session['install_id']);
        $image = DB::table('feedsales')
            ->where('gl_id', $find_data['id'])
            ->where('sys_num', $find_data['sys_num'])
            ->where('is_delect', 1)
            ->where('type', 4)->select('id','feedback_pic as url')
            ->get();
        if(in_array($find_data['status'],[1])){
            $find_data['button'] = [['action'=>'handle_ive','name'=>'立即处理']];
        }
        if(in_array($find_data['status'],[10])){
            $find_data['button'] = [['action'=>'quality','name'=>'申请完成'],['action'=>'dailyFeedback','name'=>'日常反馈']];
        }
        $return_data['data'] = $find_data;
        $return_data['remark'] = $remark ? $remark : [];
        $return_data['image'] = $image;
        return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => $return_data];
    }
    /**|---------------------------------------------------------------------------------
     * @name 上传图片
     * @param string id 售后单id
     * @param string file 售后图片base64
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/14 9:59
     * |---------------------------------------------------------------------------------
    */
    public static function upload ( $request ){
        $session = $request['session'];
        $find_data = OrderAfter::where('id',$request['id'])->first();
        if($find_data) {
            $request['path'] = './afterSale/' . date('Ym');
            $return_data = DealPicService::addPic($request['file'], $request['path']);
            if($return_data){
                $company_name = Admin::where('id',$session['admin_id'])->value("company_name");
                if($session['user_type']==1){
                    $install_phone = InstallPerson::where('admin_id',$session['install_id'])->value('install_phone');//安装人员
                }else{
                    $install_phone = AdminInfor::where("admin_id",$session['admin_id'])->value('phone');
                }
                $poss['type'] = 4;
                $poss['gl_id'] = $request['id'];
                $poss['install_name'] = $session['install_name'];
                $poss['install_phone'] = $install_phone;
                $poss['install_time'] = date("Y-m-d H:i:s");
                $poss['admin_id'] = $session['admin_id'];
                $poss['company_name'] = $company_name;
                $poss['feedback_status'] = 2;
                $poss['feedback_pic'] = $return_data;
                $poss['sys_num'] = $find_data['sys_num'];
                $poss['is_type'] = 1;
                $id = FeedSales::insertGetId($poss);
                if($id){
                    return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => ['id'=>$id,'url'=>$return_data]];
                }else{
                    return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '操作失败', 'Data' => $return_data];
                }
            }else{
                return ['ErrorCode' => ErrorInc::DATA_EMPTY, 'ErrorMessage' => '操作失败', 'Data' => $return_data];
            }
        }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'];
        $find_data = OrderAfter::where('id',$request['id'])->first();
        if($find_data) {
            $feedback = FeedSales::where('id',$request['file_id'])
                ->where('gl_id',$request['id'])
                ->where('is_delect',1)
                ->value('id');
            if($feedback){
                $res = FeedSales::where('id',$request['file_id'])
                    ->where('gl_id',$request['id'])
                    ->update(['is_delect'=>2]);
                if($res) {
                    $typename = '删除'.$request['id'].'图';
                    CommonService::inserting_log($typename, $find_data['sys_num'], '订单(' . $find_data['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' => []];
        }
    }
    /**
     * 申请完成
     * @authors ldj
     * @email  909490343@qq.com
     * @date   2024-09-12
     * @param  [type]           $data [description]
     * @return [type]                 [description]
     */
    public static function quality( $data ) {
        $session = $data['session'];
        $find_data = OrderAfter::where('id',$data['id'])->first();
        $serial_number = $find_data['serial_number'];
        if($find_data['status']==1 || $find_data['status']==10 || $find_data['status']==15){
        }else{
            return ['ErrorCode' => 2, 'ErrorMessage' => '售后状态错误', 'Data' => []];
        }
        Db::beginTransaction();
        $rest = CommonService::accMe($find_data['sys_num'],"售后订单","【售后】申请完成，".$data['remark'],$serial_number,'2',2,$session['install_name'],$session['install_id']);
        if($rest){

            $get['deal_time'] = date("Y-m-d H:i:s");
            $get['status'] = '30';
            $get['trigyn'] = '1';
            if($find_data['get_id'] < 1){
                $get['get_id'] = $session['id'];
                $get['get_time'] = date("Y-m-d H:i:s");
            }
            $result = OrderAfter::where('id',$data['id'])->update($get);
            if($result){
                DB::commit();
                self::operating_time($find_data['serial_number'], '申请质保完成时间', date("Y-m-d H:i:s"), $find_data['order_num'], $session);
                CommonService::inserting_log("申请质保完成，",$find_data['sys_num'],"订单(".$serial_number.")","售后列表web",$session,$data['ip']);//日志
                return ['ErrorCode' => 1, 'ErrorMessage' => '操作成功', 'Data' => []];
            }else{
                DB::rollBack();
                return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '操作失败', 'Data' => []];
            }
        }else{
            DB::rollBack();
            return ['ErrorCode' => ErrorInc::MYSQL_FAILED, 'ErrorMessage' => '添加备注失败', 'Data' => []];
        }
    }

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

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

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

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

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

        DB::beginTransaction();

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

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

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

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

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

        DB::beginTransaction();

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                // dd(11);

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

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

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

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

        $license_plate=$request['license_plate'];

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

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

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


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

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

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

        $order_list = objectToArray($order_list);

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

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

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

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