<?php
namespace App\Http\Controllers\Orders;
use App\Http\Controllers\Admin\Apinterface;
use App\Http\Controllers\Admin\Push;
use App\Http\Controllers\Admin\PushLidao;
use App\Http\Controllers\Admin\Pushxm;
use App\Http\Controllers\BaseController;
use App\Http\Controllers\Common\CommonController;
use App\Models\Admin;
use App\Models\AdminInfor;
use App\Models\Feedback;
use App\Models\GhPrice;
use App\Models\GhXPrice;
use App\Models\GoodsBrand;
use App\Models\InstallLine;
use App\Models\InstallPerson;
use App\Models\Management;
use App\Models\Negotiated;
use App\Models\Note;
use App\Models\OrderList;
use App\Models\OrderMsg;
use App\Models\Orders;
use App\Models\OrderSendflow;
use App\Models\OrderTime;
use App\Models\PjGoods;
use App\Models\Probability;
use App\Models\Pt;
use App\Models\SerInfor;
use App\Models\SetmoneyType;
use App\Models\SettlementList;
use App\Models\SettlementMoney;
use App\Models\SubmitPlease;
use App\Models\Temporary;
use App\Models\User;
use App\Services\AdminService;
use App\Services\CategoryService;
use App\Services\CommonService;
use App\Services\InstallPersonService;
use App\Services\OrderListService;
use \App\Services\Api\MobileWeb\OrderListService as MobileOrderListService;
use App\Services\OrderService;
use App\Services\PlatformService;
use App\Services\ServiceProviderService;
use App\Services\SettlementService;
use App\Services\SettlementThreeService;
use App\Services\SysStoresService;
use App\Services\TicketListService;
use App\Services\UserService;
use App\Services\WarehouseService;
use BlueCity\Core\Inc\ErrorInc;
use BlueCity\Data\Service\ZhiPei\OrderService as zhiPeiOrder;
use DB;
use Illuminate\Http\Request;
use League\Flysystem\Exception;

/**
 * @name 派工单列表
 * Class OrderListController
 * @package App\Http\Controllers\Admin
 */
class OrderListController extends BaseController
{
    protected $export_count = 300;

    /**
     * @name 派工单列表
     * @param state 1：全部；2：未接单；3：安装中；4：延期订单；5：待完成；6：已完成
     * @param sys_num 系统单号
     * @param order_num 平台单号
     * @param serial_number 派工单号
     * @param p_id 平台名称
     * @param ser_id  服务商id
     * @param creater 经手人
     * @param username 客户姓名
     * @param userphone 客户电话
     * @param start_time 起始时间
     * @param end_time 结束时间
     * @param page 页码
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\BlueCity\Core\Controllers\mixed
     * @author du 2021年8月3日上午8:28:38
     */
    public function index (Request $request)
    {
//        $list = DB::table('syspermission')->get();
//        $list = CommonService::dataToArray($list);
//        foreach($list as $k => $v){
//           $RES =  Permissions::where("function_id",$v['C'])->update(['function_parent_id'=>$v['B'],'function_parent_name'=>$v['D']]);
//           dump($RES);
//        }
        $session = $request->get('session_token');
        $input = $request->all();
        if (!in_array($request->input('state'),[1,2,3,4,5,6,7,8,9,10])){
        	return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        $list = OrderListService::getList($input,$session);

        //导出 start
        if ($input['is_excel'] == 1) {
            $sqls = $list['sqls'];
            $excel = new CommonController();
            return $excel->getExcelOut($input['Pri_id'], $sqls, $session,200);
        }
        if($list['sqls']){
            unset($list['sqls']);
        }

        //导出 end

        if($list['list']){
        	return $this->success('获取成功', $list); exit;
        }else{
        	return $this->error('暂无数据', ErrorInc::DATA_EMPTY,$list);exit;
        }
    }

    /**
     * 获取数量
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月30日下午4:34:15
     */
    public function getDetails(Request $request){
        $time = date("Y-m-d",strtotime("+1 day"));
        //$input = $request->all();
        $session_token = $request->get('session_token');
        $where = "is_delete = 1";
        if($session_token['admin_groupnew'] == 2){
           $where .= " and ser_id='".$session_token['id']."'";
        }elseif($session_token['com_type'] == 2){
            $where .= " and agency_id='".$session_token['company_id']."'";
        }else{
            if(!in_array($session_token['admin_groupnew'],[7,8])) {
                $where .= " and p_id in (".$session_token['admin_pt_id'].")";
            }
           // $where = "p_id in (".$session_token['admin_pt_id'].") AND is_delete = 1";
        }

        $session_token = $request->get('session_token');

        if (!in_array($session_token['admin_groupnew'], [2,3,4,7,8])){//管理员可以看全部
           $where.=" and company_id='".$session_token['company_id']."'";
        }
        if (in_array($session_token['admin_groupnew'], [2,3,8])){//管理员可以看全部
            $where.=" and company_id>1";
        }
        if (in_array($session_token['admin_groupnew'], [8])){//管理员可以看全部
            $where.=" and company_id in (".implode(',', $session_token['all_companys']).")";
        }
        //统计数量
        $wjd = OrderList::whereRaw($where)->whereRaw("(stauas = 10 or stauas = 20)")->count();

        $dwc = OrderList::whereRaw($where)->where('stauas',34)->where('delay_status',1)->count();
        $dasql = "stauas=30 AND (day_time<'".$time."' OR day_time is null)";
        if ($session_token['admin_groupnew'] == 2){
            $azz = OrderList::whereRaw($where)->where(['stauas'=>30,'invalid'=>1])->count();
        }else{
            $azz  = OrderList::whereRaw($where)->whereRaw($dasql)->count();
        }
        //$yqdd = OrderList::where('stauas',30)->whereIn('p_id',explode(',',$session_token['admin_pt_id']))->where('day_time','>',$time)->count();///延期订单数量

        //$delay_img = OrderList::where('delay_status',2)->whereRaw($where)->where('stauas',34)->count();
       // $delay_num = OrderList::where('delay_status',3)->whereRaw($where)->where('stauas',34)->count();

      //  $bmmc_pids = BmmcService::searchPids($request->get('session_token')['admin_groupnew']);

        $data['show_Menu'] = [
                ['show_name'=>"全部",'status'=>'1','show_num'=>'--'],
                ['show_name'=>"未接单",'status'=>'2','show_num'=>$wjd??0],
                ['show_name'=>"安装中",'status'=>'3','show_num'=>$azz??0],
                //['show_name'=>"延期订单",'status'=>'4','show_num'=>$yqdd??0],
                ['show_name'=>"待完成",'status'=>'5','show_num'=>$dwc??0],
               // ['show_name'=>"延期审图",'status'=>'9','show_num'=>$delay_img??0],
               // ['show_name'=>"延期结算",'status'=>'10','show_num'=>$delay_num??0],
                ['show_name'=>"已完成",'status'=>'6','show_num'=>'--'],
                //['show_name'=>"未预约",'status'=>'7','show_num'=>"--"],
                //['show_name'=>"超时",'status'=>'8','show_num'=>"--"],
        ];

        return $this->success('返回成功', $data);exit;
    }


    /**
     * @name 我要接单（查找安装技师）
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年7月31日上午9:28:53
     */
     public function getInstallPerson (Request $request)
    {
       if($request->filled('ser_id')){
           $ser_id = $request->input('ser_id');
           $admin_groupnew = $request->get('session_token')['admin_groupnew'];
           $is_lidao = $request->get('session_token')['is_lidao'];
           $owner = $request->get('session_token')['owner'];
           $id = $request->get('session_token')['id'];

           $db = new InstallPerson();
           $params = ['admin_id'=>$ser_id,'delet_y'=>'1','install_is_type'=>'1','install_state'=>'1','install_pid_searchin'=>['0','']];
           $select = ['id','install_name','check_code'];
           $rest = CommonService::getMysqlData($db, $params,$select);
           if ($rest){
               foreach( $rest as $k => $v ){
                   $res[$k]['install_person'] = $v['id'];
                   $res[$k]['install_name'] = $v['install_name'].'('.$v['check_code'].')';
               }
               return $this->success('获取成功',$res);exit;
           }else{
               return $this->error('暂无技师', ErrorInc::DATA_EMPTY,[]);exit;
           }
       }else{
       		return $this->error('参数错误无ser_id', ErrorInc::DATA_EMPTY,[]);exit;

       }
    }


    /**
     * @name 接单（动作）
     * @param id  工单id
     * @param install_person 安装技师id　type=２时
     * @param type  1：物流派送 2：上门安装
     * @param ex_name 快递公司 type=1时
     * @param ex_number 快递单号type=1时
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed|\Illuminate\Http\JsonResponse
     * @author du 2021年7月31日下午2:49:41
     */
    public function getOrder (Request $request)
    {
        $input = $request->only('id','install_person','type','ex_name','ex_number','order_price');
        return $this->executeGetOrder($input,$request->get('session_token'),$request->ip());
    }

    /**|---------------------------------------------------------------------------------
     * @name 接单动作执行
     * @param array $input 执行参数
     * @param array $session 操作人权限信息
     * @param string $ip 操作设备ip
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2022/2/11 9:25
     * |---------------------------------------------------------------------------------
    */
    public function executeGetOrder ( $input , $session , $ip ){
        $checkKey = CommonService::checkKey(['id','type'],$input);

        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $input['order_price'] = $input['order_price']??0;
        $admin_acc = $session['admin_acc'];
        $id = intval($input['id']);
        $orderListArr = OrderListService::getOrderListByID($id);
        if(!$orderListArr){
            return $this->error('无此定单', ErrorInc::MYSQL_FAILED);exit;
        }
        $negotiated = Negotiated::whereRaw("order_num='".$orderListArr['order_num']."' and state=1 and (ser_id=0 or ser_id='".$orderListArr['ser_id']."')")->first();
        $res = OrderListService::checkOrder($orderListArr['ser_id'],$session['id'],$session['admin_groupnew']);
        if(!$res){
            return $this->error('接单失败,权限不符合', ErrorInc::MYSQL_FAILED,[]);exit;
        }
        $getJdOrderStatus = OrderService::getJdOrderStatus($orderListArr['order_num'], $orderListArr['p_id']);
        if($getJdOrderStatus['ErrorCode']!=1){
            return $this->error($getJdOrderStatus['ErrorMessage'],$getJdOrderStatus['ErrorCode']);
        }
        if($orderListArr['stauas']==10||$orderListArr['stauas']==20){
            $MsgArr = OrderListService::getOrderMsgById($orderListArr['order_goods_id']);
            $insArr = InstallPersonService::getInstallPersonById($input['install_person']);
            $location = OrderService::getOrderMsgLocations(['oml_sysnum'=>$orderListArr['sys_num'],'oml_parentid'=>$MsgArr['goods_id']], ['oml_goodsid']);
            if($orderListArr['manhourfee']>0) {
                $supply_price = $orderListArr['manhourfee'];
            }else{
                if ($location) {
                    $oml_goodsid = array_column($location, 'oml_goodsid');
                    $supply_prices = GhPrice::whereIn("goods_id", $oml_goodsid)->whereIn("ser_id", [$orderListArr['ser_id'], '0'])->orderBy('id', 'DESC')->select('supply_price', 'ser_id', 'goods_id')->get();
                    if ($supply_prices) {
                        $supply_prices = CommonService::jointArrayKey($supply_prices, 'ser_id', 2);
                        foreach ($supply_prices as $k => $v) {
                            $supply_prices[$k] = CommonService::jointArrayKey($v, 'goods_id');
                        }
                        $supply_price = 0;
                        foreach ($oml_goodsid as $k => $v) {
                            $price = $supply_prices[$orderListArr['ser_id']][$v]['supply_price'] ?? '';
                            if (!$price) {
                                $price = $supply_prices[0][$v]['supply_price'] ?? '';
                                if (!$price) {
                                    $price = '0';
                                }
                            }
                            $supply_price = $supply_price + $price;
                        }
                        if ($supply_price == 0) {
                            $supply_price = $input['order_price'] ?? 0;
                        }
                    } else {
                        $supply_price = $input['order_price'] ?? 0;
                    }
                } else {
                    $pt_id_arr = PlatformService::getPtIdByPtType();
                    //if($orderListArr['p_id'] == 453)
                    if(in_array($orderListArr['p_id'], $pt_id_arr)){
                        $supply_price = GhXPrice::whereRaw("(`goods_id`='" . $MsgArr['goods_id'] . "' or `gh_gname`='" . $MsgArr['goods_name'] . "') and `ser_id`='" . $orderListArr['ser_id'] . "'")->orderBy('id', 'DESC')->value('supply_price');
                    }else {
                        $supply_price = GhPrice::whereRaw("(`goods_id`='" . $MsgArr['goods_id'] . "' or `gh_gname`='" . $MsgArr['goods_name'] . "') and `ser_id`='" . $orderListArr['ser_id'] . "'")->orderBy('id', 'DESC')->value('supply_price');
                    }
                    if (!$supply_price) {
                        //if($orderListArr['p_id'] == 453)
                        if(in_array($orderListArr['p_id'], $pt_id_arr)){
                            $supply_price = GhXPrice::whereRaw("(`goods_id`='" . $MsgArr['goods_id'] . "' or `gh_gname`='" . $MsgArr['goods_name'] . "') and `ser_id`=0")->orderBy('id', 'DESC')->value('supply_price');
                        }else {
                            $supply_price = GhPrice::whereRaw("(`goods_id`='" . $MsgArr['goods_id'] . "' or `gh_gname`='" . $MsgArr['goods_name'] . "') and `ser_id`=0")->orderBy('id', 'DESC')->value('supply_price');
                        }
                        if (!$supply_price) {
                            $supply_price = $input['order_price'] ?? 0;
                        }
                    }
                }
            }
//            $supply_price = $supply_price*$MsgArr['goods_num'];
//            $supply_price = sprintf("%.2f", $supply_price);
            $sub_type = PlatformService::getBusType($orderListArr['p_id']);
            if ($sub_type == 2) {
                $get['goods_price'] = $orderListArr['goods_price'];
            }
            $arr['sys_num'] = $orderListArr['sys_num'];
            $arr['order_num'] = $orderListArr['order_num'];
            $arr['msg_id'] = $orderListArr['order_goods_id'];
            $arr['goods_brand'] = $MsgArr['goods_brand'];
            $arr['category'] = $orderListArr['category'];
            $arr['p_id'] = $orderListArr['p_id'];
            $arr['serial_number'] = $id;
            $arr['list_id'] = $orderListArr['serial_number'];
            $arr['ser_id'] = $orderListArr['ser_id'];
            $arr['type'] = $input['type'];
            if($input['type'] == '1'){
                // 快递公司
                $arr['ex_name'] = $input['ex_name'];
                // 快递单号
                $arr['ex_number'] = $input['ex_number'];
                $is_bool = "物流派送";
                $info['installation'] = 1;//安装分类(物流派送)
                // 上门安装
            }elseif($input['type'] == '2'){
                $arr['installperson'] = $input['install_person'];// 安装人id
                $arr['intall_person'] = $insArr['install_name'];// 安装人名称
                $arr['intall_phone'] = $insArr['install_phone'];// 安装人电话
                $is_bool = "上门安装";
                $info['installation'] = 2;//安装分类(上门安装)
            }

            $arr['order_price'] = (double)$supply_price;// 供货价
            $arr['all_price'] = (double)$supply_price;// 总金额
            $arr['sett_status'] = 1;// 结算状态
            $arr['list_service_type'] = 30;// 工单状态
            $arr['customer_id'] = $orderListArr['customer_id']; // 客户id
            $arr['sel_type'] = $orderListArr['orli_type'];
            $arr['pay_types'] = $orderListArr['pay_typel'];//支付方式

            // 锁定状态
            $submit_stauas = SubmitPlease::where(['submit_sys_num'=>$orderListArr['sys_num'],'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'] = $MsgArr['goods_name'];//产品名称
            $info['manufacturer'] = GoodsBrand::where('brand_name',$MsgArr['goods_brand'])->value("brand_remark");//生产厂家
            $info['transport'] = $sometime;//入仓时间
            $info['order_time'] = substr($times,0,10);//下单时间
            $info['install_one'] = $insArr['install_name'];//安装人
            $info['replacing_time'] = substr(date('Y-m-d H:i:s',strtotime('+2 year')),0,10);//建议更换时间
            /**派工单**/
            $post['stauas'] = 30;//派工单状态
            $post['install_id'] = $input['install_person'];//安装人id
            $post['intall_person'] = $insArr['install_name'];//安装人姓名
            $post['intall_phone'] = $insArr['install_phone'];//安装人电话
            $post['get_time']=date("Y-m-d H:i:s");
            /**订  单**/
            $get['order_status'] = 30;//订单状态
            $get['intall_person'] = $insArr['install_name'];//安装人姓名
            $get['intall_phone'] = $insArr['install_phone'];//安装人电话
            $shr_phone = User::where('id',$orderListArr['customer_id'])->value('shr_phone');//手机号
            $returncount = OrderList::where(['sys_num'=>$orderListArr['sys_num'],'stauas'=>'10'])->count();
            $returncount2 = OrderList::where(['sys_num'=>$orderListArr['sys_num'],'stauas'=>'20'])->count();
            $returncount = $returncount+$returncount2;
            $reward = Admin::where('id',$orderListArr['ser_id'])->value('reward');
            $orderPrice = (double)$input['order_price'];

            $arr['company_id'] = $orderListArr['company_id'];
            $arr['agency_id'] = $orderListArr['agency_id'];
            if($returncount==1){
                $ret = $this->getOrderOne($id,$supply_price,$input['install_person'],$orderListArr, $info, $post, $get, $arr,$negotiated,$reward,$admin_acc,$orderPrice,$MsgArr,$is_bool,$ip);
                if($ret==5){
                    $pt_type = Pt::where('id',$orderListArr['p_id'])->value('pt_type');

                    if($pt_type==3){
                         $arr_up['inspectionStation'] = Admin::where('id',$orderListArr['ser_id'])->value('company_name');
                         $arr_up['workOrderId'] = $orderListArr['order_num'];
                         $arr_up['carNumber'] = $insArr['plate_num']??'暂无';
                         $arr_up['workerName'] = $insArr['install_name'];
                         $arr_up['workerMobile'] = $insArr['install_phone'];
                         $arr_up['channel'] = DB::table('tm_proprietary')->where('order_id',$orderListArr['order_num'])->value('channel');//
                         $arr_up['timestamp'] = time().'000';


                       // if($_SERVER["HTTP_HOST"]=='zpsaas.bluearp.com') {
                             $arr_up['appKey'] = '2024032216801';
                            $arr_up['app_key'] = '2024032216801';
                            $arr_up['sign'] = $this->getSign($arr_up,'b1e5c75530052abf221bfc9f3d2a591bdfa4ed7f');
                          //   $url = 'https://opengw.ncarzone.com/api/workorder/uploadworker?';
                            $url = 'https://opengw.ncarzone.com/api/workorder/uploadworker';
                        /* }else{
                             $arr_up['appKey'] = '2024032216801'; //b1e5c75530052abf221bfc9f3d2a591bdfa4ed7f
                            $arr_up['app_key'] = '2024032216801';
                             $arr_up['sign'] = $this->getSign($arr_up,'b1e5c75530052abf221bfc9f3d2a591bdfa4ed7f');
                             //$url = 'https://opensandbox.ncarzone.com/api/workorder/uploadworker?';
                            $url = 'https://opensandbox.ncarzone.com/api/workorder/uploadworker';
                         }*/

                        ksort($arr_up);
                        foreach( $arr_up as $k => $v ){
                            if(strpos($v,' ')){
                                $urldata[] = $k."=".urlencode ($v);
                            }else{
                                $urldata[] = $k."=".$v;
                            }
                        }
                        $urldata = implode("&",$urldata);
                       // echo $urldata;
                      // $url = $url.'?'.$urldata;
                      // CommonService::addLog('接单', $url, $orderListArr['order_num'],'TmOrder-get5Order');
                        $ret_up = CommonService::requestPost($url, $urldata);
                        // $ret_up = $this->https_request($url,$urldata);
                      //  CommonService::addLog('接单', $url, $orderListArr['order_num'],'TmOrder-get5Order');
                      CommonService::addLog('接单', $ret_up.'---'.json_encode($arr_up).'---'.$url, $orderListArr['order_num'],'TmOrder-get5Order');

                      //   $ret_up = CommonService::requestPost($url, json_encode($arr_up));


                     }

                     return $this->success('接单成功1',[]);exit;
                 }else{
                     return $this->error('接单失败'.$ret, ErrorInc::MYSQL_FAILED);exit;
                 }
             }elseif($returncount>1){
                 $ret = $this->getOrderTwo($id,$supply_price,$input['install_person'],$orderListArr, $info, $post, $arr, $negotiated, $reward,$admin_acc,$orderPrice,$MsgArr,$is_bool);
                 if($ret==8){
                     $pt_type = Pt::where('id',$orderListArr['p_id'])->value('pt_type');
                     if($pt_type==3){

                         $arr_up['inspectionStation'] = Admin::where('id',$orderListArr['ser_id'])->value('company_name');
                         $arr_up['workOrderId'] = $orderListArr['order_num'];
                         $arr_up['carNumber'] = $insArr['plate_num']??'暂无';
                         $arr_up['workerName'] = $insArr['install_name'];
                         $arr_up['workerMobile'] = $insArr['install_phone'];
                         $arr_up['channel'] = DB::table('tm_proprietary')->where('order_id',$orderListArr['order_num'])->value('channel');//
                         $arr_up['timestamp'] = time().'000';


                        // if($_SERVER["HTTP_HOST"]=='zpsaas.bluearp.com') {
                             $arr_up['appKey'] = '2024032216801';
                             $arr_up['app_key'] = '2024032216801';
                             $arr_up['sign'] = $this->getSign($arr_up,'b1e5c75530052abf221bfc9f3d2a591bdfa4ed7f');
                           //  $url = 'https://opengw.ncarzone.com/api/workorder/uploadworker?';
                             $url = 'https://opengw.ncarzone.com/api/workorder/uploadworker';
                         /*}else{
                             $arr_up['appKey'] = '2024032216801'; //b1e5c75530052abf221bfc9f3d2a591bdfa4ed7f
                             $arr_up['app_key'] = '2024032216801';
                             $arr_up['sign'] = $this->getSign($arr_up,'b1e5c75530052abf221bfc9f3d2a591bdfa4ed7f');
                            // $url = 'https://opensandbox.ncarzone.com/api/workorder/uploadworker?';
                             $url = 'https://opensandbox.ncarzone.com/api/workorder/uploadworker';
                         }*/
                         /* $arr_up['app_key'] = '2024032216801'; //b1e5c75530052abf221bfc9f3d2a591bdfa4ed7f
                          $arr_up['appKey'] = '2024032216801'; //b1e5c75530052abf221bfc9f3d2a591bdfa4ed7f
                          $arr_up['sign'] = $this->getSign($arr_up,'b1e5c75530052abf221bfc9f3d2a591bdfa4ed7f');
                          $url = 'https://opensandbox.ncarzone.com/api/workorder/uploadworker?';*/

                         ksort($arr_up);
                         foreach( $arr_up as $k => $v ){
                             if(strpos($v,' ')){
                                 $urldata[] = $k."=".urlencode ($v);
                             }else{
                                 $urldata[] = $k."=".$v;
                             }
                         }
                         $urldata = implode("&",$urldata);
                         // echo $urldata;
                         //$url = $url.'?'.$urldata;
                         $ret_up = CommonService::requestPost($url, $urldata);
                        // $ret_up = $this->https_request($url,$urldata);
                         CommonService::addLog('接单', $ret_up.'---'.json_encode($arr_up), $orderListArr['order_num'],'TmOrder-get8Order');

                     }
                     return $this->success('接单成功',[]);exit;
                 }else{
                     return $this->error('接单失败'.$ret, ErrorInc::MYSQL_FAILED);exit;
                 }
             }else{
                 return $this->error('订单已被操作', ErrorInc::MYSQL_FAILED);exit;
             }
         }else{
             return $this->error('接单失败状态不正确', ErrorInc::MYSQL_FAILED,[]);exit;
         }
     }

     /**
      *
      * @param  $orderListArr
      * @param  $info
      * @param  $post
      * @param  $get
      * @param  $arr
      * @return \BlueCity\Core\Controllers\mixed
      * @author du 2021年7月31日下午2:04:45
      */
    public function getOrderOne($id,$supply_price,$install_person,$orderListArr,$info,$post,$get,$arr,$negotiated,$reward,$admin_acc,$orderPrice,$MsgArr,$is_bool,$ip){
    	DB::beginTransaction(); //开启事务
    	$management = Management::where('trace_code',$orderListArr['serial_number'])->update($info);
    	//DB::connection()->enableQueryLog();
    	$restOrderList = OrderList::where('id',$id)->update($post);
    	$restOrder = Orders::where('sys_num',$orderListArr['sys_num'])->update($get);
    	//print_r(DB::getQueryLog());
    	if($restOrderList && $restOrder){
    		$install_person = $install_person??0;
    		OrderListService::creatOrderSendflow($orderListArr['serial_number'], $orderListArr['ser_id'], $install_person, $orderListArr['ser_id'], $orderListArr['order_num'], $orderListArr['sys_num']);
    		$sql = "update gone_order_status set st_one=st_one-1,st_two=st_two+1 where st_serid='".$orderListArr['ser_id']."'";
    		$ordestatu = DB::update($sql);
    		$resSett = SettlementList::insertGetId($arr);
    		if(!$resSett){
    			DB::rollback();
    			return 3;exit;
    			//return $this->error('结算表存失败', ErrorInc::MYSQL_FAILED,[]);exit;
    		}
    		if(empty($negotiated)) {
    			$sub_type = PlatformService::getBusType($orderListArr['p_id']);
    			if($sub_type != 2){
    				$tim = $orderListArr['create_time'];
    				$support = DB::table('support');
                    $sup_prices = CommonService::getMysqlData($support,['sup_serid_findinset'=>$orderListArr['ser_id'],'sup_brname'=>$MsgArr['goods_brand'],'sup_startime_searchlt'=>$tim,'sup_endtime_searchgt'=>$tim],['sup_price','sup_type','sup_goodids'],[],'first');
                    $sup_price=$sup_prices['sup_price'];
                    $sup_type=$sup_prices['sup_type'];
                    $sup_goodids=explode(',',$sup_prices['sup_goodids']);
    				if ($sup_price && $reward == '1') {
    					if ($sup_price > 0) {
                            if($sup_type=='1') {
                                SettlementService::createSettMoney($resSett, $orderListArr['sys_num'], "-" . $sup_price, $admin_acc, 12);
                            }else{
                                if(in_array($MsgArr['goods_id'],$sup_goodids)){
                                    SettlementService::createSettMoney($resSett, $orderListArr['sys_num'], "-" . $sup_price, $admin_acc, 12);
                                }
                            }
    					}
    				}
    				$dbld = DB::table('leadsubsidie');
    				$paramld = ['ld_goodid' => $MsgArr['goods_id'], 'ld_type' => '1', 'ld_release' => '1'];
    				$ld_price = CommonService::getMysqlData($dbld, $paramld,[],[],'first');
    				//$ld_price = DB::table('leadsubsidie')->where(['ld_goodid' => $MsgArr['goods_id'], 'ld_type' => '1', 'ld_release' => '1'])->first();
    				if ($ld_price) {
                        SettlementService::createSettMoney($resSett, $orderListArr['sys_num'], $ld_price['ld_price'],$admin_acc,$ld_price['le_setyid']);
    				}
    			}
    			OrderListService::calculates($resSett, $orderListArr, $supply_price, $reward,$orderPrice,$admin_acc,$arr['category']);//计算奖惩金额以及评分
    		}else{
    			SettlementService::createSettMoney($resSett, $orderListArr['sys_num'], $negotiated['negotiated_price'],$admin_acc,15);
    			Negotiated::where('id',$negotiated['id'])->update(['ser_id'=>$orderListArr['ser_id']]);
    			$all_price['all_price'] = SettlementMoney::where('sem_slid',$info)->sum('sem_price');
    			SettlementList::where('id',$resSett)->update($all_price);
    		}
    		OrderListService::createInstallLine($orderListArr['serial_number'], $orderListArr['sys_num'], $orderListArr['order_num'], 0, 1);


    		$content = "订单".$is_bool."(".$orderListArr['serial_number'].")";
    		//订单操作时间
    		$this->operatingTime($orderListArr['serial_number'],'接单时间',date("Y-m-d H-i-s"),$orderListArr['order_num'],$admin_acc);
    		//添加历史时间
    		$this->addThistory($orderListArr['serial_number'],'tih_acceptime',date("Y-m-d H:i:s"),$orderListArr['ser_id'],2);
    		//日志
    		$this->insertingLog('接单，',$orderListArr['sys_num'],$content,'派工单','',$admin_acc);
    		$retu = OrderListService::editVisit($orderListArr['serial_number'],2);
    		//2019-08-09
    		Temporary::where('order_num',$orderListArr['order_num'])->update(['order_state'=>30,'acceptance_time'=>date("Y-m-d H:i:s"),'update_time'=>date("Y-m-d H:i:s"),'category'=>1,'customer_id'=>$orderListArr['order_goods_id'],'install_id'=>$install_person,'orli_type'=>$orderListArr['orli_type']]);


    		DB::commit();
    		return 5;exit;
    		//return $this->success('接单成功',[]);exit;
    	}else{
    		DB::rollback();
    		return 6;exit;
    		//return $this->error('接单失败1', ErrorInc::MYSQL_FAILED,[]);exit;
    	}

    }
    /**
     *
     * @param  $orderListArr
     * @param  $info
     * @param  $post
     * @param  $arr
     * @param  $negotiated
     * @param  $reward
     * @return \BlueCity\Core\Controllers\mixed|\Illuminate\Http\JsonResponse
     * @author du 2021年7月31日下午2:26:33
     */
    public function getOrderTwo($id,$supply_price,$install_person,$orderListArr,$info,$post,$arr,$negotiated,$reward,$admin_acc,$orderPrice,$MsgArr,$is_bool){
    	DB::beginTransaction(); //开启事务
    	Management::where('trace_code',$orderListArr['serial_number'])->update($info);
    	$restOrderList = OrderList::where('id',$id)->update($post);
    	if($restOrderList){
    		$sql = "update gone_order_status set st_one=st_one-1,st_two=st_two+1 where st_serid='".$orderListArr['ser_id']."'";
    		$orderstatu = DB::update($sql);
    		//DB::connection()->enableQueryLog();
    		$resSett = SettlementList::insertGetId($arr);
    		//print_r(DB::getQueryLog());
    		if(!$resSett){
    			DB::rollback();
    			return 7;exit;
    			//return $this->error('结算表存失败', ErrorInc::MYSQL_FAILED,[]);exit;
    		}
    		if(empty($negotiated)){
    			$sub_type = PlatformService::getBusType($orderListArr['p_id']);
    			if($sub_type != 2){
    				$tim = $orderListArr['create_time'];
                    $support = DB::table('support');
                    $sup_prices = CommonService::getMysqlData($support,['sup_serid_findinset'=>$orderListArr['ser_id'],'sup_brname'=>$MsgArr['goods_brand'],'sup_startime_searchlt'=>$tim,'sup_endtime_searchgt'=>$tim],['sup_price','sup_type','sup_goodids'],[],'first');
                    $sup_price=$sup_prices['sup_price'];
                    $sup_type=$sup_prices['sup_type'];
                    $sup_goodids=explode(',',$sup_prices['sup_goodids']);
                    if ($sup_price && $reward == '1') {
                        if ($sup_price > 0) {
                            if($sup_type=='1') {
                                SettlementService::createSettMoney($resSett, $orderListArr['sys_num'], "-" . $sup_price, $admin_acc, 12);
                            }else{
                                if(in_array($MsgArr['goods_id'],$sup_goodids)){
                                    SettlementService::createSettMoney($resSett, $orderListArr['sys_num'], "-" . $sup_price, $admin_acc, 12);
                                }
                            }
                        }
                    }
    			}
    			//计算奖惩金额以及评分
    			OrderListService::calculates($resSett,$orderListArr,(double)$supply_price,$reward,$orderPrice,$admin_acc,$arr['category']);
    		}else{
    			Negotiated::where('id',$negotiated['id'])->update(['ser_id'=>$orderListArr['ser_id']]);
    			SettlementService::createSettMoney($resSett, $orderListArr['sys_num'], $negotiated['negotiated_price'], $admin_acc,15);
    			$all_price['all_price'] = SettlementMoney::where('sem_slid',$info)->sum('sem_price');
    			SettlementList::where('id',$info)->update($all_price);
    		}
    		OrderListService::createInstallLine($orderListArr['serial_number'], $orderListArr['sys_num'], $orderListArr['order_num'], 0, 1);

    		$content = "订单".$is_bool."(".$orderListArr['serial_number'].")";
    		//计算接单率
    		$this->probability('1',$orderListArr['ser_id'],$orderListArr['stauas']);
    		//订单操作时间
    		$this->operatingTime($orderListArr['serial_number'],'接单时间',date("Y-m-d H-i-s"),$orderListArr['order_num'],$admin_acc);
    		//添加历史时间
    		$this->addThistory($orderListArr['serial_number'],'tih_acceptime',date("Y-m-d H:i:s"),$orderListArr['ser_id'],2);
    		//日志
    		$this->insertingLog('接单，',$orderListArr['sys_num'],$content,'派工单','',$admin_acc);
    		$retu = OrderListService::editVisit($orderListArr['serial_number'],2);
    		Temporary::where('order_num',$orderListArr['order_num'])->update(['order_state'=>30,'acceptance_time'=>date("Y-m-d H:i:s"),'update_time'=>date("Y-m-d H:i:s"),'category'=>1,'customer_id'=>$orderListArr['order_goods_id'],'install_id'=>$install_person,'orli_type'=>$orderListArr['orli_type']]);

    		//订单推送
    		/* if($instArr['phone_type']=='xiaomi'){
    			try{
    				$Push = new PushxmController();
    				$Push->push($instArr['token'], '新订单');
    			}catch(Exception $e){
    				$err = $e->getMessage();
    			}
    		}else{
    			try{
    				$Push= new PushController();
    				$Push->res_push($orderListArr['sys_num'],$instArr['check_code'],'新订单',2,'');
    			}catch(Exception $e){
    				$err = $e->getMessage();
    			}
    		} */
    		DB::commit();
    		return 8;exit;
    		//return $this->success('接单成功2',[]);exit;
    	}else{
    		DB::rollback();
    		return 9;exit;
    		//return $this->error('接单失败2', ErrorInc::MYSQL_FAILED,[]);exit;
    	}

    }


    /**
     * @name 拒单（获取标签）
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年7月31日下午6:10:13
     */
    public function labtype (Request $request)
    {
    	$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 = $request->get('session_token')['admin_groupnew'];//session('admin_group');
        if($list){
            $data = [];
            foreach ($list as $key=>$val){
                $arr = explode(',',$val['lt_group']);
                if(in_array($group,$arr)){
                    $data[] = $val;
                }
            }
            return $this->success('获取成功',$data);exit;
        }else{
        	return $this->error('暂无数据', ErrorInc::DATA_EMPTY,[]);exit;
        }
    }


    /**
     * @name 拒单（动作）
     * @param serial_number 派工单号
     * @param stauas        订单状态
     * @param sys_num       系统单号
     * @param note_content  备注内容
     * @param setmoney_type 标签（array）
     * @param type 多个订单拒单 1单订单 2 多订单
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月3日下午3:57:11
     */
    public function refuseOrder (Request $request)
    {
        $ip = $request->ip();
        $input = $request->only('serial_number','stauas','sys_num','note_content','setmoney_type','type','getOrderSerId','service_charge','distance');

        $checkKey = CommonService::checkKey(['serial_number','stauas','sys_num','setmoney_type',],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }

        $admin_groupnew = $request->get('session_token')['admin_groupnew'];
        $admin_acc = $request->get('session_token')['admin_acc'];
        $admin_name = $request->get('session_token')['admin_name'];
        $id = $request->get('session_token')['id'];
        $db = new OrderList;
        $params = ['sys_num'=>$input['sys_num']];
        $select = ['order_num','sys_num','serial_number','stauas','ser_id','p_id','order_goods_id','store_type','ol_dispamount','customer_id','company_id'];
        $orderBy = ['stauas'=>'DESC'];
        $orderListArrs = CommonService::getMysqlData($db, $params,$select,$orderBy);
        if(!$orderListArrs){
        	return $this->error('无此定单', ErrorInc::MYSQL_FAILED);exit;
        }
		$serial_number = array_column($orderListArrs, 'serial_number');
		$orderListArr = $orderListArrs[0];
        $res = OrderListService::checkOrder($orderListArr['ser_id'],$id,$admin_groupnew);
        if(!$res){
        	return $this->error('拒单失败，该订单状态不正确1', ErrorInc::MYSQL_FAILED);exit;
        }
        if($orderListArr['stauas']==30){
            $data_time = date("Y-m-d H:i:s",strtotime("-5 minutes"));
            $time = OrderTime::where(['is_type'=>'拒单时间','serial_number'=>$input['serial_number']])->value("create_time");
            if($admin_groupnew == '2' && $time < $data_time){
            	return $this->error('5分钟内不可重复拒单', ErrorInc::MYSQL_FAILED);exit;
            }
        }
        $returncount = count($orderListArrs);

        if($orderListArr['stauas']<>10 && $orderListArr['stauas']<>20 && $orderListArr['stauas']<>30){
            // 拒单失败！该单状态不正确！
            return $this->error('拒单失败！该单状态不正确2', ErrorInc::MYSQL_FAILED);exit;
        }else{
            if($orderListArr['stauas']!=$input['stauas']){
            	return $this->error('拒单失败！该单状态不正确3', ErrorInc::MYSQL_FAILED);exit;
            }
        }
        if($returncount > 1 && $input['type']!=2){
            // 该订单有多款商品，该工单不可拒单
            return response()->json(['Data'=>'','ErrorMessage'=>'该订单有多款商品，是否确认拒单','ErrorCode'=>7]);exit;
        }

        $company_name = AdminService::getAdminBy('id', $orderListArr['ser_id'],['company_name']);
        $note_content = "(".$company_name.")";
        if($orderListArr['stauas'] == '10' || $orderListArr['stauas'] == '20'){
	        $note_content .= '接单前拒单，';
        }else{
	        $note_content .= '接单后拒单，';
        }
        if($request->filled('note_content')){
	        $note_content .= $input['note_content'];
        }
        if($input['type']=='2'){
       		$rest = CommonService::accMe($input['sys_num'],'派工单列表',"拒单，".$note_content,$input['serial_number']."等",'1',$admin_groupnew,$admin_acc,$id);//添加备注
   		}else{
       		$rest = CommonService::accMe($input['sys_num'],'派工单列表',"拒单，".$note_content,$input['serial_number'],'1',$admin_groupnew,$admin_acc,$id);//添加备注
   		}

   		//sin_state 标签状态：1未处理；2：已处理；3：已审核
        SerInfor::where('sin_ordernum',$orderListArr['order_num'])->update(['sin_state'=>2]);

        if($rest){
            DB::beginTransaction(); //开启事务
            if($orderListArr['stauas'] == '10'|| $orderListArr['stauas'] == '20'){
                if($admin_groupnew==2){
                    $input['or_centent'] = '门店自主拒单';
                    $input['or_show'] = '1';
                }else {
                    $input['or_centent'] = '管理员驳回订单';
                    $input['or_show'] = '2';
                }
            	$ret = $this->refuseOrderOne($serial_number,$orderListArr,$input,$admin_acc,$id,$ip);
            	 if($ret==2){
                     if($orderListArr['ol_dispamount'] > 0){
                         $pt_data = PlatformService::getFieldsById($orderListArr['p_id'],['id','pt_prepamount','pt_lockamount']);
                         $pt_install=[];
                         $pt_install['pi_ptid']=$pt_data['id'];
                         $pt_install['pi_serid']=$orderListArr['ser_id'];
                         $pt_install['pi_sysbh']=$orderListArr['sys_num'];
                         $pt_install['pi_skbbh']=$orderListArr['order_num'];
                         $pt_install['pi_creatime']=date('Y-m-d H:i:s');
                         $pt_install['pi_conent']='拒单';
                         $pt_install['pi_pricetype']=1;
                         $pt_install['pi_companyid']=1;
                         $pt_install['pi_username'] =$request->get('session_token')['admin_acc'];
                         $pt_install['pi_price']=$orderListArr['ol_dispamount'];
                         $pt_install['pi_afterprice']=$pt_data['pt_prepamount']+$orderListArr['ol_dispamount'];
                         $pt_install['pi_lockprice']=$pt_data['pt_lockamount'];
                         $pt_install['pi_preprice']=$pt_data['pt_prepamount'];

                         $pt_instData[]=$pt_install;

                         $pt_install['pi_pricetype']	=2;
                         $pt_install['pi_preprice']	=$pt_data['pt_prepamount']+$orderListArr['ol_dispamount'];
                         $pt_install['pi_price']		=0-$orderListArr['ol_dispamount'];
                         $pt_install['pi_afterprice']=$pt_data['pt_lockamount']-$orderListArr['ol_dispamount'];

                         $pt_instData[]=$pt_install;

                         DB::table('pt_installog')->insert($pt_instData);
                         $pt_res = DB::update("UPDATE gone_pt set pt_prepamount=pt_prepamount+".$orderListArr['ol_dispamount'].",pt_lockamount=pt_lockamount-".$orderListArr['ol_dispamount']." where id=?",[$orderListArr['p_id']]);

                     }
            	 	if($request->filled('getOrderSerId')&&$input['getOrderSerId']!=0){
            	 	 //orders_id：数据id  ser_id：服务商id  user_id：用户id  sys_num：工单号
            	 		$info = OrderService::getOrderBy('sys_num', $input['sys_num'],['new_customer_id','id']);
            	 		$orderInfoArr['orders_id'] = $info['id'];
            	 		$orderInfoArr['user_id'] = $info['new_customer_id'];
            	 		$orderInfoArr['sys_num'] = $input['sys_num'];
            	 		$orderInfoArr['ser_id'] = $input['getOrderSerId'];
                        if(isset($input['service_charge'])) {
                            $orderInfoArr['service_charge'] = $input['service_charge'];
                        }
            	 		$retgetOrder = OrderService::sendOrder($request->get('session_token'), $orderInfoArr, $ip);
            	 		return $this->error($retgetOrder['ErrorMessage'], $retgetOrder['ErrorCode']);
            	 	}
            	 	return $this->success('拒单成功',[]);exit;
            	 }else{
                     if(is_array($ret)){
                         return $this->error($ret['ErrorMessage'],$ret['ErrorCode']);
                         exit;
                     }else {
                         return $this->error('拒单失败' . $ret,ErrorInc::MYSQL_FAILED);
                         exit;
                     }
            	 }
            }elseif ($orderListArr['stauas'] == '30'){
                if($admin_groupnew==2){
                    $input['or_centent'] = '门店自主拒单';
                    $input['or_show'] = '1';
                }else {
                    $input['or_centent'] = '管理员驳回订单';
                    $input['or_show'] = '2';
                }
            	$ret = $this->refuseOrderTwo($serial_number, $orderListArr,$input,$admin_acc,$id,$ip);
            	if($ret==6){
            		if($request->filled('getOrderSerId')&&$input['getOrderSerId']!=0){
            			$info = OrderService::getOrderBy('sys_num', $input['sys_num'],['new_customer_id','id']);
            			$orderInfoArr['orders_id'] = $info['id'];
            			$orderInfoArr['user_id'] = $info['new_customer_id'];
            			$orderInfoArr['sys_num'] = $input['sys_num'];
            			$orderInfoArr['ser_id'] = $input['getOrderSerId'];
            			if(isset($input['service_charge'])) {
                            $orderInfoArr['service_charge'] = $input['service_charge'];
                        }
            			$retgetOrder = OrderService::sendOrder($request->get('session_token'), $orderInfoArr, $ip);
            			return $this->error($retgetOrder['ErrorMessage'], $retgetOrder['ErrorCode']);
            		}
            	 	return $this->success('拒单成功',[]);exit;
            	 }else{
            	    if(is_array($ret)){
                        return $this->error($ret['ErrorMessage'],$ret['ErrorCode']);
                        exit;
                    }else {
                        return $this->error('拒单失败' . $ret,ErrorInc::TRANSFER_FAILED);
                        exit;
                    }
            	 }
            }else{
            	// 该单状态不正确
            	DB::rollback();
            	return $this->error('订单状态不正确4', ErrorInc::MYSQL_FAILED);exit;
            }

        }else{
        	return $this->error('备注失败', ErrorInc::MYSQL_FAILED);exit;
        }
    }


    /**
     * 拒单　状态值为10时
     * @param array $serial_number
     * @param array $orderListArr
     * @param array $input
     * @param int $admin_acc
     * @param int $id
     * @return number
     * @author du 2021年8月3日下午3:39:05
     */
    public function refuseOrderOne($serial_number,$orderListArr,$input,$admin_acc,$id,$ip){

    	$resultOrderList = OrderList::whereIn('serial_number',$serial_number)->delete();
    	if(!$resultOrderList){
    		return "1(原因：无此工单)";exit;//拒单失败
    	}else{
    		//$orderstatu = DB::table('order_status')->where('st_serid',$orderListArr['ser_id'])->decrement('st_one',$returncount);
    		$data['ser_id'] = 0;
    		$data['order_status'] = 10;
    		$resultOrder = Orders::where('sys_num',$input['sys_num'])->update($data);

    		/* $sqlgid = "SELECT count(*) as num,`goods_id` FROM `gone_order_msg` WHERE `sys_num`='".$input['sys_num']."' group by `goods_id`";
    		$goodid = DB::select($sqlgid);
    		//库存有关
    		if ($goodid){
    			$gsql = "";
    			$sql = "INSERT INTO `gone_invenrecor`( `iv_serid`, `iv_goodid`, `iv_num`,`iv_serial`) VALUES";
    			foreach( $goodid as $kgi => $vgi){
    				$gsql .= "UPDATE `gone_inventory` SET `inv_num`=`inv_num`+".$vgi['num']." WHERE `inv_serid`='".$orderListArr['ser_id']."' and `inv_goodid`='".$vgi['goods_id']."';";
    				$sql .= "('".$orderListArr['ser_id']."','".$vgi['goods_id']."','+".$vgi['num']."','+".$orderListArr['serial_number']."'),";
    			}

    			$sql = trim($sql,',');
    			DB::insert($sql);
    			DB::update($gsql);
    		} */
    		if($resultOrder){
    			DB::table("aftercust")->where("afc_order",$orderListArr['order_num'])->where("afc_refund",4)->update(['afc_state'=>'4']);//电话沟通单状态：1：未处理；2：需跟进；3：待审核；4：已完成
    			//计算接单率
    			$this->probability('2',$orderListArr['ser_id'],$orderListArr['stauas']);

    			OrderTime::where('serial_number','in',$serial_number)->delete();

    			Management::where('trace_code','in',$serial_number)->delete();
    			//日志
    			$this->insertingLog('拒单，',$orderListArr['sys_num'],'订单('.$orderListArr['serial_number'].')','派工单列表',$ip,$admin_acc);

    			$labstate = SetmoneyType::where('sety_id',$input['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'], $admin_acc,'',1,1,'','',$user['shr_name'],$user['shr_phone'],$dress,$orderListArr['company_id']);
    			}
    			OrderListService::creatAftersale($labstate['lt_type'], $orderListArr['order_num'], $orderListArr['serial_number'], 2, 20, 25, $input['setmoney_type'], $orderListArr['p_id'], $orderListArr['ser_id'], $input['note_content'], $admin_acc, $admin_acc,$orderListArr['company_id']);

    			//订单操作时间
    			foreach( $serial_number as $k => $v ){
    				$this->operatingTime($v,'拒单时间',date("Y-m-d H:i:s"),$orderListArr['order_num'],$admin_acc);
    				$retu = OrderListService::editVisit($v,4);
    			}

    			//2019-08-09
    			if($input['type']=='2'){
    				$temp = Temporary::where('sys_num',$orderListArr['sys_num'])->update(['rejection_time'=>date("Y-m-d H:i:s"),'update_time'=>date("Y-m-d H:i:s"),'refusal_person'=>$admin_acc,'refusal_id'=>$id,'category'=>2]);
    			}else{
    				$temp = Temporary::where('serial_number',$orderListArr['serial_number'])->update(['rejection_time'=>date("Y-m-d H:i:s"),'update_time'=>date("Y-m-d H:i:s"),'refusal_person'=>$admin_acc,'refusal_id'=>$id,'category'=>2]);
    			}
                /***************半径推送******************************/
//    				$store = SyncStores::where("ser_id",$orderListArr['ser_id'])->where('type','2')->value('id');
                $store = CommonService::getSyncStores($orderListArr['ser_id'], $orderListArr['category']);
                if(!empty($store) && $orderListArr['store_type']=='5'){
                    foreach ($serial_number as $k => $v) {
                        $pop['ord_order_number'] = $v;
                        $pop['type'] = 2;
                        $pop['orcl_consent_price'] = 0;
                        $pop['remark'] = '平台回收订单';
                        $store = SysStoresService::sysStore($pop, 'recycleOrder',$store);
                        if ($store['ErrorCode'] != 1) {
                            DB::rollBack();
                            return $store;
                        }
                    }
                }
                /***************半径推送******************************/
    			// 成功
    				DB::commit();
                    DB::table('order_rejected')->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'=>$input['or_centent'],'or_show'=>$input['or_show']]);
    				return 2;exit;
    				//return $this->success('拒单成功',[]);exit;


    			}else{
    				DB::rollBack();
    				return 3;exit;
    				//return response()->json(['Data'=>'','ErrorMessage'=>'失败1','ErrorCode'=>2]);exit;
    			}
    		}

    }

    /**
     * 拒单　状态值为30时
     * @param array $serial_number
     * @param array $orderListArr
     * @param array $input
     * @param int $admin_acc
     * @param int $id
     * @return number|\Illuminate\Http\JsonResponse
     * @author du 2021年8月3日下午3:40:22
     */
    public function refuseOrderTwo($serial_number,$orderListArr,$input,$admin_acc,$id,$ip){

    	$settListArr = SettlementList::where('list_id',$input['serial_number'])->value('sett_status');
    	if($settListArr>1){
    		return "5 (原因：财务结算中)";exit;// 该单已审核
    		//return response()->json(['Data'=>'','ErrorMessage'=>'该单已审核','ErrorCode'=>4]);exit;
    	}
    	if($orderListArr['ser_id']=='617'){
    		$url='http://order.autocamel.com/api/order.htm';//正式
    		$luot['orderid'] = $orderListArr['order_num'];
    		$luot['outorderid'] = "";
    		$luot['canceltime'] = date("Y-m-d H:i:s");

    		$luot['rmk'] = "";
    		$ParArray = array("cid" => "123.56.102.226","uid" => "LANCHENG","sid"=>"ordercancel","stat"=>"0","rmk"=>"","ver"=>"1","biz"=>$luot);
    		$ParArray = json_encode($ParArray);
    		$resp = $this->request_posts($url,$ParArray);
    		$obj = json_decode($resp,true);

    		if($obj['biz']['data']['status']=='0'){

    			$poss['le_error'] = $ParArray;
    			$poss['le_ltero'] = $resp;
    			$poss['le_number'] = $orderListArr['order_num'];
    			DB::table('luotuo_error')->insert($poss);
    		}else{
    			$poss['le_error'] = $ParArray;
    			$poss['le_ltero'] = $resp;
    			$poss['le_number'] = $orderListArr['order_num'];
    			DB::table('luotuo_error')->insert($poss);
    			if($obj['biz']['data'][0]['rmk'] == "订单正在配送中,取消待定,需回调通知或主动轮询查询确认"){

    			}else{

    			}
    			exit;
    		}
    	}
    	$resultOrderList = OrderList::where('sys_num',$input['sys_num'])->delete();
    	if($resultOrderList){
    		//$sql2 = 'INSERT INTO `gone_aftersale` (`afs_statues`,`afs_order`,`afs_serial`,`afs_sales`,`afs_granid`,`afs_paid`,`afs_type`,`afs_pid`,`afs_serid`,`afs_creactime`,`asf_time`,`afs_day`,`afs_creacter`,`afs_dealer`) VALUES ';
    		$ordestatu = DB::table('order_status')->where('st_serid',$orderListArr['ser_id'])->decrement('st_two',1);
    		$resultsettList = SettlementList::where('sys_num',$input['sys_num'])->delete();
    		if($resultsettList){
    			OrderTime::where('serial_number','in',$serial_number)->delete();
    			//金额信息接单后生成
    			DB::table('settlement_money')->where('sem_synum',$input['sys_num'])->delete();
    			//评分信息接单后生成
    			DB::table('order_score')->where('orsc_sernum','in',$serial_number)->delete();
    			$data['ser_id'] = 0;
    			$data['order_status'] = 10;
    			$data['day_time'] = 0;
    			$resultOrder = Orders::where('sys_num',$input['sys_num'])->update($data);
    			if($resultOrder){
    				DB::table("aftercust")->where("afc_order",$orderListArr['order_num'])->where("afc_refund",4)->update(['afc_state'=>'4']);
    				//计算接单率
    				$this->probability('2',$orderListArr['ser_id'],$orderListArr['stauas']);
    				Management::where('trace_code',$input['serial_number'])->delete();
    				//日志
    				$this->insertingLog('拒单，',$orderListArr['sys_num'],'订单('.$input['serial_number'].')','派工单列表',$ip,$admin_acc);
    				//订单操作时间
    				$this->operatingTime($orderListArr['serial_number'],'拒单时间',date("Y-m-d H:i:s"),$orderListArr['order_num'],$admin_acc);

    				//$sql2 = 'INSERT INTO `gone_aftersale` (`afs_statues`,`afs_order`,`afs_serial`,`afs_sales`,`afs_granid`,`afs_paid`,`afs_type`,`afs_pid`,`afs_serid`,`afs_creactime`,`asf_time`,`afs_day`,`afs_creacter`,`afs_dealer`) VALUES ';
    				$labarr = explode(',',$input['setmoney_type']);
    				$labarr = (array)$input['setmoney_type'];
    				$grand = '20';
    				$parent = '25';
    				foreach($labarr as $key=>$val){
    					//$arr = explode('-',$val);
    					$labstate = SetmoneyType::where('sety_id',$val)->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'], $admin_acc,'',1,1,'','',$user['shr_name'],$user['shr_phone'],$dress,$orderListArr['company_id']);
    					}

    					OrderListService::creatAftersale($labstate['lt_type'], $orderListArr['order_num'], $orderListArr['serial_number'], 2, 20, 25, $input['setmoney_type'], $orderListArr['p_id'],$orderListArr['ser_id'], $input['note_content'], $admin_acc, $admin_acc,$orderListArr['company_id']);
    				}

    				// 成功
    				foreach( $serial_number as $k => $v ){
    					$retu = OrderListService::editVisit($v,4);
    				}

    				if($input['type']){
    					$temp = Temporary::where('serial_number',$orderListArr['sys_num'])->update(['rejection_time'=>date("Y-m-d H:i:s"),'update_time'=>date("Y-m-d H:i:s"),'refusal_person'=>$admin_acc,'refusal_id'=>$id,'category'=>2]);
    				}else{
    					$temp = Temporary::where('serial_number',$orderListArr['serial_number'])->update(['rejection_time'=>date("Y-m-d H:i:s"),'update_time'=>date("Y-m-d H:i:s"),'refusal_person'=>$admin_acc,'refusal_id'=>$id,'category'=>2]);
    				}

                    /***************半径推送******************************/
//    				$store = SyncStores::where("ser_id",$orderListArr['ser_id'])->where('type','2')->value('id');
                    $store = CommonService::getSyncStores($orderListArr['ser_id'], $orderListArr['category']);
                    if(!empty($store) && $orderListArr['store_type']=='5'){
                        foreach ($serial_number as $k => $v) {
                            $pop['ord_order_number'] = $v;
                            $pop['type'] = 2;
                            $pop['orcl_consent_price'] = 0;
                            $pop['remark'] = '平台回收订单';
                            $store = SysStoresService::sysStore($pop, 'recycleOrder',$store);
                            if ($store['ErrorCode'] != 1) {
                                DB::rollBack();
                                return $store;
                            }
                        }
                    }
                    /***************半径推送******************************/

    				DB::commit();
                    DB::table('order_rejected')->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'=>$input['or_centent'],'or_show'=>$input['or_show']]);
    				return 6;exit;
    				//return response()->json(['Data'=>'','ErrorMessage'=>'成功','ErrorCode'=>1]);exit;
    			}else{
    				DB::rollback();
    				return 7;exit;
    				//return response()->json(['Data'=>'','ErrorMessage'=>'失败','ErrorCode'=>2]);exit;
    			}
    		}else{
    			//结算表修改失败
    			DB::rollback();
    			return 8;exit;
    			//return response()->json(['Data'=>'','ErrorMessage'=>'结算表修改失败','ErrorCode'=>5]);exit;
    		}
    	}else{
    		//orderlist失败
    		DB::rollback();
    		return 9;exit;
    		//return response()->json(['Data'=>'','ErrorMessage'=>'orderlist失败','ErrorCode'=>6]);exit;
    	}

    }


    /**
     * @name 转单（获取安装人员）
     * @param order_id  工单id号
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月3日下午4:18:49
     */
    public function transferPersonnel (Request $request)
    {
        if (!$request->filled('order_id')){
            return $this->error('参数错误无工单ID', ErrorInc::FAILED_PARAM, []);exit;
        }
        $input = $request->only('order_id');
        $order_info = OrderListService::getOrderListByID($input['order_id']);
        if(!$order_info['install_id']){
            return $this->error('当前门店未接单', ErrorInc::MYSQL_FAILED);exit;
        }
        if(!$order_info){
        	return $this->error('无此定单', ErrorInc::MYSQL_FAILED);exit;
        }
        /* $check = InstallLine::where('line_serm',$order_info['serial_number'])->value('line_status');
        if($check == '0' || $check == '当前订单不可转单'){
        	return $this->error('当前订单不可转单', ErrorInc::MYSQL_FAILED);exit;
        } */
        $ser_id = $order_info['ser_id'];
        $list = InstallPerson::whereRaw("`admin_id`='".$ser_id."' AND `id` != ".$order_info['install_id']." AND `install_is_type`=1 AND `delet_y`=1 and install_pid='0'")->orderBy('id','DESC')->get()->toArray();
        if($list){
            foreach($list as $k=>$v){
                if($v['id'] == $order_info['install_id']){
                    unset($list[$k]);
                }
            }
            foreach($list as $k=>$v){
                $json[$k]['id'] = $v['id'];//id
                $json[$k]['ser_id'] = $v['admin_id'];//安装中心id
                $json[$k]['install_name'] = $v['install_name'];//安装人姓名
            }
            return $this->success('获取成功',$json);exit;
        }else{
        	return $this->error('暂无安装人员', ErrorInc::MYSQL_FAILED);exit;
        }
    }


    /**
     * @name 转单（动作）
     * @param order_id 工单id号
     * @param install_id 安装技师id
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月3日下午4:35:55
     */
    public function transferOrder (Request $request)
    {
        $input = $request->only('order_id','install_id');
        $checkKey = CommonService::checkKey(['order_id','install_id'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }

        $list = OrderListService::getOrderListByID($input['order_id']);
        $res = OrderListService::checkOrder($list['ser_id'],$request->get('session_token')['id'],$request->get('session_token')['admin_groupnew']);
        if(!$res){
            return $this->error('当前订单不可转单1', ErrorInc::MYSQL_FAILED);exit;
        }
       /*  $checkOrder = InstallLine::where('line_serm',$list['serial_number'])->value('line_status');//查询是否可转单
        if($checkOrder == 0){
            return $this->error('当前订单不可转单2', ErrorInc::MYSQL_FAILED);exit;
        } */
        if($list['stauas']== '10' || $list['stauas'] > '40'){
        	return $this->error('当前订单不可操作', ErrorInc::MYSQL_FAILED);exit;
        }

        if($list['install_id'] == $input['install_id']){
        	return $this->error('当前订单转单不可转为自己', ErrorInc::MYSQL_FAILED);exit;
        }
        if($list['locklist_type'] == '2'){
        	return $this->error('当前订单已锁定，不可转单', ErrorInc::MYSQL_FAILED);exit;
        }else{
        	$db = new InstallPerson();
        	$params = ['id'=>$input['install_id'],'admin_id'=>$list['ser_id']];
        	$install_infor = CommonService::getMysqlData($db, $params,[],[],'first');
            if(!$install_infor){//不是当前子级技师
            	return $this->error('该技师不是当前服务商子级技师', ErrorInc::MYSQL_FAILED);exit;
            }
            DB::beginTransaction(); //开启事务
            $install_id = $input['install_id'];
            $intall_person = $install_infor['install_name'];
            $intall_phone = $install_infor['install_phone'];
            $res = OrderList::where('id',$input['order_id'])->update(['install_id'=>$install_id,'intall_person'=>$intall_person,'intall_phone'=>$intall_phone,'line_status'=>1]);
            $res1 = SettlementList::where('list_id',$list['serial_number'])->update(['installperson'=>$install_id,'intall_person'=>$intall_person,'intall_phone'=>$intall_phone]);
            if($res && $res1){
                DB::commit(); //提交
                $binds = InstallPerson::where('id',$input['install_id'])->value("bind");
                if($binds==2){
                    $Push = new PushController();
                    $Push->res_push($list['sys_num'],$install_infor['check_code'],'新订单',2,'');
                }
                $input['install_id'] = $input['install_id']??0;
                OrderListService::createSendflow( $list['serial_number'],$install_infor['admin_id'],$input['install_id'],$list['ser_id'],$list['order_num'],$list['sys_num']);
                InstallLine::where('line_serm',$list['serial_number'])->update(['line_status'=>0]);
                $content = '(派工单：'.$list['sys_num'].')已转单';
                //日志
                $admin_acc = $request->get('session_token')['admin_acc'];
                $this->insertingLog('转单，',$list['sys_num'],$content,"派工单列表",$request->ip(),$admin_acc);
                return $this->success('转单成功');exit;
            }else{
                DB::rollback();//回滚
                return $this->error('转单失败', ErrorInc::MYSQL_FAILED);exit;
            }
        }
    }


    /**
     * @name 派单信息
     * @param serial_number 派工单号
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月5日下午6:11:34
     */
    public function OrderInformation (Request $request)
    {
        $input = $request->only('serial_number');
        $checkKey = CommonService::checkKey(['serial_number'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $list = OrderSendflow::leftJoin('install_person','install_person.id','=','order_sendflow.os_installid')->leftJoin('admin','admin.id','=','order_sendflow.os_serid')->where('os_serial',$input['serial_number'])->select('os_serid','os_creactime','os_parenid','company_name','install_name')->get()->toArray();
        $pt_name = OrderList::join('pt','order_list.p_id','=','pt.id')->where('serial_number',$input['serial_number'])->value('pt_name');
        if($list){
            foreach ($list as $key => $value) {
                $list[$key]['pt_name'] = $pt_name??'暂无';
            }
            return $this->success('获取成功',$list);exit;
        }else{
        	return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
        }

    }


    /**
     * @name  驳回至安装中
     * @param serial_number 派工单号
     * @param sys_num       系统单号
     * @param order_num     平台单号
     * @param id            id号
     * @param type          勾选进行处罚 1：处罚(勾选)；2：不处罚
     * @param note_content  备注内容
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed|\Illuminate\Http\JsonResponse
     * @author du 2021年8月3日下午5:39:59
     */
    public function completeBohui (Request $request)
    {
        if ($request->filled('id')&&$request->filled('note_content')){
            $Input = OrderListService::getOrderListByID($request->input('id'));
            $db = new SettlementList();
            $select = ['id','wat_num'];
            $params = array('list_id'=>$Input['serial_number']);
            $sett = CommonService::getMysqlData($db, $params,$select,[],'first');
            $sem_slid = $sett['id'];
            try{
            	DB::beginTransaction(); //开启事务
            	$MsgArr = OrderListService::getOrderMsgById($Input['order_goods_id']);;
            	if($Input['stauas'] != 34){
            		// 该工单状态不正确！
            		return $this->error('该工单状态不正确', ErrorInc::MYSQL_FAILED);exit;
            	}
            	// 订单状态
            	$arr["order_status"] = 30;
            	// 工单列表
            	$post["stauas"] = 30;
            	$post["feeds_time"] = "";// 反馈时间
            	$post["is_bohui"] = 2;
            	if($Input['category']==3) {
                    $post["goods_type"] = 3;
                }
            	// 工单结算
            	$poss["xuanze"] = 0;
            	$poss["list_service_type"] = 30;
            	// 追溯
            	$ary['goods_time'] = "";
            	$ary['qualification'] = "";
            	$ary['installation_pictures'] = "";
            	$ary['qualification_pr'] = "";

            	Orders::where('sys_num',$Input['sys_num'])->update($arr);
            	$line['line_state'] = 4;
            	InstallLine::where('line_serm',$Input['serial_number'])->update($line);
            	SettlementMoney::whereRaw("sem_slid='".$sem_slid."' and (sem_type=7 or sem_type=18)")->delete();
            	$poss['all_price'] = SettlementMoney::where('sem_slid',$sem_slid)->sum('sem_price');
            	SettlementList::where('list_id',$Input['serial_number'])->update($poss);
            	Management::where('trace_code',$Input['serial_number'])->update($ary);

            	$Lee = OrderList::where('id',$Input['id'])->update($post);
                /***************半径推送******************************/
//            	$store = SyncStores::where("ser_id",$Input['ser_id'])->where('type','2')->value('id');
                $store = CommonService::getSyncStores($Input['ser_id'], $Input['category']);
                if(!empty($store) && $Input['store_type']=='5'){
                    $pop['ord_order_number'] = $Input['serial_number'];
                    $pop['type'] = 2;
                    $pop['remark'] = $request->input('note_content');
                    $store = SysStoresService::sysStore($pop, 'opinionOrder',$store);
                    if($store['ErrorCode']!=1){
                        DB::rollBack();
                        return $store;
                    }
                }
                /***************半径推送******************************/
            	if ($Lee){
            		$session_token = $request->get('session_token');

            		$Elise = SettlementMoney::where(['sem_slid'=>$sem_slid,'sem_type'=>11])->value("sem_id");
            		if ($request->input('type') == 1 && !$Elise){
            			$sem_price = SetmoneyType::where('sety_id','11')->value('sety_price');
            			SettlementService::createSettMoney($sem_slid, $Input['sys_num'], $sem_price, $session_token['admin_acc'], 11);
            			$all_money['all_price'] = SettlementMoney::where('sem_slid',$sem_slid)->sum('sem_price');
            			SettlementList::where('id',$sem_slid)->update($all_money);
            		}
            		$this->insertingLog("驳回，",$Input['sys_num'],"待完成订单(".$Input['serial_number'].")驳回到安装中","派工单列表",$request->ip(),$session_token['admin_acc']);//日志
            		$sys_num = $Input['sys_num'];
            		$note_type = "派工单列表";//$Input['note_type'];
            		$note_content = $request->input('note_content');
            		$send_num = $Input['serial_number'];
            		$public_state = 2;
            		if ($request->input('note_content')){
            			$rest = CommonService::accMe($sys_num,$note_type,$note_content,$send_num,$public_state,$session_token['admin_groupnew'],$session_token['admin_acc'],$session_token['id']);
            		}

            		DB::commit();//提交
            		return $this->success('操作成功');exit;
            	}else{
            		DB::rollback();//回滚
            		return $this->error('操作失败1', ErrorInc::MYSQL_FAILED);exit;
            	}
            } catch (\Exception $e){
            	DB::rollback();//回滚
            	return $this->error('操作失败2', ErrorInc::MYSQL_FAILED);exit;
            }

        }else{
           return $this->error('参数错误无ID或无备注', ErrorInc::FAILED_PARAM, []);exit;
        }
    }


    /**
     * @name 驳回至待完成
     * @param serial_number 派工单号
     * @param id 工单id
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月3日下午5:52:33
     */
    public function rejectedPending (Request $request)
    {
        if (!$request->filled('id')){
            return $this->error('参数错误无ID', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('id'));
        $restlins = OrderListService::getOrderListByID($id);
        $sett_status = SettlementList::where('list_id',$restlins['serial_number'])->value("sett_status");
        if($restlins['stauas']!=40){
        	return $this->error('状态不正确', ErrorInc::MYSQL_FAILED);exit;
        }
        $res = OrderListService::checkOrder($restlins['ser_id'],$request->get('session_token')['id'],$request->get('session_token')['admin_groupnew']);
        if(!$res){
        	return $this->error('操作失败1', ErrorInc::MYSQL_FAILED);exit;
        }
        $arrName = OrderService::getOrderStatusName();
        $is_html = $arrName[$restlins['stauas']];
        DB::beginTransaction(); //开启事务
        if($sett_status==1){
            try {
                $stauas = "34";
                $cons = OrderList::where('id',$restlins['id'])->update(['stauas'=>$stauas]);
                $ret = Orders::where('sys_num',$restlins['sys_num'])->update(['order_status'=>$stauas]);
                $res = SettlementList::where('list_id',$restlins['serial_number'])->update(['list_service_type'=>$stauas]);
                if($cons&&$ret&&$res){
                    SettlementThreeService::deletData($restlins['serial_number']);
                    $this->insertingLog("驳回，",$restlins['sys_num'],$is_html."订单(".$restlins['serial_number'].")驳回至待完成","派工单列表",$request->ip(),$request->get('session_token')['admin_acc']);//日志
                    DB::commit();
                    return $this->success('操作成功');exit;
                }else{
                    DB::rollback();
                    return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
                }
            } catch (\Exception $e){
            	return $this->error($e->getMessage(), ErrorInc::MYSQL_FAILED);exit;
            }

        }else{
        	return $this->error('该订单不可驳回', ErrorInc::MYSQL_FAILED);exit;
        }
    }


    /**
     * @name 协商价格
     * @param sys_num 系统单号
     * @param serial_number 派工单号
     * @param sem_price 协商价格
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月3日下午6:10:52
     */
   /* public function negprice (Request $request)
    {
        $Input = $request->only('sys_num','serial_number','sem_price');
        $checkKey = CommonService::checkKey(['sys_num','serial_number','sem_price'],$Input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }

        DB::beginTransaction(); //开启事务
        $setid = SettlementList::where('list_id',$Input['serial_number'])->value('id');
        if(!$setid){
        	return $this->error('暂无数据1', ErrorInc::MYSQL_FAILED);exit;
        }
        $res = SettlementMoney::where('sem_slid',$setid)->delete();
        if($res){
        	$olaf['all_price'] = $Input['sem_price'];
        	$rea = SettlementService::createSettMoney($setid, $Input['sys_num'], $Input['sem_price'],$request->get('session_token')['admin_acc'],15);
        	$theShy = SettlementList::where('list_id',$Input['serial_number'])->update($olaf);
        	if($theShy){
        		$this->insertingLog("添加协商价格，",$Input['sys_num'],$Input['sem_price'],"派工单列表",$request->ip(),$request->get('session_token')['admin_acc']);//日志
        		DB::commit();
        		return $this->success('操作成功');exit;
        	}else{
        		DB::rollback();
        		return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
        	}
        }else{
        	return $this->error('暂无数据', ErrorInc::MYSQL_FAILED);exit;
        }
    }*/

    /**
     * @name 完成申请
     * @param id id号
     * @param type 1：处罚；2：不处罚
     * @param note_content 备注内容
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed|\Illuminate\Http\JsonResponse
     * @author du 2021年8月4日上午11:46:36
     */
    public function completeApply (Request $request)
    {
        if (!$request->filled('id') || !$request->filled('type')){
            return $this->error('参数错误无ID或无type', ErrorInc::FAILED_PARAM, []);exit;
        }
        $session_token = $request->get('session_token');
        $id = intval($request->input('id'));
        $orderListArr = OrderListService::getOrderListByID($id);
        if(!$orderListArr){
            return $this->error('无此定单', ErrorInc::MYSQL_FAILED);exit;
        }

        $res = OrderListService::checkOrder($orderListArr['ser_id'],$request->get('session_token')['id'],$request->get('session_token')['admin_groupnew']);
        if(!$res){
        	return $this->error('工单错误', ErrorInc::MYSQL_FAILED);exit;
        }
        if($orderListArr['stauas']!=34){
        	return $this->error('状态不正确', ErrorInc::MYSQL_FAILED);exit;
        }

        //是否天猫服务平台
        $pt_type = Pt::where('id',$orderListArr['p_id'])->value('pt_type');
        if($pt_type==3){
            //是否核销
            $isv = DB::table('tm_code')->where('order_id',$orderListArr['order_num'])->value('is_verifi');
            if(isset($isv) && $isv==1){
                return $this->error('未核销订', ErrorInc::MYSQL_FAILED);
            }

        }
        $SettlementList = SettlementList::where('list_id',$orderListArr['serial_number'])->first();
        if(empty($SettlementList['order_price'])){
            $MsgArr = OrderListService::getOrderMsgById($orderListArr['order_goods_id']);
            $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){
                    return $this->error('缺少结算价', ErrorInc::MYSQL_FAILED);exit;
                }
            }
            SettlementMoney::where('sem_type',1)->where('sem_slid',$SettlementList['id'])->update(['sem_price'=>$supply_price]);
            $arr['all_price'] = SettlementMoney::where('sem_slid',$SettlementList['id'])->sum('sem_price');
            $arr['order_price'] = $supply_price;
            if(empty($arr['all_price'])){
                $arr['all_price'] = $supply_price;
            }
        }

        $poss['stauas'] = 40;//派工单表完成
        $post['order_status'] = 40;//订单表完成
        $arr['list_service_type'] = 40;//派工单结算列表完成
        $arr['setl_examintime'] = date("Y-m-d H:i:s");//派工单结算列表完成
        $OrderCount = OrderList::where(['sys_num'=>$orderListArr['sys_num'],'stauas'=>34])->count();
        DB::beginTransaction(); //开启事务
        if ($OrderCount==1){
            $syspt = $this->completeApplyOne($orderListArr, $post);
            if($syspt['ErrorCode']!=1){
                return $this->error($syspt['ErrorMessage'], $syspt['ErrorCode']);exit;
            }
        }
        $restOrder_list = OrderList::where('id',$orderListArr['id'])->update($poss);
        $settlementthree = SettlementThreeService::addData($orderListArr['serial_number'], 40);
        if($settlementthree){
            $arr['update_three'] = 1;
        }

        $restSettlement_list = SettlementList::where('list_id',$orderListArr['serial_number'])->update($arr);
        if($restOrder_list && $restSettlement_list){

            $sql = "update gone_order_status set st_three=st_three-1,st_four=st_four+1 where st_serid='".$orderListArr['ser_id']."'";
            DB::update($sql);

            $sem_slid = SettlementList::where('list_id',$orderListArr['serial_number'])->value('id');
            if($request->input('note_content')!=""){
                CommonService::accMe($orderListArr['sys_num'],'派工单列表',"错图备注:".$request->input('note_content'),'',2,$session_token['admin_groupnew'],$session_token['admin_acc'],$session_token['id']);
            }
            if($request->input('type')==1){
	            if($request->input('note_content')==""){
		            DB::rollback();
		            return $this->error('请添加备注信息', ErrorInc::FAILED_PARAM, []);exit;
	            }
	            $resa = SettlementMoney::where('sem_slid',$sem_slid)->where("sem_type",'11')->value('sem_id');
	            if(empty($resa)){
	                $sem_price = SetmoneyType::where('sety_id',11)->value('sety_price');
	                SettlementService::createSettMoney($sem_slid, $orderListArr['sys_num'], $sem_price, $session_token['admin_acc'], 11);
	                $all_money['all_price'] = SettlementMoney::where('sem_slid',$sem_slid)->sum('sem_price');
	                SettlementList::where('id',$sem_slid)->update($all_money);
                }
            }
            $this->operatingTime($orderListArr['serial_number'],'完成时间',date("Y-m-d H:i:s"),$orderListArr['order_num'],$session_token['admin_acc']);//订单操作时间
            $this->insertingLog("完成，",$orderListArr['sys_num'],"待完成订单(".$orderListArr['serial_number'].")".$request->input('type')."备注：".$request->input('note_content'),"派工单列表",$request->ip(),$session_token['admin_acc']);//日志
            /***************半径推送******************************/
//            $store = SyncStores::where("ser_id",$orderListArr['ser_id'])->where('type','2')->value('id');
            $store = CommonService::getSyncStores($orderListArr['ser_id'], $orderListArr['category']);
            if(!empty($store) && $orderListArr['store_type']=='5'){
                $pop['ord_order_number'] = $orderListArr['serial_number'];
                $pop['type'] = 1;
                $pop['remark'] = '';
                $store = SysStoresService::sysStore($pop, 'opinionOrder',$store);
                if($store['ErrorCode']!=1){
                    DB::rollBack();
                    return $store;
                }
            }
            /***************半径推送******************************/
            Temporary::where('serial_number',$orderListArr['serial_number'])->update(['order_state'=>40,'update_time'=>date("Y-m-d H:i:s")]);

            $shr_code = UserService::getUserBy('id', $orderListArr['customer_id'],['shr_code']);
            if(strstr($shr_code,'BH')){
                $code = DB::table('jd_code')->where('jdc_code',$shr_code)->where('jdc_state',1)->first();
                $admin_infoData = AdminInfor::where('admin_id',$orderListArr['ser_id'])->select('verstoreid','verstorename')->first();
                if($admin_infoData){
                    $admin_infoData = CommonService::dataToArray($admin_infoData);
                }
                if($admin_infoData && $admin_infoData['verstoreid'] != '' && $admin_infoData['verstorename'] != '' && !$code){
                    $jdpush_data=[];
                    $jdpush_data['verStoreId'] = $admin_infoData['verstoreid'];
                    $jdpush_data['verStoreName'] = $admin_infoData['verstorename'];
                    $jdpush_data['workerName'] = $orderListArr['intall_person'];
                    $jdpush_data['workerMobile'] = $orderListArr['intall_phone'];
                    $jdpush_data['verCode'] = $shr_code;
                    $car_number = Note::where("orders_id",$orderListArr['sys_num'])->where('note_type','客户车型')->value('note_content');
                    $jdpush_data['source'] = $car_number;
                    $url = "http://116.196.75.172/index.php/JdjxApi/installcar";
                    $res =  CommonService::requestPost($url, $jdpush_data);
                    $jd_code=[];
                    $verstoreid = 1;
                    if($res=='1'){
                        $jd_code['jdc_code'] = $shr_code;
                        $jd_code['jdc_creactime'] = date("Y-m-d H:i:s");
                        $jd_code['jdc_state'] = '1';
                    }else{
                        $verstoreid=2;
                        $jd_code['jdc_code'] = $shr_code;
                        $jd_code['jdc_creactime'] = date("Y-m-d H:i:s");
                        $jd_code['jdc_state'] = '2';
                    }
                    DB::table('jd_code')->insert($jd_code);
                }
            }


            DB::commit();



            return $this->success('操作成功');exit;
        }else{
            DB::rollback();
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
        }
    }
    /**
     *
     * @param array $orderListArr
     * @param array $post
     * @author du 2021年8月4日上午11:36:33
     */
    public function completeApplyOne($orderListArr,$post){

    	$restOrder = Orders::where('sys_num',$orderListArr['sys_num'])->update($post);
    	if ($restOrder){
            /*------------------------------------------同步第三方平台结束-----------------------------------------------*/
    		if($orderListArr['p_id']==44 && $orderListArr['send_sms']==1){
    			$user_phone = User::where('id',$orderListArr['customer_id'])->first();//获取客户电话
    			$create_time = Orders::where('sys_num',$orderListArr['sys_num'])->value("create_time");
    			//发送短信
    			//include_once('SendsmsAction.class.php');
    			//$shr_phone=$user_phone['shr_phone'];//手机号
    			//$activitysms=M("activitysms");
    			//$content = DB::table('activitysms')->where('act_type',1)->value("act_centent");

    		}

            /*------------------------------------------同步第三方平台开始-----------------------------------------------*/
            $syspt = OrderService::sysPtThree( $orderListArr , 30);
            return $syspt;
    	}else{
            return ['Data' => [], 'ErrorMessage' => '订单状态变更失败', 'ErrorCode' => 3];
        }

    }

    /**
     * @name 任务反馈
     * @param id 工单id号
     * @param type 1:物流派送 2:上门安装
     * @param fahuo_type  发货状态；1：已发货；2：未发货  （type=1）
     * @param ex_name   快递公司（type=1）
     * @param ex_number   快递单号（type=1）
     * @param kouer   生产日期（type=1）
     * @param img1    安装后照片（type=2）
     * @param img2   安装确认单（type=2）
     * @param img3   车架号照片（type=2）
     * @param img4   不断电安装照片（type=2）
     * @param img5   生产日期照片（type=2）
     * @param production   生产日期（type=2）
     * @param stats1   1:已安装；2：未安装(type=2)
     * @param xuanze   回收旧电瓶1:不清楚；2：是；3：否(type=2)
     * @param car_place    车牌号(非必传)(type=2)
     * @param bar_code   条码(非必传)(type=2)
     * @param serial_number    单号(非必传)(type=2)
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月5日下午5:58:20
     */
    public function feedbackrefer (Request $request)
    {

        $input = $request->only('id','type','ex_name','ex_number','production','oroe_check','xuanze','stats1');
        $checkKey = CommonService::checkKey(['id','type'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $id = intval($request->input('id'));

        $orderListArr = OrderListService::getOrderListByID($id);
        if(!$orderListArr){
            return $this->error('无此订单', ErrorInc::MYSQL_FAILED, []);exit;
        }

        $goodid = OrderMsg::where('id',$orderListArr['order_goods_id'])->value('goods_id');
        $db = new PjGoods();
        $params = ['pg_id'=>$goodid];
        $select = ['brand_name','pg_series','version','pg_assurance'];
        $goods = CommonService::getMysqlData($db, $params,$select,[],'first');
        $res = OrderListService::checkOrder($orderListArr['ser_id'],$request->get('session_token')['id'],$request->get('session_token')['admin_groupnew']);
        if(!$res){
        	return $this->error('操作失败1', ErrorInc::MYSQL_FAILED, []);exit;
        }
        if($orderListArr['stauas']!=30){
        	return $this->error('订单状态不正确', ErrorInc::MYSQL_FAILED, []);exit;
        }
        $admin_acc = $request->get('session_token')['admin_acc'];
        $adb = new Admin();
        $aparams = ['id'=>$orderListArr['ser_id']];
        $aselect = ['company_name','reward'];
        $company = CommonService::getMysqlData($adb, $aparams,$aselect,[],'first');
        $company_name = $company['company_name'];
        if($request->input('type') == 1){// 已发货
            if($request->input('fahuo_type')==1){
            	$feedback_status = 2;
                /**追溯**/
                $info['goods_time'] = date("Y-m-d H:i:s");//收货时间
                $info['installation'] = 2;//安装方式2上门
                $info['production'] = $request->input('kouer');//生产日期
            }else{/**反馈**/
            	$feedback_status = 1;
            }
        } elseif($request->input('type') == 2 || $request->input('type') == 3){ // 上门安装
            if($orderListArr['category'] == '3'){
                $type1 = 4;$type2 = 5;$type3 = 1;$type4 = 2;$type5 = 3;
                if ((!$request->filled('img1') && !$request->filled('img3') && !$request->filled('img4') && !$request->filled('img5')) || !$request->filled('img2')) {
                    return $this->error('反馈失败，请核实上传图片的数量', ErrorInc::FAILED_PARAM, []);
                    exit;
                }
            }else {
                $type1 = 1;$type2 = 2;$type3 = 3;$type4 = 4;$type5 = 5;
                if (!$request->filled('img1') || !$request->filled('img2') || !$request->filled('img3') || !$request->filled('img4') || !$request->filled('img5')) {
                    return $this->error('反馈失败，反馈图片必须全部上传', ErrorInc::FAILED_PARAM, []);
                    exit;
                }
            }
            if ($request->input('stats1') == 1){//已安装
            	$feedback_status = 2;//已安装
                /**追溯**/
                $info['goods_time'] = date("Y-m-d H:i:s");//收货时间
                $info['installation'] = 2;//安装方式2上门
                $info['production'] = $request->input('production');//生产日期
                $feedback_pic1 = $request->input('img1')??'';
                $feedback_pic2 = $request->input('img2')??'';
                $feedback_pic3 = $request->input('img3')??'';
                $feedback_pic4 = $request->input('img4')??'';
                $feedback_pic5 = $request->input('img5')??'';
                $feedback_pic6 = $request->input('img6')??'';
                $feedback_pic7 = $request->input('img7')??'';
            }else{/**反馈**/
            	$feedback_status = 1;//未安装
            }
        }else{
        	return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        DB::beginTransaction();
        if($request->input('type') == 2 || $request->input('type') == 3) {
            $restFeedback = OrderListService::createFeedback($type1, $id, $orderListArr['intall_person'], $orderListArr['intall_phone'], $orderListArr['ser_id'], $company_name, 3, $feedback_status, $feedback_pic1,'安装确认单');
            if (!$restFeedback) {
                DB::rollback();
                return $this->error('安装后照片反馈失败！', ErrorInc::FAILED_PARAM, []);
                exit;
            }
            $restFeedbackNew = OrderListService::createFeedback($type2, $id, $orderListArr['intall_person'], $orderListArr['intall_phone'], $orderListArr['ser_id'], $company_name, 3, $feedback_status, $feedback_pic2,'安装后图片');

            if (!$restFeedbackNew) {
                DB::rollback();
                return $this->error('安装确认单反馈失败！', ErrorInc::FAILED_PARAM, []);
                exit;
            }
            $restFeedbackNews = OrderListService::createFeedback($type3, $id, $orderListArr['intall_person'], $orderListArr['intall_phone'], $orderListArr['ser_id'], $company_name, 3, $feedback_status, $feedback_pic3,'车牌号图片');
            if (!$restFeedbackNews) {
                DB::rollback();
                return $this->error('车架号照片反馈失败！', ErrorInc::FAILED_PARAM, []);
                exit;
            }
            $restFeedbackIns = OrderListService::createFeedback($type4, $id, $orderListArr['intall_person'], $orderListArr['intall_phone'], $orderListArr['ser_id'], $company_name, 3, $feedback_status, $feedback_pic4,'不断电安装');
            if (!$restFeedbackIns) {//不断电安装照片
                DB::rollback();
                return $this->error('不断电安装照片反馈失败！', ErrorInc::FAILED_PARAM, []);
                exit;
            }
            $restFeedbackDate = OrderListService::createFeedback($type5, $id, $orderListArr['intall_person'], $orderListArr['intall_phone'], $orderListArr['ser_id'], $company_name, 3, $feedback_status, $feedback_pic5,'生产日期');
            if (!$restFeedbackDate) { //生产日期照片
                DB::rollback();
                return $this->error('生产日期照片反馈失败！', ErrorInc::FAILED_PARAM, []);
                exit;
            }
            if(!empty($feedback_pic6)){
                OrderListService::createFeedback(6, $id, $orderListArr['intall_person'], $orderListArr['intall_phone'], $orderListArr['ser_id'], $company_name, 3, $feedback_status, $feedback_pic6,'电子质保单');
            }
            if(!empty($feedback_pic7)){
                OrderListService::createFeedback(10086, $id, $orderListArr['intall_person'], $orderListArr['intall_phone'], $orderListArr['ser_id'], $company_name, 3, $feedback_status, $feedback_pic7,'其它');
            }
        }
        // 扣费
        // $post_data['adm_id'] = $orderListArr['admin_id'];
        // $post_data['company_id'] = $orderListArr['company_id'];
        // $post_data['order_number'] = $orderListArr['sys_num'];
        // $post_data['reo_price'] = -0.5;
        // $reduce_price = OrderDeductionFeeService::deductFee($post_data);
        // 扣库存
        $ware_id = DB::table('warehouse')
            ->where('company_id', $orderListArr['agency_id'])
            ->value('id');
        if (empty($ware_id)) {
            // 新增默认仓库
            $add_ware['shck_ckmc'] = '默认仓库';
            $add_ware['company_id'] = $orderListArr['agency_id'];
            $ware_id = DB::table('warehouse')->insertGetId($add_ware);
        }
        $warehouse_data['ware_id'] = $ware_id;
        $warehouse_data['sys_num'] = $orderListArr['sys_num'];
        $warehouse_data['serial_number'] = $orderListArr['serial_number'];
        $find_goods_data = DB::table('order_msg')
            ->where('id', $orderListArr['order_goods_id'])
            ->get();
        if ($find_goods_data) {
            foreach ($find_goods_data as $key => $value) {
                $goods_data[$key]['goods_num'] = 0-$value['goods_num'];
                $goods_data[$key]['goods_id'] = $value['goods_id'];
            }
            $warehouse_data['goods_data'] = $goods_data;
            $reduce_wago_res = WarehouseService::chargeWareGoodsNum($warehouse_data);
        }
        if ($request->input('fahuo_type')==1 || $request->input('stats1')==1){
        	Management::where('trace_code',$orderListArr['serial_number'])->update($info);// 追溯
        	$ret = $this->feedbackOne($orderListArr, $input, $admin_acc, $company);
        	if($ret==1){
                DB::commit();
        		return $this->success('反馈成功');exit;
        	}else{
        		DB::rollback();
        		return $this->error('反馈失败'.$ret, ErrorInc::MYSQL_FAILED);exit;
        	}
        }elseif($request->input('fahuo_type') == 2 || $request->input('stats1') == 2){
            $retu = OrderListService::editVisit($orderListArr['serial_number'],3);
            Temporary::where('serial_number',$orderListArr['serial_number'])->update(['end_time'=>date("Y-m-d H:i:s")]);

            DB::commit();
            return $this->success('反馈成功');exit;
        }else{
        	DB::rollback();
        	return $this->error('反馈失败', ErrorInc::MYSQL_FAILED);exit;
        }
    }
    /**
     *
     * @param array $orderListArr
     * @param array $input
     * @param string $admin_acc
     * @param array $company
     * @return \Illuminate\Http\JsonResponse|number
     * @author du 2021年8月5日上午11:14:11
     */
    public function feedbackOne($orderListArr,$input,$admin_acc,$company){
    	$OrderCount = OrderList::where('sys_num',$orderListArr['sys_num'])->where('stauas',30)->count();
    	if($input['type'] == 1){// 物流
    		$arr['ex_name'] = $input['ex_name'];// 快递公司
    		$arr['ex_number'] = $input['ex_number'];// 快递单号
    	}else if($input['type']==2){// 上门
    		$arr['xuanze'] = $input['xuanze'];// 回收旧电瓶
    	}
    	$time = date("Y-m-d H:i:s");
    	$arr['list_service_type'] = 34;//派工单列表申请完成
    	$arr['fahuo_type'] = 1;//已发货
    	$arr['setfeeds_time'] = $time;//待完成
    	$Darius = SettlementList::where('list_id',$orderListArr['serial_number'])->update($arr);
    	if(!$Darius){
    		DB::rollback();
    		return 5;exit;
    	}
    	if($Darius && $orderListArr['orli_type']==1 ){
    		$Diana = SettlementList::where('list_id',$orderListArr['serial_number'])->value('id');
    		$times = OrderTime::whereRaw("serial_number='".$orderListArr['serial_number']."' and (is_type='接单时间' or is_type='安装预约时间' or is_type='派单时间')")->orderBy('id','DESC')->groupBy('is_type')->pluck('create_time','is_type');
    		$payout_time = $times['接单时间']??"2015-01-01 00:00:00";
    		$yy_time = $times['安装预约时间']??"2015-01-01 00:00:00";
    		$pd_time = $times['派单时间'];
    		$zero4 = strtotime ($pd_time);
    		$zero2 = strtotime ($payout_time);
    		if($yy_time){
    			$zero3 = strtotime ($yy_time);
    			$yyaz = ($zero3-$zero2)/60; //60s*60min*24h
    			if($yyaz>17){
    				$flag = 1;
    			}else{
    				$flag = 2;
    			}
    		}else{
    			$flag = 1;
    		}
    		$sub_type = PlatformService::getBusType($orderListArr['p_id']);
    		if($sub_type != 2){
    			$money_type = SetmoneyType::whereRaw("sety_id=7 or sety_id=18")->pluck('sety_price','sety_id');
    			if($flag =='1' && $company['reward']=='1'){ //reward:奖罚设置1.开启2.关闭
    				if($payout_time>"2017-08-01"){
    					SettlementService::createSettMoney($Diana, $orderListArr['sys_num'], $money_type[18], $admin_acc, 18);
    					$all_price['all_price'] = SettlementMoney::where('sem_slid',$Diana)->sum('sem_price');
    					SettlementList::where('id',$Diana)->update($all_price);
    				}
    			}
    			$res = SettlementMoney::where(['sem_slid'=>$Diana,'sem_type'=>15])->value("sem_type");
    			if(!$res){
    				$zero1 = time();
    				$guonian = ($zero1-$zero4)/60;
    				if($company['reward']=='1'){
    					$Install_money = str_replace('，',',',$money_type[7]);
    					$Install_money = explode(',',$Install_money);
    					if($guonian<=41 ){
    						$sem_price = $Install_money[0];
    					}
    					if ($guonian>41 && $guonian<=61 ){
    						$sem_price = $Install_money[1];
    					}
    					if ($guonian>61 && $guonian<=91 ){
    						$sem_price = $Install_money[2];
    					}
    					SettlementService::createSettMoney($Diana, $orderListArr['sys_num'],$sem_price, $admin_acc, 7);
    					$all_price['all_price'] = SettlementMoney::where('sem_slid',$Diana)->sum('sem_price');
    					SettlementList::where('id',$Diana)->update($all_price);
    				}
    			}
    		}
    	}
    	$post['stauas'] = 34;//派工单列表申请完成状态
    	$post['feeds_time'] = $time;//反馈时间
        $post['service_type'] = $input['type'];//服务类型
    	$restOrder_list = OrderList::where('id',$orderListArr['id'])->update($post);
    	if($restOrder_list){
    		$sql = "update gone_order_status set st_three=st_three+1,st_two=st_two-1 where st_serid='".$orderListArr['ser_id']."'";
    		DB::update($sql);
    		if($OrderCount==1){
    			$orArr['order_status'] = 34;//订单表申请完成状态
    			$restOrder = Orders::where('sys_num',$orderListArr['sys_num'])->update($orArr);
                DB::table('recharge_order')->where('reo_order_number',$orderListArr['order_num'])->update(['reo_sg'=>2]);
    		}
    		$this->operatingTime($orderListArr['serial_number'],'任务反馈时间',date("Y-m-d H:i:s"),$orderListArr['order_num'],$admin_acc);//订单操作时间
    		$this->addThistory($orderListArr['serial_number'],'tih_feektime',date("Y-m-d H:i:s"),$orderListArr['ser_id'],3);//添加历史时间
    		$content = "订单(".$orderListArr['serial_number']."),已安装";
    		$this->insertingLog('任务反馈，',$orderListArr['sys_num'],$content,"派工单列表",'',$admin_acc);//日志
    		$retu = OrderListService::editVisit($orderListArr['serial_number'],3);
    		Temporary::where('serial_number',$orderListArr['serial_number'])->update(['end_time'=>date("Y-m-d H:i:s")]);
    		return 1;exit;
    		//return response()->json(['Data'=>'','ErrorCode'=>1,'ErrorMessage'=>'反馈成功']);exit;
    	}else{
    		return 2;exit;
    		//return response()->json(['Data'=>'','ErrorCode'=>2,'ErrorMessage'=>'反馈失败']);exit;
    	}

    }


    /**
     * @name 反馈日志
     * @param id id号
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月4日下午2:50:05
     */
    public function logIve (Request $request)
    {
        if (!$request->filled('id')){
        	return $this->error('参数错误无ID', ErrorInc::DATA_EMPTY,[]);exit;
        }
        if(isset($request['search_type']) && $request['search_type'] == 2){
            $data['feedback'][0]['feedback_pic'] = '';
            $data['feedback'][0]['type'] = 'img1';
            $data['feedback'][0]['isMust'] = true;
            $data['feedback'][0]['type_name'] = MobileOrderListService::getPicName(1);
            $data['feedback'][1]['feedback_pic'] = '';
            $data['feedback'][1]['type'] = 'img2';
            $data['feedback'][1]['isMust'] = true;
            $data['feedback'][1]['type_name'] = MobileOrderListService::getPicName(2);
            $data['feedback'][2]['feedback_pic'] = '';
            $data['feedback'][2]['type'] = 'img3';
            $data['feedback'][2]['isMust'] = true;
            $data['feedback'][2]['type_name'] = MobileOrderListService::getPicName(3);
            $data['feedback'][3]['feedback_pic'] = '';
            $data['feedback'][3]['type'] = 'img4';
            $data['feedback'][3]['isMust'] = true;
            $data['feedback'][3]['type_name'] = MobileOrderListService::getPicName(4);
            $data['feedback'][4]['feedback_pic'] = '';
            $data['feedback'][4]['type'] = 'img5';
            $data['feedback'][4]['isMust'] = true;
            $data['feedback'][4]['type_name'] = MobileOrderListService::getPicName(5);
            $data['feedback'][5]['feedback_pic'] = '';
            $data['feedback'][5]['type'] = 'img6';
            $data['feedback'][5]['isMust'] = true;
            $data['feedback'][5]['type_name'] = MobileOrderListService::getPicName(6);
            $data['feedback'][6]['feedback_pic'] = '';
            $data['feedback'][6]['type'] = 'img7';
            $data['feedback'][6]['isMust'] = false;
            $data['feedback'][6]['type_name'] = MobileOrderListService::getPicName(7);
            return $this->success('获取成功', $data);
            exit;
        }else {
            $db = new Feedback();
            $params = ['gl_id' => $request->input('id')];
            $select = ['is_type', 'type', 'feedback_status', 'feedback_pic', 'install_name', 'install_time', 'type_name'];
            $orderBy = ['id' => 'ASC'];
            $feedAcc = CommonService::getMysqlData($db, $params, $select, $orderBy);
            if ($feedAcc) {
                if ($feedAcc[0]['feedback_status'] == 1) {
                    $state = "未安装";
                } else {
                    $state = "已安装";
                }
                $theShy['install_name'] = $feedAcc[0]['install_name'];
                $theShy['install_time'] = $feedAcc[0]['install_time'];
                $theShy['state'] = $state;
                $theShy['service_name'] = "上门安装";
                $picName = OrderListService::getFeedPicName();
                $category = OrderList::where("id", $request->input('id'))->value('category');
                foreach ($feedAcc as $k => $v) {
                    if (strstr($v['feedback_pic'], 'http')) {
                        $url = $v['feedback_pic'];
                    } else {
                        if ($v['is_type'] == 1) {
                            if ($category == 3) {
                                $url = $this->picurl($v['feedback_pic'], $category);
                            } else {
                                $url = "http://weixin.sudianwang.com" . ltrim($v['feedback_pic'], '.');
                            }
                        } else {
                            $url = $this->picurl($v['feedback_pic'], $category);
                        }
                    }
                    if ($v['type_name']) {
                        $pictype = $v['type_name'];
                    } else {
                        if (isset($picName[$category])) {
                            $pictype = $picName[$category][$v['type']] ?? '';
                        } else {
                            $pictype = $picName[1][$v['type']] ?? '';
                        }
                    }
                    if ($v['feedback_pic']) {
                        $feedAcc[$k]['pictype'] = $pictype;
                        $feedAcc[$k]['url'] = $url;
                    } else {
                        $feedAcc[$k]['pictype'] = '';
                        $feedAcc[$k]['url'] = '';
                    }
                }
                $data['list'] = $feedAcc;
                $data['theShy'] = $theShy;
                return $this->success('获取成功', $data);
                exit;
            } else {
                return $this->error('暂无数据', ErrorInc::DATA_EMPTY);
                exit;
            }
        }
    }


    /**
     * @name 获取图片审核信息IDs
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月4日下午3:33:35
     */
    public function auditpic (Request $request)
    {
        if(!$request->filled('category')){
            return $this->error('请选择订单商品类型', ErrorInc::INVALID_PARAM);exit;
        }
    	$db = new OrderList();
    	$params = ['stauas'=>34,'delay_status'=>1,'is_delete'=>1,'category'=>$request->input('category'),'company_id'=>$request->get('session_token')['company_id']];
    	$orderBy = ['feeds_time'=>'DESC','orli_type'=>'DESC'];
    	$select = ['id'];
    	$ids = CommonService::getMysqlData($db, $params,$select,$orderBy);
        $flag = 1;
        if ($ids){
            foreach( $ids as $k => $v ){
                if($v['id']==$request->input('id')){
                    $flag = 2;
                }
                if($flag=='2'){
                    $id[] = $v['id'];
                }
            }
            if (isset($id)){
                $id = implode(',',$id);
                return $this->success('获取成功',$id);exit;
            }else{
                return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
            }
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
        }

    }


    /**
     * @name 获取订单详情
     * @param id id号
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月6日上午9:16:47
     */
    public function searhData (Request $request)
    {
        if (!$request->filled('id')){
            return $this->error('参数错误无ID', ErrorInc::DATA_EMPTY,[]);exit;
        }
        $id = intval($request->input('id'));
        $db = new OrderList();
        $params = ['id'=>$id,'delay_status'=>1];
        if($request->filled('category')){
            $params['category'] = $request->input('category');
        }else{
            return $this->error('请选择商品品类', ErrorInc::DATA_EMPTY,[]);exit;
        }
        $select = ['id','serial_number','p_id','ser_id','sys_num','order_num','order_goods_id','intall_person','stauas','create_time','feeds_time','customer_id','category','manhourfee'];
        $order = CommonService::getMysqlData($db, $params,$select,[],'first');
        if($order){
            $admin = AdminService::getAdminBy('id', $order['ser_id'],['company_name','mouth_pay']);
            $pay_name = ServiceProviderService::getMouthPay(true);
            $user = User::where('id',$order['customer_id'])->first();
            $order['shr_name'] = $user['shr_name'];
            $order['shr_phone'] = $user['shr_phone'];
            $order['shr_sheng'] = $user['shr_sheng'];
            $order['shr_shi'] = $user['shr_shi'];
            $order['shr_xian'] = $user['shr_xian'];
            $order['shr_adress'] = $user['shr_adress'];
            $order['good'] = OrderMsg::where('id',$order['order_goods_id'])->value("goods_name");
            $order['pt_name'] = Pt::where('id',$order['p_id'])->value("pt_name");
            $order['ser_name'] = $admin['company_name'];
            $order['pay_name'] = $pay_name[$admin['mouth_pay']]??'未设定';
            $order['cd_name'] = CategoryService::getNameByCdId($order['category']);
            $odb = new OrderTime();
            $oparams = ['serial_number' => $order['serial_number']];
            $oselect = ['create_time','is_type'];
            $orderBy = ['id'=>'ASC'];
            $operation_time = CommonService::getMysqlData($odb,$oparams,$oselect,$orderBy,'get');
            if ($operation_time){
                foreach( $operation_time as $ko => $vo){
                    switch ( $vo['is_type'] ){
                        case '下单时间':
                            if(!empty($order['place_time'])){
                                $order['place_time'] = $vo['create_time'];
                            }else{
                                if($order['place_time']<$vo['create_time']){
                                    $order['place_time'] = $vo['create_time'];
                                }
                            }
                            break;
                        case '接单时间':
                            if(!empty($order['receiving_time'])){
                                $order['receiving_time'] = $vo['create_time'];
                            }else{
                                if($order['receiving_time'] < $vo['create_time']){
                                    $order['receiving_time'] = $vo['create_time'];
                                }
                            }
                            break;
                        case '任务反馈时间':
                            if(!empty($order['feedback_time'])){
                                $order['feedback_time'] = $vo['create_time'];
                            }else{
                                if($order['feedback_time']<$vo['create_time']){
                                    $order['feedback_time'] = $vo['create_time'];
                                }
                            }
                            break;
                        case '安装预约时间':
                            if(!empty($order['subscribe_time'])){
                                $order['subscribe_time'] = $vo['create_time'];
                            }else{
                                if($order['subscribe_time']<$vo['create_time']){
                                    $order['subscribe_time'] = $vo['create_time'];
                                }
                            }
                            break;
                    }
                }
            }
            $feedAcc = Feedback::where('gl_id',$order['id'])->where('type',"!=",0)->select('is_type','type','feedback_pic','type_name');
            if($order['category'] == '3'){
                $feedAcc = $feedAcc->orderBy('install_time','ASC')->orderBy('type','ASC');
            }
            $feedAcc = $feedAcc->orderBy('id','ASC')->get();
            if ($feedAcc){
            	$picName = OrderListService::getFeedPicName();
                foreach($feedAcc as $k=>$v){
                    $caoniam[$k]['is_type'] = $v['is_type'];
                    $caoniam[$k]['type'] = $v['type'];
                    $caoniam[$k]['feedback_pic'] = $this->picurl($v['feedback_pic'],$order['category'],$order['p_id']);
                    if($v['type_name']){
                    	$pictype = $v['type_name'];
                    }else{
                        if(isset($picName[$order['category']])){
                            $pictype = $picName[$order['category']][$v['type']]??'';
                        }else{
                            $pictype = $picName[1][$order['type']]??'';
                        }
                    }
                    $caoniam[$k]['pictype'] = $pictype;
                }
                if(!$caoniam){
                    $caoniam[0]['is_type'] = 1;
                    $caoniam[0]['type'] = 1;
                    $caoniam[0]['feedback_pic'] = '';
                    $caoniam[0]['pictype'] = '未确认';
                    $data['pic'] = $caoniam;
                }else {
                    $data['pic'] = $caoniam;
                }
                $data['data'] = $order;

                //反馈录音
                $feedSound = DB::table('feedsound')->where('gl_id',$order['id'])->select('feedback_sound')->get()->toarray();
                if(!empty($feedSound)){
                   // $arr = ['1'=>'安装确认单','2'=>'安装后图片','3'=>'关联汽车图片'];
                    foreach ($feedSound as $k=>$v){
                        $sound[$k]['feedback_sound'] = $this->picurl($v['feedback_sound']);
                       // $sound[$k]['sound_type'] = $arr[$v['type']];
                    }
                    $data['sound'] = $sound;
                }
                return $this->success('获取成功',$data);exit;
            }else{
                return $this->error('暂无数据1', ErrorInc::DATA_EMPTY);exit;
            }

        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
        }
    }







    /**|写公用---------------------------------------------------------------------------------
     * @name 添加备注
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * |---------------------------------------------------------------------------------
     */
/*     public function addNote (Request $request)
    {
        if (!$request->filled('sys_num') || !$request->filled('id')){
            return response()->json(['Data'=>'','ErrorMessage'=>'参数错误','ErrorCode'=>3]);exit;
        }
        if (!$request->filled('content')){
            return response()->json(['Data'=>'','ErrorMessage'=>'备注内容不能为空','ErrorCode'=>4]);exit;
        }
        $content = $request->input('content');
        $function_name = DB::table('permissions')->where('function_id',$request->input('Pri_id'))->value("function_name");

        $icon = $this->accMe($request->input('sys_num'),$function_name,$content,'',1,$request->get('session_token')['admin_groupnew'],$request->get('session_token')['admin_acc'],$request->get('session_token')['id']);
        if ($icon){
            return response()->json(['Data'=>'','ErrorMessage'=>'添加成功','ErrorCode'=>1]);exit;
        }else{
            return response()->json(['Data'=>'','ErrorMessage'=>'添加失败','ErrorCode'=>2]);exit;
        }
    } */

    /**
     * @name  预约时间
     * @param id 工单ＩＤ
     * @param day_time　预约时间
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月4日下午2:15:57
     */
    public function appointment (Request $request)
    {
    	if (!$request->filled('id')||!$request->filled('day_time')){
    		return $this->error('参数错误无ID或无预约时间', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$session = $request->get('session_token');
    	$id = intval($request->input('id'));
    	$day_time = $request->input('day_time');
    	$oldArr = OrderListService::getOrderListByID($id);
    	if ($request->filled('remark')){
    		$remark = $request->input('remark');

    		$rest = CommonService::accMe($oldArr['sys_num'],'派工单列表',"预约时间，".$remark,$oldArr['serial_number'],'1',$session['admin_groupnew'],$session['admin_acc'],$session['id']);//添加备注

    		if (!$rest){
    			return $this->error('备注添加失败', ErrorInc::MYSQL_FAILED);exit;
    		}
    	}
    	if ($oldArr['day_time'] && ($oldArr['day_time'] == $day_time)){
    		return $this->error('您已预约当前时间，请选择其它时间', ErrorInc::MYSQL_FAILED);exit;
    	}
    	$res = OrderList::where('id',$id)->update(['day_time'=>$day_time]);
    	$res1 = Orders::where('sys_num',$oldArr['sys_num'])->update(['day_time'=>$day_time]);
    	if ($res && $res1){
    		$this->insertingLog("预约时间，",$oldArr['sys_num'],"预约时间：".$day_time,"派工单列表",$request->ip(), $request->get('session_token')['admin_acc']);
    		return $this->success('预约成功');exit;
    	}else{
    		return $this->error('预约失败,数据异常', ErrorInc::MYSQL_FAILED);exit;
    	}
    }




    /**|---------------------------------------------------------------------------------
     * @name  转单（门店）
     * @param serial_number  派工单号
     * @param stauas         订单状态
     * @param sys_num        系统单号
     * @param note_content   备注内容
     * @param setmoney_type  标签
     * @param ser_id         服务商id
     * @param user_id        用户id
     * @return \Illuminate\Http\JsonResponse

     *|---------------------------------------------------------------------------------
     */
    /* public function changeorder (Request $request)
    {
        if (!$request->filled('serial_number') || !$request->filled('stauas') || !$request->filled('sys_num') || !$request->filled('setmoney_type')){
            return response()->json(['Data'=>'','ErrorMessage'=>'参数错误','ErrorCode'=>3]);exit;
        }
        //$sys_num,$ser_id,$user_id,$orders_id,$admin_acc,$admin_groupnew,$id,$ip
        $input = $request->only('serial_number','stauas','sys_num','note_content','setmoney_type','ser_id','user_id');
        $admin_groupnew = $request->get('session_token')['admin_groupnew'];
        $admin_acc = $request->get('session_token')['admin_acc'];
        $admin_name = $request->get('session_token')['admin_name'];
        $id = $request->get('session_token')['id'];
        $ip = $request->ip();
        $orderListArr = OrderList::where('serial_number',$input['serial_number'])->select('order_num','sys_num','serial_number','stauas','ser_id','p_id','order_goods_id')->first();

        $MsgArr = OrderMsg::where('id',$orderListArr['order_goods_id'])->select('goods_brand')->first();
        $res = $this->checkOrder($orderListArr['ser_id'],$id,$admin_groupnew);
        if(!$res){
            return response()->json(['Data'=>'','ErrorMessage'=>'拒单失败，该订单状态不正确1','ErrorCode'=>14]);exit;
        }

        if($orderListArr['stauas']==30){
            $data_time=date("Y-m-d H:i:s",strtotime("-5 minutes"));
            $time=OrderTime::where(['is_type'=>'拒单时间','serial_number'=>$input['serial_number']])->value("create_time");
            if($admin_groupnew == '2' && $time < $data_time){
                return response()->json(['Data'=>'','ErrorMessage'=>'5分钟内不可重复拒单','ErrorCode'=>13]);exit;
            }
        }

        $returncount = OrderList::where(['sys_num'=>$orderListArr['sys_num']])->count();
        if($orderListArr['stauas']<>10 && $orderListArr['stauas']<>30){
            // 拒单失败！该单状态不正确！
            return response()->json(['Data'=>'','ErrorMessage'=>'拒单失败！该单状态不正确2','ErrorCode'=>14]);exit;
        }else{
            if($orderListArr['stauas']!=$input['stauas']){
                return response()->json(['Data'=>'','ErrorMessage'=>'拒单失败！该单状态不正确3','ErrorCode'=>14]);exit;
            }
        }
        if($returncount > 1){
            // 该订单有多款商品，该工单不可拒单
            return response()->json(['Data'=>'','ErrorMessage'=>'该订单有多款商品，该工单不可拒单','ErrorCode'=>7]);exit;
        }
        if($request->filled('note_content')){
            $rest=$this->acc_me($input['sys_num'],'派工单列表',"拒单，".$input['note_content'],$input['serial_number'],'1',$admin_groupnew,$admin_acc,$id);//添加备注
        }else{
            $rest = 1;
        }

        SerInfor::where('sin_ordernum',$orderListArr)->update(['sin_state'=>2]);
        if($rest == '1'){
            DB::beginTransaction(); //开启事务
            try{
                if($orderListArr['stauas'] == '10'){
                    $resultOrderList = OrderList::where('serial_number',$input['serial_number'])->delete();
                    if($resultOrderList){

                        $orderstatu = DB::table('order_status')->where('st_serid',$orderListArr['ser_id'])->decrement('st_one',1);
                        $data['ser_id']=0;
                        $data['order_status']=10;
                        $resultOrder = Orders::where('sys_num',$input['sys_num'])->update($data);

                        $sqlgid="SELECT count(*) as num,`goods_id` FROM `gone_order_msg` WHERE `sys_num`='".$input['sys_num']."' group by `goods_id`";
                        $goodid = DB::select($sqlgid);
                        if ($goodid){
                            $gsql="";
                            $sql="INSERT INTO `gone_invenrecor`( `iv_serid`, `iv_goodid`, `iv_num`) VALUES";
                            foreach( $goodid as $kgi => $vgi){
                                $gsql.="UPDATE `gone_inventory` SET `inv_num`=`inv_num`+".$vgi['num']." WHERE `inv_serid`='".$orderListArr['ser_id']."' and `inv_goodid`='".$vgi['goods_id']."';";
                                $sql.="('".$orderListArr['ser_id']."','".$vgi['goods_id']."','+".$vgi['num']."'),";

                            }
                            $sql=trim($sql,',');
                            DB::insert($sql);

                            DB::update($gsql);
                        }

                        if($resultOrder){
                            //计算接单率
                            $this->probability('2',$orderListArr['ser_id'],$orderListArr['stauas']);
                            OrderTime::where('serial_number',$input['serial_number'])->delete();
                            DB::table('management')->where('trace_code',$input['serial_number'])->delete();
                            //日志
                            $this->inserting_log('拒单，',$orderListArr['sys_num'],'订单('.$input['serial_number'].')','派工单列表',$request->ip(),$admin_acc);
                            $labstate = DB::table('setmoney_type')->where('sety_id',$input['setmoney_type'])->first();
                            if(strstr((string)$labstate['sety_price'],'-')){
                                $price = substr($labstate['sety_price'],1);
                            }else{
                                $price = $labstate['sety_price'];
                            }
                            if($price > 0){
                                $number = 'C'.date("Ymdhis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                                $ticket['til_ticnum'] = $number;
                                $ticket['til_ornum'] = $orderListArr['order_num'];
                                $ticket['til_sernum'] = $orderListArr['serial_number'];
                                $ticket['til_watnum'] = '';
                                $ticket['til_wats'] = '';
                                $ticket['til_serid'] = $orderListArr['ser_id'];
                                $ticket['til_price'] = $price;
                                $ticket['til_state'] = 1;
                                $ticket['til_cause'] = $labstate['sety_name'];
                                $ticket['til_creactor'] = $admin_acc;
                                $ticket['til_creactime'] = date('Y-m-d H:i:s');
                                TicketList::insert($ticket);
                            }
                            $anna['afs_statues'] = $labstate['lt_type'];
                            $anna['afs_order'] = $orderListArr['order_num'];
                            $anna['afs_serial'] = $orderListArr['serial_number'];
                            $anna['afs_sales'] = 2;
                            $anna['afs_granid'] = 20;
                            $anna['afs_paid'] = 25;
                            $anna['afs_type'] = $input['setmoney_type'];
                            $anna['afs_pid'] = $orderListArr['p_id'];
                            $anna['afs_serid'] = $orderListArr['ser_id'];
                            $anna['afs_creactime'] = date('Y-m-d H:i:s');
                            $anna['asf_time'] = date('Y-m-d H:i:s');
                            $anna['afs_day'] = date('Y-m-d');
                            $anna['afs_content'] = $input['note_content'];
                            $anna['afs_creacter'] = $request->get('session_token')['admin_acc'];
                            $anna['afs_dealer'] = $request->get('session_token')['admin_acc'];
                            Aftersale::insert($anna);

                            //订单操作时间
                            $this->operating_time($orderListArr['serial_number'],'拒单时间',date("Y-m-d H:i:s"),$orderListArr['order_num'],$admin_acc);

                            //2019-08-09
                            $temp = Temporary::where('serial_number',$orderListArr['serial_number'])->update(['rejection_time'=>date("Y-m-d H:i:s"),'update_time'=>date("Y-m-d H:i:s"),'refusal_person'=>$request->get('session_token')['admin_acc'],'refusal_id'=>$request->get('session_token')['id'],'category'=>2]);

                            // 成功
                            $retu = $this->editVisit($orderListArr['serial_number'],4);
                            if($orderListArr['p_id']=="105"){
                                //include_once('OeapiAction.class.php');
                                //$Oeapi= new OeapiAction();
                                //$oeres=$Oeapi->editoeorder($orderListArr['sys_num'],10);
                                //if($oeres<>1){
                                //日志
                                //$this->inserting_log('OE订单同步，',$orderListArr['sys_num'],"订单状态同步失败，错误码".$oeres,"派工单列表",$request->ip());
                                //}
                            }

                            //$sys_num,$ser_id,$user_id,$orders_id,$admin_acc,$admin_groupnew,$id,$ip
                            $workres = $this->workorder($input['sys_num'],$input['ser_id'],$input['user_id'],$admin_acc,$admin_groupnew,$id,$ip);
                            if ($workres == 1) {
                                DB::commit();
                                return response()->json(['Data'=>'','ErrorMessage'=>'成功','ErrorCode'=>1]);exit;
                            } elseif ($workres == 5) {
                                DB::rollBack();
                                return response()->json(['ErrorMessage'=>'派单失败，请添加服务费！','ErrorCode'=>$workres]);exit;
                            } elseif ($workres == 6) {
                                return response()->json(['ErrorMessage'=>'通知养车宝失败，请刷新核实！','ErrorCode'=>$workres]);exit;
                            } elseif ($workres == 7) {
                                DB::rollBack();
                                return response()->json(['ErrorMessage'=>'通知乐车邦失败,请刷新核实！','ErrorCode'=>$workres]);exit;
                            } elseif ($workres == 8) {
                                return response()->json(['ErrorMessage'=>'通知畅通车友失败！请刷新核实！','ErrorCode'=>$workres]);exit;
                            } elseif ($workres == 67) {
                                DB::rollBack();
                                return response()->json(['ErrorMessage'=>'骆驼对接无该条数据！','ErrorCode'=>$workres]);exit;
                            } elseif ($workres == 10) {
                                DB::rollBack();
                                return response()->json(['ErrorMessage'=>'派单失败，该订单已被派单，请刷新核实！','ErrorCode'=>$workres]);exit;
                            } elseif ($workres == 2) {
                                DB::rollBack();
                                return response()->json(['ErrorMessage'=>'派单失败，请刷新核实！','ErrorCode'=>$workres]);exit;
                            } else {
                                DB::rollBack();
                                return $workres;exit;
                            }


                        }else{
                            DB::rollBack();
                            return response()->json(['Data'=>'','ErrorMessage'=>'失败','ErrorCode'=>2]);exit;
                        }
                    }else{
                        //order_List失败
                        DB::rollBack();
                        return response()->json(['Data'=>'','ErrorMessage'=>'失败','ErrorCode'=>2]);exit;
                    }
                }elseif ($orderListArr['stauas'] == '30'){
                    $settListArr = SettlementList::where('list_id',$input['serial_number'])->select('sett_status')->first();
                    if($settListArr['sett_status']>1){
                        // 该单已审核
                        return response()->json(['Data'=>'','ErrorMessage'=>'该单已审核','ErrorCode'=>4]);exit;
                    }
                    if($orderListArr['ser_id']=='617'){
                        $url='http://order.autocamel.com/api/order.htm';//正式
                        $luot['orderid']=$orderListArr['order_num'];
                        $luot['outorderid']="";
                        $luot['canceltime']=date("Y-m-d H:i:s");

                        $luot['rmk']="";
                        $ParArray=array("cid" => "123.56.102.226","uid" => "LANCHENG","sid"=>"ordercancel","stat"=>"0","rmk"=>"","ver"=>"1","biz"=>$luot);
                        $ParArray = json_encode($ParArray);
                        $resp = $this->request_posts($url,$ParArray);
                        $obj=json_decode($resp,true);

                        if($obj['biz']['data']['status']=='0'){

                            $poss['le_error']=$ParArray;
                            $poss['le_ltero']=$resp;
                            $poss['le_number']=$orderListArr['order_num'];
                            DB::table('luotuo_error')->insert($poss);
                        }else{
                            $poss['le_error']=$ParArray;
                            $poss['le_ltero']=$resp;
                            $poss['le_number']=$orderListArr['order_num'];
                            DB::table('luotuo_error')->insert($poss);
                            if($obj['biz']['data'][0]['rmk']=="订单正在配送中,取消待定,需回调通知或主动轮询查询确认"){

                            }else{

                            }
                            exit;
                        }
                    }
                    $resultOrderList = OrderList::where('serial_number',$input['serial_number'])->delete();
                    if($resultOrderList){
                        //$sql2 = 'INSERT INTO `gone_aftersale` (`afs_statues`,`afs_order`,`afs_serial`,`afs_sales`,`afs_granid`,`afs_paid`,`afs_type`,`afs_pid`,`afs_serid`,`afs_creactime`,`asf_time`,`afs_day`,`afs_creacter`,`afs_dealer`) VALUES ';
                        $ordestatu = DB::table('order_status')->where('st_serid',$orderListArr['ser_id'])->decrement('st_two',1);
                        $resultsettList = SettlementList::where('list_id',$input['serial_number'])->delete();
                        if($resultsettList){
                            OrderTime::where('serial_number',$input['serial_number'])->delete();
                            //金额信息接单后生成
                            DB::table('settlement_money')->where('sem_synum',$input['sys_num'])->delete();
                            //评分信息接单后生成
                            DB::table('order_score')->where('orsc_sernum',$input['serial_number'])->delete();
                            $data['ser_id']=0;
                            $data['order_status']=10;
                            $data['day_time']=0;
                            $resultOrder = Orders::where('sys_num',$input['sys_num'])->update($data);
                            if($resultOrder){
                                //计算接单率
                                $this->probability('2',$orderListArr['ser_id'],$orderListArr['stauas']);
                                DB::table('management')->where('trace_code',$input['serial_number'])->delete();
                                //日志
                                $this->inserting_log('拒单，',$orderListArr['sys_num'],'订单('.$input['serial_number'].')','派工单列表',$request->ip(),$admin_acc);
                                //订单操作时间
                                $this->operating_time($orderListArr['serial_number'],'拒单时间',date("Y-m-d H:i:s"),$orderListArr['order_num'],$admin_acc);

                                //$sql2 = 'INSERT INTO `gone_aftersale` (`afs_statues`,`afs_order`,`afs_serial`,`afs_sales`,`afs_granid`,`afs_paid`,`afs_type`,`afs_pid`,`afs_serid`,`afs_creactime`,`asf_time`,`afs_day`,`afs_creacter`,`afs_dealer`) VALUES ';
                                $labarr = explode(',',$input['setmoney_type']);
                                $labarr = (array)$input['setmoney_type'];
                                $grand = '20';
                                $parent = '25';
                                foreach($labarr as $key=>$val){
                                    //$arr = explode('-',$val);
                                    $labstate = DB::table('setmoney_type')->where('sety_id',$val)->first();
                                    if(strstr((string)$labstate['sety_price'],'-')){
                                        $price = substr($labstate['sety_price'],1);
                                    }else{
                                        $price = $labstate['sety_price'];
                                    }
                                    if($price > 0){
                                        $number = 'C'.date("Ymdhis").str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                                        $ticket['til_ticnum'] = $number;
                                        $ticket['til_ornum'] = $orderListArr['order_num'];
                                        $ticket['til_sernum'] = $orderListArr['serial_number'];
                                        $ticket['til_watnum'] = '';
                                        $ticket['til_wats'] = '';
                                        $ticket['til_serid'] = $orderListArr['ser_id'];
                                        $ticket['til_price'] = $price;
                                        $ticket['til_state'] = 1;
                                        $ticket['til_cause'] = $labstate['sety_name'];
                                        $ticket['til_creactor'] = $admin_acc;
                                        $ticket['til_creactime'] = date('Y-m-d H:i:s');
                                        TicketList::insert($ticket);
                                    }
                                    $anna['afs_statues'] = $labstate['lt_type'];
                                    $anna['afs_order'] = $orderListArr['order_num'];
                                    $anna['afs_serial'] = $orderListArr['serial_number'];
                                    $anna['afs_sales'] = 2;
                                    $anna['afs_granid'] = 20;
                                    $anna['afs_paid'] = 25;
                                    $anna['afs_type'] = $input['setmoney_type'];
                                    $anna['afs_pid'] = $orderListArr['p_id'];
                                    $anna['afs_serid'] = $orderListArr['ser_id'];
                                    $anna['afs_creactime'] = date('Y-m-d H:i:s');
                                    $anna['asf_time'] = date('Y-m-d H:i:s');
                                    $anna['afs_day'] = date('Y-m-d');
                                    $anna['afs_content'] = $input['note_content'];
                                    $anna['afs_creacter'] = $request->get('session_token')['admin_acc'];
                                    $anna['afs_dealer'] = $request->get('session_token')['admin_acc'];
                                    Aftersale::insert($anna);
                                    //$sql2 .= "('".$labstate['lt_type']."','".$orderListArr['order_num']."','".$orderListArr['serial_number']."','2','".$grand."','".$parent."','".$val."','".$orderListArr['p_id']."','".$orderListArr['ser_id']."','".date('Y-m-d H:i:s')."','".date('Y-m-d H:i:s')."','".date('Y-m-d')."','".$admin_name."','".$admin_name."'),";
                                }
                                $sql2 = substr($sql2,0,strlen($sql2)-1);
                                //DB::insert($sql2);
                                // 成功
                                $retu=$this->editVisit($orderListArr['serial_number'],4);
                                if($orderListArr['p_id']=="105"){
                                }
                                $temp = Temporary::where('serial_number',$orderListArr['serial_number'])->update(['rejection_time'=>date("Y-m-d H:i:s"),'update_time'=>date("Y-m-d H:i:s"),
                                    'refusal_person'=>$request->get('session_token')['admin_acc'],'refusal_id'=>$request->get('session_token')['id'],'category'=>2]);

                                $workres = $this->workorder($input['sys_num'],$input['ser_id'],$input['user_id'],$admin_acc,$admin_groupnew,$id,$ip);
                                if ($workres == 1) {
                                    DB::commit();
                                    return response()->json(['Data'=>'','ErrorMessage'=>'成功','ErrorCode'=>1]);exit;
                                } elseif ($workres == 5) {
                                    DB::rollback();
                                    return response()->json(['ErrorMessage'=>'派单失败，请添加服务费！','ErrorCode'=>$workres]);exit;
                                } elseif ($workres == 6) {
                                    DB::rollback();
                                    return response()->json(['ErrorMessage'=>'通知养车宝失败，请刷新核实！','ErrorCode'=>$workres]);exit;
                                } elseif ($workres == 7) {
                                    DB::rollback();
                                    return response()->json(['ErrorMessage'=>'通知乐车邦失败,请刷新核实！','ErrorCode'=>$workres]);exit;
                                } elseif ($workres == 8) {
                                    DB::rollback();
                                    return response()->json(['ErrorMessage'=>'通知畅通车友失败！请刷新核实！','ErrorCode'=>$workres]);exit;
                                } elseif ($workres == 67) {
                                    DB::rollback();
                                    return response()->json(['ErrorMessage'=>'骆驼对接无该条数据！','ErrorCode'=>$workres]);exit;
                                } elseif ($workres == 10) {
                                    DB::rollback();
                                    return response()->json(['ErrorMessage'=>'派单失败，该订单已被派单，请刷新核实！','ErrorCode'=>$workres]);exit;
                                } elseif ($workres == 2) {
                                    DB::rollback();
                                    return response()->json(['ErrorMessage'=>'派单失败，请刷新核实！','ErrorCode'=>$workres]);exit;
                                } else {
                                    DB::rollback();
                                    return $workres;exit;
                                }

                            }else{
                                DB::rollback();
                                return response()->json(['Data'=>'','ErrorMessage'=>'失败','ErrorCode'=>2]);exit;
                            }
                        }else{
                            //结算表修改失败
                            DB::rollback();
                            return response()->json(['Data'=>'','ErrorMessage'=>'结算表修改失败','ErrorCode'=>5]);exit;
                        }
                    }else{
                        //orderlist失败
                        DB::rollback();
                        return response()->json(['Data'=>'','ErrorMessage'=>'orderlist失败','ErrorCode'=>6]);exit;
                    }
                }else{
                    // 该单状态不正确
                    DB::rollback();
                    return response()->json(['Data'=>'','ErrorMessage'=>'订单状态不正确4','ErrorCode'=>14]);exit;
                }
            }catch(Exception $e){
                return response()->json(['Data'=>'','ErrorMessage'=>$e->getMessage(),'ErrorCode'=>13]);exit;
            }

        }else{
            return response()->json(['Data'=>'','ErrorMessage'=>'备注失败','ErrorCode'=>6]);exit;
        }
    } */



    /**
     * @name 编辑负责人手机号
     * @param ser_id 服务商ID
     * @param head_phone 电话
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月4日下午2:27:40
     */
    public function editHeadPhone (Request $request)
    {
        if ($request->filled('ser_id','head_phone')) {
        	$res = AdminInfor::where('admin_id',$request->input('ser_id'))->update(['head_phone' => $request->input('head_phone')]);
        	if ($res) {
        		return $this->success('操作成功');exit;
        	} else {
        		return $this->error('操作失败', ErrorInc::MYSQL_FAILED);exit;
        	}
        } else {
            return $this->error('参数错误无ser_id或无head_phone', ErrorInc::FAILED_PARAM, []);exit;
        }

    }


    /**
     *@param $type   1接单2拒单
     * @param $ser_id 服务商ID
     * @param $stauas 订单状态：10未接单  30 已接单
     * @param  $type
     * @param  $ser_id
     * @param  $stauas
     * @author du 2021年8月3日上午10:38:59
     */
    public function probability ($type,$ser_id,$stauas ){

    	$db = new Probability();
    	$params = ['prb_sid'=>$ser_id];
    	$res = CommonService::getMysqlData($db, $params,[],[],'first');
        if($res){
            $Ym = date("Y-m");
            $prb_creatime = substr($res['prb_creatime'],0,7);
            if($type=="2"){
                if($Ym==$prb_creatime){
                    $poss['prb_refuse'] = $res['prb_refuse']+1;
                    if($res['prb_receive'] != '0' && $stauas=="30"){
                        $poss['prb_receive'] = $res['prb_receive']-1;
                    }
                }else{
                    $poss['prb_refuse'] = 1;
                    $poss['prb_receive'] = 0;
                }
            }else{
                if($Ym==$prb_creatime){
                    $poss['prb_receive'] = $res['prb_receive']+1;
                }else{
                    $poss['prb_receive'] = 1;
                    $poss['prb_refuse'] = 0;
                }
            }
            Probability::where('prb_sid',$ser_id)->update($poss);
        }else{
            $poss['prb_sid'] = $ser_id;
            if($type=="2"){
                $poss['prb_refuse'] = 1;
            }else{
                $poss['prb_receive'] = 1;
            }
            Probability::insert($poss);
        }
    }

    /**
     * 订单金额明细
     * @param status 状态值
     * @param serial_number 工单系列号
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年8月6日下午1:34:52
     */
    public function getOrderPrice(Request $request){
    	if(!$request->filled('serial_number')||!$request->filled('status')){
    		return $this->error('参数错误无serial_number或无status', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$status = $request->input('status');
    	if(!in_array($status,[34,40])){
    		return $this->error('状态不正确', ErrorInc::FAILED_PARAM);
    	}
    	$serial_number = $request->input('serial_number');
    	$sid = SettlementList::where('list_id',$serial_number)->value('id');
    	if(!$sid){
    		return $this->error('暂无数据1',ErrorInc::DATA_EMPTY);
    	}
    	$data = SettlementService::getPriceById($sid);
    	if($data){
    	    unset($data['all_price']);
    		return $this->success('获取成功',$data);
    	}else{
    		return $this->error('暂无数据',ErrorInc::DATA_EMPTY);
    	}

    }



    //不参与奖惩平台
	public function rulesout(){
        $arr = [];
        $arr　=　array('111','112','108','95','106','110','120','136');
		return $arr;
	}




    //接口访问
    public function request_posts($url,$param) {
        $header = array(
            'Content-Type: application/json',
        );
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
        $response = curl_exec($ch);
        curl_close($ch);
        return trim($response);
    }



    //生成短域名识别码
    public function scurl ( $serial_number ,$num ){
        $string=md5(md5($serial_number));
        $string=substr($string,0,$num);
        $res=DB::table('install_scourl')->where('ins_code',$string)->value('ins_id');
        if($res){
            $num++;
            $this->scurl($serial_number,$num);
        }else{
            return $string;
            //$_SESSION['urlcode'][$serial_number]=$string;
        }
    }


    /**
     * @name 派单数量统计
     * @param time 时间
     * @param type 1:按平台单号统计 2：按ID数量统计
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/8
     */
    public function ordersDispatchDatas(Request $request)
    {
        if (!$request->filled('time')||!$request->filled('type')) {
            return $this->error('参数错误无time或无type', ErrorInc::FAILED_PARAM, []);exit;
        }
        $rime1 = $request->input('time');
        $rime2 = date("Y-m-d",strtotime($rime1." +1 month"));
        if($request->input('type') == '1'){
            $sql = "SELECT COUNT(DISTINCT order_num) AS num,admin_id FROM `gone_order_list` WHERE create_time BETWEEN '".$rime1."' and '".$rime2."' GROUP BY admin_id";
        }else{
            $sql = "SELECT COUNT(id) AS num,admin_id FROM `gone_order_list` WHERE create_time BETWEEN '".$rime1."' and '".$rime2."' GROUP BY admin_id";
        }
        $list = DB::select($sql);
        if($list){
            $admin = Admin::pluck('admin_acc','id');
            foreach( $list as $k => $v ){
                $list[$k]['admin_acc'] = $admin[$v['admin_id']];
            }
            return $this->success('获取成功',$list);
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
        }

    }

    /**
     * @param name 更新延期审图 延期结算
     * @param type 1:延期审图 2;延期结算
     * @param id 工单数据ID
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/11/19
     */
    public function delayStatus(Request $request){
        if (!$request->filled('id')||!$request->filled('type')||!$request->filled('note')) {
            return $this->error('参数错误无工单ID或无type或无note', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('id'));
        $type = intval($request->input('type'));
        //获取工单状态
        $status = OrderListService::getOrderListBy('id', $id ,'first' ,['stauas','sys_num']);
        if($status['stauas']!=34){
            return $this->error('状态不正确', ErrorInc::MYSQL_FAILED);
        }
        if($type==1){
            $delay_status = 2;//延期审图
           $note_content = '延期审图 '.$request->input('note');
        }elseif($type==2){
            $delay_status = 3;//延期结算
            $note_content = '延期结算 '.$request->input('note');
        }else{
            return $this->error('参数错误type错误', ErrorInc::FAILED_PARAM, []);exit;
        }
        $res = OrderList::where('id',$id)->update(['delay_status'=>$delay_status]);//1:正常；2：延期审图；3：延期结算
        if($res){

            //添加备注
            $rest = CommonService::accMe($status['sys_num'],'派工单列表',"延期状态：".$note_content,$status['sys_num'],'1',$request->get('session_token')['admin_groupnew'],$request->get('session_token')['admin_acc'],$request->get('session_token')['id']);//添加备注

            $this->insertingLog("延期审图，",$status['sys_num'],"更新为：".$delay_status,"工单管理",$request->ip(), $request->get('session_token')['admin_acc']);//日志
            return $this->success('更新成功');
        }else{
            return $this->error('更新失败', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * @param name 恢复正常（将延期审图 延期结算）
     * @param id 工单数据ID
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/11/19
     */
    public function returnDelayStatus(Request $request){
        if (!$request->filled('id')) {
            return $this->error('参数错误无工单ID', ErrorInc::FAILED_PARAM, []);exit;
        }
        $id = intval($request->input('id'));
        //获取工单状态
        $status = OrderListService::getOrderListBy('id', $id ,'first' ,['stauas','delay_status','sys_num']);
        if($status['stauas']!=34||$status['delay_status']==1){
            return $this->error('状态不正确', ErrorInc::MYSQL_FAILED);
        }
        $res = OrderList::where('id',$id)->update(['delay_status'=>1]);//1:正常；2：延期审图；3：延期结算
        if($res){
            $this->insertingLog("延期审图，",$status['sys_num'],"恢复为：1 正常","工单管理",$request->ip(), $request->get('session_token')['admin_acc']);//日志
            return $this->success('恢复成功');
        }else{
            return $this->error('恢复失败', ErrorInc::MYSQL_FAILED);
        }
    }

    /**
     * @name 获取延期状态名
     * @return mixed
     * @author du
     * @date 2021/11/19
     */
    public function getDelayStatusName(){
        $data = OrderListService::getDelayStatusName();

        return $this->success('获取成功',$data);
    }

    /**
     * @param Request $request
     * @return array|string|string[]
     * @author du
     * @date 2022/2/11
     */
    public function sendSmsOrderListModel(Request $request){
        $input = $request->all();
        $session = $request->get("session_token");
        $ret = CommonService::sendMsgCommonModel($input, $session);
        return $ret;
    }

    /**
     * @name 修改工时费
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2022/3/21
     */
    public function updateManhourfee(Request $request){
        if (!$request->filled('id')||!$request->filled('hourfee')) {
            return $this->error('参数错误无工单ID或工时费', ErrorInc::FAILED_PARAM, []);exit;
        }
        $input = $request->only('hourfee');
        $id = intval($request->input('id'));
        DB::beginTransaction();
        //获取工单状态
        $status = OrderListService::getOrderListBy('id', $id ,'first' ,['stauas','manhourfee','sys_num']);
        if(in_array($status['stauas'],['1','3','5','10','20'])){
            $res = OrderList::where('id',$id)->update(['manhourfee'=>$input['hourfee']]);
            $mret = 1;
            $sret = 1;
        }elseif(in_array($status['stauas'],['40','30','34'])){
            //cho 2;exit;
            $wam = SettlementList::where('serial_number',$id)->select('wat_num','id')->first();

            if($wam['wat_num']){
                return $this->error('已经生成结算单,不可修改', ErrorInc::MYSQL_FAILED);exit;
            }else{
                $res = OrderList::where('id',$id)->update(['manhourfee'=>$input['hourfee']]);
                $exsit = SettlementMoney::where('sem_slid',$wam['id'])->where('sem_type',1)->value('sem_id');
                if($exsit){
                    $mret = SettlementMoney::where('sem_slid',$wam['id'])->where('sem_type',1)->update(['sem_price'=>$input['hourfee']]);
                }else{
                    $mret = SettlementService::createSettMoney($wam['id'], $status['sys_num'], $input['hourfee'],$request->get('session_token')['admin_acc'],1); ;
                }
                if(!$mret){
                    DB::rollback();
                    return $this->error('供货价修改失败-'.$wam['id'], ErrorInc::MYSQL_FAILED);exit;
                }
                $all_price = SettlementMoney::where('sem_slid',$wam['id'])->sum('sem_price');
                $sret = SettlementList::where('serial_number',$id)->update(['order_price'=>$input['hourfee'],'all_price'=>$all_price]);
                if(!$sret){
                    DB::rollback();
                    return $this->error('结算价修改失败', ErrorInc::MYSQL_FAILED);exit;
                }
            }
        }else{
            return $this->error('状态不正确', ErrorInc::MYSQL_FAILED); exit;
        }
        if($res&&$sret&&$mret){
            DB::commit();
            $this->insertingLog("修改工时费，",$status['sys_num'],"工时费由：".$status['manhourfee'].'修改为'.$input['hourfee'],"工单管理",$request->ip(), $request->get('session_token')['admin_acc']);//日志
            return $this->success('操作成功');
        }else{
            DB::rollback();
            return $this->error('操作失败', ErrorInc::MYSQL_FAILED);
        }
    }


  /* @param id  工单id
     * @param install_person 安装技师id　type=２时
     * @param type  1：物流派送 2：上门安装
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed|\Illuminate\Http\JsonResponse
     * @author du 2022年3月23日下午2:49:41
     */
    public function patchGetOrder (Request $request)
    {
        $input['type'] = 2;//$request->only('id', 'install_person', 'type', 'ex_name', 'ex_number', 'order_price');

        if($request->filled('id')&&intval($request->input('id'))>0){
        $id = intval($request->input('id'));
            $info = OrderList::whereIn('stauas',[10,20])->where('id',$id)->first();
        }else{
            $info = OrderList::whereIn('stauas',[10,20])->first();
        }
        if(empty($info)){
            return $this->error('无数据', ErrorInc::MYSQL_FAILED);
        }
        $db = new InstallPerson();
        $params = ['admin_id'=>$info['ser_id'],'delet_y'=>'1','install_is_type'=>'1','install_state'=>'1','install_pid_searchin'=>['0','']];
        $select = ['id'];
        $rest = CommonService::getMysqlData($db, $params,$select,[],'value');
        $input['id'] = $info['id'];
        $input['install_person'] = $rest;
        $ret = $this->executeGetOrder($input, $request->get('session_token'), $request->ip());

        if($ret->original['ErrorCode']==1){
            return $this->error('操作成功:'.$info['order_num'], 10086);
        }else{
            return $this->error('操作失败:'.$info['order_num'], 10086);
            //return $ret->original;
        }

    }
    /**|---------------------------------------------------------------------------------
     * @name 指派门店
     * @param string id 服务工单id
     * @param string ser_id 改派的服务门店
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2024/9/19 15:15
     * |---------------------------------------------------------------------------------
     */
    public function sendAgain ( Request $request ){
        if (!$request->filled('id')||!$request->filled('ser_id')) {
            return $this->error('参数错误无工单ID或服务商id', ErrorInc::FAILED_PARAM, []);exit;
        }
        $return = OrderListService::sendAgain($request->all(),$request->ip(),$request->get('session_token'));
        return $this->error($return['ErrorMessage'], $return['ErrorCode'], $return['Data']);
    }
    private function getSign($params,$sec) {
        if ($params != null) { // 所有请求参数按照字母先后顺序排序
            ksort($params);
            // 定义字符串开始 结尾所包括的字符串
            $stringToBeSigned = $sec;//'eb229319be99494583fe87810b608123';//'8de8b7903e7740abb9ac6ec39f22c0e5';
            // 把所有参数名和参数值串在一起
            foreach ($params as $k => $v) {
                $stringToBeSigned .= "$k$v";
            }
            unset($k, $v);

            // 把venderKey加在字符串的两端
            $stringToBeSigned .= $sec;//'eb229319be99494583fe87810b608123';//'8de8b7903e7740abb9ac6ec39f22c0e5';
        } else {
            // 定义字符串开始 结尾所包括的字符串
            $stringToBeSigned = $sec;//'eb229319be99494583fe87810b608123';//'8de8b7903e7740abb9ac6ec39f22c0e5';
            // 把venderKey加在字符串的两端
            $stringToBeSigned .= $sec;//'eb229319be99494583fe87810b608123';//'8de8b7903e7740abb9ac6ec39f22c0e5';
        }
        // 使用MD5进行加密，再转化成大写

       // return strtoupper(md5($stringToBeSigned));
        // 使用MD5进行加密，再转化成小写
        return strtolower(md5($stringToBeSigned));
    }

    function https_request($url,$data = null){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)){
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }

}
