<?php

namespace App\Http\Controllers\Supplychain;

use App\Services\CommonService;
use Complex\Exception;
use App\Http\Controllers\BaseController as BaseController;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use DB;

class SupplyMzchainController extends BaseController
{


    /**|*********************************************************************************|
     * @name  推送服务商信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author he  <2020/3/20 13:57>
     *|**********************************************************************************|
     */
    public function get_user(Request $request)
    {
        $req = file_get_contents("php://input");
        //dd($request);
        $arr = json_decode($req, true);
        if ($arr['ser_id']) {
            $result = DB::table('admin')->where('id', $arr['ser_id'])->first([
                'id','company_name', 'admin_acc', 'is_lidao'
            ]);
            if ($result) {
                $dress = DB::table('admin_infor')->where('admin_id', $result['id'])->first(['admin_province','admin_city','admin_county']);
                $result['admin_dress'] = $dress['admin_province'] . $dress['admin_city'] . $dress['admin_county'];
                if ($result) {
                    return response()->json(['data' => $result,'code' => 200, 'msg' => '成功']);
                    exit;
                } else {
                    return response()->json(['code' => 201, 'msg' => '匹配失败']);
                    exit;
                }
            } else {
                return response()->json(['code' => 201, 'msg' => '匹配失败']);
                exit;
            }



        } else {
            return response()->json(['code' => 202, 'msg' => '参数错误']);
            exit;
        }
    }



    /**|*********************************************************************************|
     * @name 补货完成同步
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author he  <2020/3/25 11:40>
     *|***********************************************************************************|
     */
    public function get_supply_chain (Request $request)
    {
        $req = file_get_contents("php://input");
        $req = json_decode($req, true);
        //return response()->json($req);exit;
        if (empty($req['wat_num'])) {
            return response()->json(['code' => '202', 'msg' => '参数错误']);exit;
        }
        DB::beginTransaction();

        if ($req['store_list'] && $req['store_list'] != []) {

            $store_list = $req['store_list'];

            $pid = DB::table('bh_watlist')->insertGetId([
                'bl_wat' => $req['wat_num'],
                'bl_watnew' => '',
                'bl_serid'  => $store_list['ser_id'],
                'bl_storeid' =>$store_list['wd_id'],
                'bl_price'   => round($store_list['all_price']/100,2),
                'bl_nums'   => $store_list['distri_num'],
                'bl_time'   => date("Y-m-d H:i:s"),
            ]);

            if ((isset($store_list['good_list']) && $store_list['good_list'] != [])) {

                $good_list = array_values($store_list['good_list']);
                $goodArr = [];
                foreach ($good_list as $k => $v) {
                    $goodArr[$k]['blg_gid'] = $v['pg_id'];
                    $goodArr[$k]['blg_gname'] = $v['good_name'];
                    $goodArr[$k]['blg_price'] = $v['price'];
                    $goodArr[$k]['blg_allprice'] = round($v['good_num'] * $v['price']/100,2);
                    $goodArr[$k]['blg_num'] = $v['good_num'];
                    $goodArr[$k]['blg_bhid'] = $pid;
                    $goodArr[$k]['blg_type'] = 1;

                }
                $req1 = DB::table('bh_glist')->insert($goodArr);
                if (!$req1) {
                    DB::rollBack();
                    return response()->json([ 'code' =>201, 'msg' => '推送失败']);exit;
                }

            }

            if (isset($store_list['damaged_list']) && $store_list['damaged_list'] != []) {
                $damaged_list = array_values($store_list['damaged_list']);
                $damagedArr = [];

                foreach ($damaged_list as $k => $v) {
                    $damagedArr[$k]['blg_gid'] = $v['pg_id'];
                    $damagedArr[$k]['blg_gname'] = $v['good_name'];
                    $damagedArr[$k]['blg_price'] = $v['price'];
                    $damagedArr[$k]['blg_allprice'] = intval($v['good_num']) * intval($v['price'])/100;
                    $damagedArr[$k]['blg_num'] = $v['good_num'];
                    $damagedArr[$k]['blg_bhid'] = $pid;
                    $damagedArr[$k]['blg_type'] = 2;
                }

                $req2 = DB::table('bh_glist')->insert($damagedArr);
                if (!$req2) {
                    DB::rollBack();
                    return response()->json([ 'code' =>201, 'msg' => '推送失败']);exit;
                }
            }

        }elseif ($req['sd_list'] && $req['sd_list'] != []) {

            $sd_list = $req['sd_list'];

            $pid = DB::table('bh_watlist')->insertGetId([
                'bl_wat' => $req['wat_num'],
                'bl_watnew' => '',
                'bl_serid'  => $sd_list['ser_id'],
                'bl_storeid' =>$sd_list['wd_id'],
                'bl_price'   => $sd_list['all_price']/100,
                'bl_nums'   => $sd_list['distri_num'],
                'bl_time'   => date("Y-m-d H:i:s"),
            ]);

            if ((isset($sd_list['good_list']) && $sd_list['good_list'] != [])) {

                $good_list = array_values($sd_list['good_list']);
                $goodArr = [];
                foreach ($good_list as $k => $v) {
                    $goodArr[$k]['blg_gid'] = $v['pg_id'];
                    $goodArr[$k]['blg_gname'] = $v['good_name'];
                    $goodArr[$k]['blg_price'] = 0;
                    $goodArr[$k]['blg_allprice'] = 0;
                    $goodArr[$k]['blg_num'] = $v['good_num'];
                    $goodArr[$k]['blg_bhid'] = $pid;
                    $goodArr[$k]['blg_type'] = 1;

                }
                $req1 = DB::table('bh_glist')->insert($goodArr);
                if (!$req1) {
                    DB::rollBack();
                    return response()->json([ 'code' =>201, 'msg' => '推送失败']);exit;
                }

            }

            if (isset($sd_list['damaged_list']) && $sd_list['damaged_list'] != []) {
                $damaged_list = array_values($sd_list['damaged_list']);
                $damagedArr = [];

                foreach ($damaged_list as $k => $v) {
                    $damagedArr[$k]['blg_gid'] = $v['pg_id'];
                    $damagedArr[$k]['blg_gname'] = $v['good_name'];
                    $damagedArr[$k]['blg_price'] = 0;
                    $damagedArr[$k]['blg_allprice'] = 0;
                    $damagedArr[$k]['blg_num'] = $v['good_num'];
                    $damagedArr[$k]['blg_bhid'] = $pid;
                    $damagedArr[$k]['blg_type'] = 2;
                }

                $req2 = DB::table('bh_glist')->insert($damagedArr);
                if (!$req2) {
                    DB::rollBack();
                    return response()->json([ 'code' =>201, 'msg' => '推送失败']);exit;
                }
            }
        } else {
            DB::rollBack();
            return response()->json([ 'code' =>202, 'msg' => '参数错误']);exit;
        }
        DB::commit();
        return response()->json([ 'code' =>200, 'msg' => '推送成功']);exit;

    }


    /**|---------------------------------------------------------------------------------
     * @name  残损抵扣
     * @param
     * @return \Illuminate\Http\JsonResponse
     * @author he <2020/4/29 18:03>
     *|---------------------------------------------------------------------------------
     */
    public function syncGetDamaged ()
    {
        $req = file_get_contents("php://input");
        $req = json_decode($req, true);
        //return response()->json($req);exit;
        if (empty($req['pg_id']) || empty($req['good_name']) || empty($req['good_num']) || empty($req['all_price'])) {
            return response()->json(['code' => '202', 'msg' => '参数错误']);exit;
        }

        if ($req['good_num'] <= 0) {
            return response()->json(['code' => '202', 'msg' => '参数错误']);exit;
        }

        DB::beginTransaction();
        $pid = DB::table('bh_watlist')->insertGetId([
            'bl_wat'     => $req['wat_num'],
            'bl_watnew'  => '',
            'bl_serid'   => $req['ser_id'],
            'bl_storeid' =>$req['ser_id'],
            'bl_price'   => -$req['all_price']/100,
            'bl_nums'   => $req['distri_num'],
            'bl_time'    => date("Y-m-d H:i:s"),
            'bl_type'    => 2
        ]);

        $all_price = $req['all_price']/100;
        $result = DB::table('bh_glist')->insert([
            'blg_gid'      => $req['pg_id'],
            'blg_gname'    => $req['good_name'],
            'blg_price'    => -$all_price/$req['good_num'],
            'blg_allprice' => $req['all_price'],
            'blg_num'      => $req['good_num'],
            'blg_bhid'     => $pid,
            'blg_type'     => 3
        ]);

        if ($pid && $result) {
            DB::commit();
            return response()->json([ 'code' =>200, 'msg' => '成功']);exit;
        } else {
            DB::rollBack();
            return response()->json([ 'code' =>201, 'msg' => '推送失败']);exit;
        }
    }

    /**|*********************************************************************************|
     * @name  同步技师
     * @param id       门店数据id
     * @param name     技师姓名
     * @param phone    技师手机号
     * @param store_id 对应门店id
     * @return \Illuminate\Http\JsonResponse
     * @author he  <2020/4/6 9:28>
     *|***********************************************************************************|
     */
    public function sync_install_persion (Request $request)
    {
//        $req = file_get_contents("php://input");
//        $req = json_decode($req, true);
//
//        if (empty($req['id']) || empty($req['name']) || empty($req['phone']) || empty($req['store_id'])) {
//            return response()->json(['code' => '202', 'msg' => '参数错误']);exit;
//        }
        $req = json_decode(file_get_contents("php://input"), true);
        if(!$this->validationKey($req,['id','name','phone','store_id'])){
            return response()->json(['msg' => '参数错误', 'code' => 202]);
        }
        $data['data']=json_encode($req);
        $data['api']='sync_install_persion';
        DB::table('store_data')->insert($data);
        if ($req['type'] == 1) {
            $exit = DB::table('install_person')->where('bind_id', $req['id'])->first();

            if ($exit) {
                if($req['name']==$exit['install_name'] && $req['phone']==$exit['install_phone'] && $req['store_id']==$exit['admin_id']){
                    return response()->json([ 'code' =>200, 'msg' => '同步成功']);exit;
                }
                $upRes = DB::table('install_person')->where('bind_id', $req['id'])->update([
                    'install_name' => $req['name'],
                    'install_phone' => $req['phone'],
                    'admin_id' => $req['store_id'],
                    'updata_time'=>date("Y-m-d H:i:s"),
                    'delet_y'  => 1
                ]);

                if ($upRes){
                    return response()->json([ 'code' =>200, 'msg' => '同步成功']);exit;
                }else{
                    return response()->json([ 'code' =>201, 'msg' => '同步失败']);exit;
                }
            }

            $check_code = DB::table('install_person')->whereRaw("admin_id='".$req['store_id']."' and check_code>10000000 and check_code<100000000")->orderBy('check_code','DESC')->limit('1')->value('check_code');
            $length=strlen($check_code);
            if($length==8){
                $num=rand(5,99);
                $che=$check_code+$num;
                $bin=strpos($che,"4");
                if($bin){
                    $arr['check_code']=str_replace("4",'5',$che);
                }else{
                    $arr['check_code']=$che;
                }
            }else{
                $certification_num = DB::table('certification')->where('ser_id',$req['store_id'])->value('certification_num');
                if(empty($certification_num)){
                    return response()->json([ 'code' =>201, 'msg' => '门店不存在']);exit;
                }else{
                    $arr['check_code']=$certification_num."1001";
                }
            }

            $arr['install_name'] = $req['name'];
            $arr['install_phone'] = $req['phone'];
            $arr['admin_id'] = $req['store_id'];
            $arr['company_id'] = 0;
            $arr['install_password1'] = $arr['check_code'];
            $arr['install_password'] = md5($arr['check_code']);
            $arr['bind_id'] = $req['id'];
            $insRes = DB::table('install_person')->insert($arr);

            if ($insRes){
                return response()->json([ 'code' =>200, 'msg' => '同步成功']);exit;
            }else{
                return response()->json([ 'code' =>201, 'msg' => '同步失败']);exit;
            }
        } elseif ($req['type'] == 2) {
            $delRes = DB::table('install_person')->where('bind_id', $req['id'])->update(['delet_y' => 2,'updata_time'=>date("Y-m-d H:i:s")]);
            if ($delRes){
                return response()->json([ 'code' =>200, 'msg' => '同步成功']);exit;
            }else{
                return response()->json([ 'code' =>201, 'msg' => '同步失败']);exit;
            }

        }

    }



    /**|*********************************************************************************|
     * @name  同步 接单、拒单状态
     * @param serial_number
     * @param install_id 技师（门店id）
     * @param iP 访问ip
     * @return \Illuminate\Http\JsonResponse
     * @author he  <2020/4/6 11:43>
     *|***********************************************************************************|
     */
    public function sync_receipt_status ()
    {
        $req = json_decode(file_get_contents("php://input"), true);
        //dump($req);
        if($req['type']=='2'){
            if(!$this->validationKey($req,['serial_number','ip','type','sin_bid','content','sin_bcentent'])){
                return response()->json(['msg' => '参数错误', 'code' => 202]);
            }
        }else{
            if(!$this->validationKey($req,['serial_number','ip','type'])){
                return response()->json(['msg' => '参数错误', 'code' => 202]);
            }
        }
        $Ip = $req['ip'];
        $orderListArr = DB::table('order_list')->where('serial_number',$req['serial_number'])->select('id','create_time','sys_num','order_num','locklist_type','orli_type','serial_number','p_id','order_goods_id','ser_id','customer_id','stauas','pay_typel','company_id')->first();
        if(empty($orderListArr)){
            return response()->json(['msg'=>'单号错误','code'=>202]);exit;
        }
//        $is_lidao = DB::table('admin')->where('id',$orderListArr['ser_id'])->value('is_lidao');

        // 不等于未接单
        if($orderListArr['locklist_type']==2){
            return response()->json(['msg'=>'该订单已锁定，不可操作','code'=>4]);exit;
        }
        if($req['type'] == 2){
            if($orderListArr['stauas']!=10 && $orderListArr['stauas']!=20 && $orderListArr['stauas']!=30){
                return response()->json(['msg'=>'该状态不可拒单','code'=>3]);exit;
                exit;
            }
        }else{
            if($orderListArr['stauas'] != 10 && $orderListArr['stauas'] != 20){
                if($orderListArr['stauas']=='30'){
                    if(!isset($req['install_id'])){
                        $instArr = DB::table('install_person')->where('id',1)->select('id','install_name','install_phone','check_code','bind')->first();
                    }else{
                        $instArr = DB::table('install_person')->where('bind_id',$req['install_id'])->select('id','install_name','install_phone','check_code','bind')->first();
                    }
                    if(empty($instArr)){
                        return response()->json(['msg' => '技师未绑定', 'code' => 204]);exit;
                    }
                    $install_id=DB::table('order_list')->where('serial_number',$req['serial_number'])->value('install_id');
                    if($instArr['id']==$install_id){
                        return response()->json(['msg' => '操作成功', 'code' => 200]);
                        exit;
                    }
                    $post['install_id']=$instArr['id'];//安装人id
                    $post['intall_person']=$instArr['install_name'];//安装人姓名
                    $post['intall_phone']=$instArr['install_phone'];//安装人电话
                    $get['intall_person']=$instArr['install_name'];//安装人姓名
                    $get['intall_phone']=$instArr['install_phone'];//安装人电话
                    DB::beginTransaction();
                    $restOrderList = DB::table('order_list')->where('serial_number',$req['serial_number'])->update($post);
                    $restSettlementList=DB::table('settlement_list')->where('list_id',$req['serial_number'])->update($get);
                    if(empty($restOrderList) || empty($restSettlementList)){
                        DB::rollback();
                        return response()->json(['msg' => '操作失败', 'code' => 201]);
                    }else{
                        DB::commit();
                        return response()->json(['msg' => '操作成功', 'code' => 200]);
                    }
                }else {
                    return response()->json(['msg' => '该状态不可接单4444'.$orderListArr['stauas'], 'code' => 5]);
                    exit;
                }
            }
        }

        $admins = DB::table('admin')->where('id',$orderListArr['ser_id'])->first();
        $admin_acc=$admins['admin_acc'];

        // 拒单
        if($req['type'] == 2){
            //$returncount = DB::table('order_list')->where('sys_num',$orderListArr['sys_num'])->where('stauas','<','34')->count();
            $payout_time = DB::table('order_time')->where(['serial_number'=>$orderListArr['serial_number'],'is_type'=>'接单时间'])->orderBy('id','DESC')->value('create_time');
            if($payout_time <> ''){
                $zero1=time();
                $zero2=strtotime($payout_time);
                $guonian=($zero1-$zero2)/60;
                if($guonian>11){
                    // return response()->json(['data'=>null,'desecption'=>'接单十分钟后不可拒单','state'=>6]);exit;
                }
            }
            $centent=$req['content']."；".$req['sin_bcentent'];
            // 添加备注
            /*$centent=$req['remark'];
            $this->Message($orderListArr['ser_id'],$orderListArr['sys_num'],"拒单，".$centent."(".$orderListArr['serial_number'].")","派工单(半径)",'0');*/
            $this->Message($orderListArr['ser_id'],$orderListArr['sys_num'],'【拒单】'.$centent,'拒单（门店）',$admins['company_name']);

            $is_html='拒单，';

            DB::beginTransaction();
            $labstate = DB::table('setmoney_type')->where("sety_id",$req['sin_bid'])->first();
            if(strstr((string)$labstate['sety_price'],'-')){
                $price = substr($labstate['sety_price'],1);
            }else{
                $price = $labstate['sety_price'];
            }
            $adddata['afs_statues'] = $labstate['sety_type'];
            $adddata['afs_order'] = $orderListArr['order_num'];
            $adddata['afs_serial'] = $orderListArr['serial_number'];
            $adddata['afs_sales'] = 1;
            $adddata['afs_paid'] = $labstate['lt_parent_id'];
            $adddata['afs_type'] = $req['sin_bid'];
            $adddata['afs_pid'] = $orderListArr['p_id'];
            $adddata['afs_serid'] = $orderListArr['ser_id'];
            $adddata['afs_creactime'] = date('Y-m-d H:i:s');
            $adddata['asf_time'] = date('Y-m-d H:i:s');
            $adddata['afs_day'] = date('Y-m-d');
            $adddata['afs_creacter'] = $admin_acc;
            $adddata['afs_dealer'] = "";
            $adddata['afs_content'] = $centent;
            $aftersale=DB::table("aftersale")->insert($adddata);
            $resultOrderList = DB::table('order_list')->where('serial_number',$req['serial_number'])->delete();
            //if($returncount==1){
            //    $data['refuse_ids']=$orderListArr['ser_id'];
            //    $data['ser_id']=0;
            //    $data['order_status']=10;

            //    DB::table('orders')->where('sys_num',$orderListArr['sys_num'])->update($data);
            //}
            $visit['ov_show']='4';

            $cisis = DB::table('order_visit')->where('ov_serial',$orderListArr['serial_number'])->update($visit);
            if($resultOrderList && $aftersale){
                $returncount = DB::table('order_list')->where('sys_num',$orderListArr['sys_num'])->count();
                if($returncount<1){
                    $data['refuse_ids']=$orderListArr['ser_id'];
                    $data['ser_id']=0;
                    $data['order_status']=10;
                    $rea=DB::table('orders')->where('sys_num',$orderListArr['sys_num'])->update($data);
                    if(!$rea){
                        DB::rollback();
                        return response()->json(['msg' => '拒单失败', 'code' => 201]); exit;
                    }
                }
                DB::commit();
                //拒单归还库存
                $sqlgid="SELECT count(*) as num,`goods_id` FROM `gone_order_msg` WHERE `sys_num`='".$orderListArr['sys_num']."' group by `goods_id`";
                //$goodid=$order_msg->query($sqlgid);
                $goodid = DB::select($sqlgid);
                $gsql="";
                $sql="INSERT INTO `gone_invenrecor`( `iv_serid`, `iv_goodid`, `iv_num`,`iv_serial`,`iv_ordernum`) 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']."','".$orderListArr['order_num']."'),";
                }

                $sql=trim($sql,',');

                DB::insert($sql);
                DB::update($gsql);

                //$this->probability('2',$orderListArr['ser_id'],$orderListArr['stauas']);//计算接单率
                //$management->where("`trace_code`='".$orderListArr['serial_number']."'")->delete();
                DB::table('management')->where('trace_code',$orderListArr['serial_number'])->delete();
                //$order_time->where("`serial_number`='".$orderListArr['serial_number']."'")->delete();
                DB::table('management')->where('trace_code')->delete();

                // 日志
                $this->Add_log($orderListArr['ser_id'],$Ip,'派工单(半径)',$is_html,"订单(".$orderListArr['serial_number'].")",$orderListArr['order_num']);
                $temaddtime['rejection_time']=date("Y-m-d H:i:s");
                $temaddtime['refusal_person']=$admin_acc;
                $temaddtime['refusal_id']=$orderListArr['ser_id'];
                $temaddtime['category']=2;
                $this->temaddtime($temaddtime,$orderListArr['serial_number']);
                return response()->json(['msg' => '拒单成功', 'code' => 200]); exit;

            }else{
                DB::rollback();
                return response()->json(['msg' => '拒单失败', 'code' => 201]); exit;
            }
            exit;
            // 接单
        }elseif($req['type'] == 1){
            $returncount = DB::table('order_list')->where('sys_num',$orderListArr['sys_num'])->whereRaw("stauas = 10 or stauas=20")->count();

            $stauasa = DB::table('order_list')->where('serial_number',$req['serial_number'])->first();

            //接单同步数据进入技师路线表
            $stauas=$stauasa['stauas'];
            if($stauas!='10' && $stauas!='20'){
                return response()->json(['msg'=>'该状态不可接单222','code'=>3]);exit;
            }

            $MsgArr = DB::table('order_msg')->where('id',$orderListArr['order_goods_id'])->select('goods_id','goods_name','goods_brand')->first();
            if(isset($req['install_id'])){
                $instArr = DB::table('install_person')->where('bind_id',$req['install_id'])->select('id','install_name','install_phone','check_code','bind')->first();
            }else{
                $instArr = DB::table('install_person')->where('id',1)->select('id','install_name','install_phone','check_code','bind')->first();
            }
            //$instArr = DB::table('install_person')->where('bind_id',$req['install_id'])->select('id','install_name','install_phone','check_code','bind')->first();
            if(empty($instArr)){
                return response()->json(['msg' => '技师未绑定', 'code' => 204]);exit;
            }
            $supply_price = DB::table('gh_price')->where(['goods_id'=>$MsgArr['goods_id'],'ser_id'=>$orderListArr['ser_id']])->orderBy('id',"DESC")->value('supply_price');
            if(!$supply_price) {
                $supply_price = DB::table('gh_price')->where(['goods_id' => $MsgArr['goods_id'], 'ser_id' => '0'])->orderBy('id', "DESC")->value('supply_price');
                if (!$supply_price) {
                    $supply_price = '0.00';
                }
            }

            $info['installation']=2;//安装分类(上门安装)

            $arr['sys_num']=$orderListArr['sys_num'];
            $arr['order_num']=$orderListArr['order_num'];
            $arr['msg_id']=$orderListArr['order_goods_id'];
            $arr['p_id']=$orderListArr['p_id'];
            $arr['list_id']=$orderListArr['serial_number'];

            $arr['ser_id']= $orderListArr['ser_id'];
            // 上门安装
            $arr['type']=2;
            // 安装人id
            $arr['installperson']=$instArr['id'];
            // 安装人名称
            $arr['intall_person']=$instArr['install_name'];
            // 安装人电话
            $arr['intall_phone']=$instArr['install_phone'];
            if(!empty($supply_price)){
                // 供货价
                $arr['order_price']=$supply_price;
                // 总金额
                $arr['all_price']=$supply_price;
            }

            // 结算状态
            $arr['sett_status']=1;
            // 工单状态
            $arr['list_service_type']=30;
            // 客户id
            $arr['customer_id']=$orderListArr['customer_id'];
            //订单状态
            $arr['sel_type']=$orderListArr['orli_type'];
            $arr['pay_types']=$orderListArr['pay_typel'];//支付方式
            $arr['serial_number']=$orderListArr['id'];
            $arr['company_id']=$orderListArr['company_id'];

            // 锁定状态
            $submit_stauas = DB::table('submit_please')->where(['submit_sys_num'=>$orderListArr['sys_num'],'msg_id'=>$orderListArr['order_goods_id']])->value('submit_stauas');
            if($submit_stauas==1){
                $arr['locked']=2;
            }
            // 接单
            $is_html='接单，';
        }

        /**追  溯**/
        $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']=DB::table('goods_brand')->where('brand_name',$MsgArr['goods_brand'])->value("brand_remark");//生产厂家
        $info['transport']=$sometime ;//入仓时间
        $info['order_time']=substr($times,0,10);//下单时间
        $info['install_one']=$instArr['install_name'];//安装人
        $info['replacing_time']=substr(date('Y-m-d H:i:s',strtotime('+2 year')),0,10);//建议更换时间
        //dd($info);
        /**派工单**/
        $post['stauas']=30;//派工单状态
        $post['install_id']=$instArr['id'];//安装人id
        $post['intall_person']=$instArr['install_name'];//安装人姓名
        $post['intall_phone']=$instArr['install_phone'];//安装人电话
        // $post['accept_time']=date("Y-m-d H:i:s");//添加接单时间;
        /**订  单**/
        $get['order_status']=30;//订单状态
        $get['intall_person']=$instArr['install_name'];//安装人姓名
        $get['intall_phone']=$instArr['install_phone'];//安装人电话
        //dd($get);

        DB::beginTransaction();

        $restOrderList = DB::table('order_list')->where('serial_number',$req['serial_number'])->update($post);

        $restSettlementList=DB::table('settlement_list')->insertGetId($arr);

        //$ov_id=$order_visit->where("ov_serial='".$stauasa['serial_number']."'")->getField('ov_id');
        $ov_id = DB::table('order_visit')->where('ov_serial',$stauasa['serial_number'])->value('ov_id');

        if($ov_id){
            $visit['ov_show']='2';
            //$cisis=$order_visit->where("ov_serial='".$stauasa['serial_number']."'")->save($visit);
            $cisis = DB::table('order_visit')->where('ov_serial',$stauasa['serial_number'])->update($visit);
        }else{
            $visit['ov_serial']=$stauasa['serial_number'];
            $visit['ov_sys']=$stauasa['sys_num'];
            $visit['ov_order']=$stauasa['order_num'];
            $visit['ov_creatime']=$stauasa['create_time'];
            $visit['ov_statue']='1';
            $visit['ov_show']='2';
            //dd($visit);
            $cisis=DB::table('order_visit')->insert($visit);

        }

        if($restSettlementList) {
            $money['sem_slid'] = $restSettlementList;
            $money['sem_synum'] = $orderListArr['sys_num'];
            $money['sem_price'] = (float)$supply_price;
            $money['sem_creacter'] = $admin_acc . "(半径)";
            $money['sem_type'] = 1;

            $sql = "insert into gone_settlement_money (sem_slid,sem_creacter,sem_synum,sem_price,sem_type) values ('".$restSettlementList."','".$money['sem_creacter']."','".$money['sem_synum']."',".$money['sem_price'].",'".$money['sem_type']."')";



            //DB::connection()->enableQueryLog();
            $res = DB::insert($sql);

            $tim = $orderListArr['create_time'];
            $sup_price = DB::table('support')->whereRaw("sup_serid like '%," . $orderListArr['ser_id'] . ",%' and sup_brname='" . $MsgArr['goods_brand'] . "' and sup_startime<'" . $tim . "' and sup_endtime>'" . $tim . "'")->value('sup_price');
            //dd($sup_price);
            if ($sup_price) {
                if ($sup_price > 0) {
                    $money['sem_slid'] = $restSettlementList;
                    $money['sem_synum'] = $orderListArr['sys_num'];
                    $money['sem_price'] = "-" .(double)$sup_price;
                    $money['sem_creacter'] = $admin_acc . "(半径)";
                    $money['sem_type'] = 12;
                    if ($admins['reward'] == '1') {
                        DB::table('settlement_money')->insert($money);
                    }
                    //$testa=M("`sdo2o_bluezp`.testa");
                    //$posa['sqlss']=$settlement_money->getlastsql();
                    //$testa->add($posa);
                }
            }
            #开始计算奖惩金额以及评分
            $payout_time = DB::table('order_time')->where(['serial_number'=>$orderListArr['serial_number'],'is_type'=>'起始时间'])->orderBy('id','DESC')->value('create_time');//获取奖罚派单时间
            //dd($payout_time);
            if ($payout_time == "") {
                $payout_time = DB::table('order_time')->where(['serial_number'=>$orderListArr['serial_number'],'is_type'=>'派单时间'])->orderBy('id','DESC')->value('create_time');//获取奖罚派单时间
            }
            $zero1 = time();
            $zero2 = strtotime($payout_time);
            $guonian = ($zero1 - $zero2) / 60;
            #计算评分
            if ($guonian <= 5) {
                $score['orsc_grade'] = 5;
            }
            if ($guonian > 5 && $guonian <= 10) {
                $score['orsc_grade'] = 2;
            }
            if ($guonian > 10) {
                $score['orsc_grade'] = 1;
            }
            $score['orsc_sernum'] = $orderListArr['serial_number'];
            $score['orsc_slid'] = $restSettlementList;
            $score['orsc_creacter'] = $admin_acc . "(半径)";
            $score['orsc_type'] = 1;
            DB::table('order_score')->insert($score);


            //默认生成平台评分十分
            $scoreq['orsc_grade'] = 5;
            $scoreq['orsc_sernum'] = $orderListArr['serial_number'];
            $scoreq['orsc_slid'] = $restSettlementList;
            $scoreq['orsc_creacter'] = $admin_acc."(半径)";
            $scoreq['orsc_type'] = 2;
            DB::table('order_score')->insert($scoreq);
            #计算奖惩金额
            $moneyjc['sem_slid'] = $restSettlementList;
            $moneyjc['sem_creacter'] = $admin_acc."(半径)";
            $moneyjc['sem_synum'] = $orderListArr['sys_num'];

            $moneyqj['sem_slid'] = $restSettlementList;
            $moneyqj['sem_creacter'] = $admin_acc."(半径)";
            $moneyqj['sem_synum'] = $orderListArr['sys_num'];
            //$moneyqj['sem_type']='14';
            //$leadsubsidie = M("leadsubsidie");
            //if($_POST['admin_id']=="587"){
            //	$ld_price=$leadsubsidie->where("ld_goodid='".$MsgArr['goods_id']."' and ld_type=1 and ld_release=1")->getField('ld_price');
            //}else{
            //	$ld_price=$leadsubsidie->where("ld_goodid='".$MsgArr['goods_id']."' and ld_type=1 and ld_release=1")->getField('ld_price');
            //}
            $ld_price = DB::table('leadsubsidie')->where(['ld_goodid'=> $MsgArr['goods_id'],'ld_type'=>'1','ld_release'=>'1'])->first();
            //if($ld_price){
            //	if($ld_price>0){
            //		$moneyqj['sem_price']=$ld_price;
            //		if($admins['reward']=='1'){
            //			$settlement_money->add($moneyqj);
            //		}
            //	}
            //}

            //*
            if ($ld_price) {
                if ($ld_price['ld_price'] > 0) {
                    $moneyqj['sem_price'] = $ld_price['ld_price']??'0';
                    $moneyqj['sem_type'] = $ld_price['le_setyid']??'0';
                    //if($admins['reward']=='1'){
                    DB::table('settlement_money')->insert($moneyqj);
                    //}
                }
            }
            if ($orderListArr['orli_type'] == 1) {
                $money_type = DB::table('setmoney_type')->whereRaw("sety_id in (2,3)")->value('sety_id','sety_price');//->select();
                if ($guonian <= 5) {
                    $moneyjc['sem_price'] = $money_type[2];
                    $moneyjc['sem_type'] = 2;
                }
                if ($guonian >= 15) {
                    $moneyjc['sem_price'] = $money_type[3];
                    $moneyjc['sem_type'] = 3;
                }
            } else {
                if ($orderListArr['orli_type'] == 10) {
                    $money_type = DB::table('setmoney_type')->where('sety_id','9')->value('sety_id','sety_price');//->select();
                    $moneyjc['sem_price'] = $money_type[9];
                    $moneyjc['sem_type'] = 9;
                }
                if ($orderListArr['orli_type'] == 20) {
                    $money_type = DB::table('setmoney_type')->where('sety_id','8')->value('sety_id','sety_price');//->select();
                    $moneyjc['sem_price'] = $money_type[8];
                    $moneyjc['sem_type'] = 8;
                }
            }
            if ($guonian > 11 && $guonian <= 21) {
                $valtype = '121';
            } elseif ($guonian > 21 && $guonian <= 31) {
                $valtype = '122';
            } elseif ($guonian > 31) {
                $valtype = '123';
            }
            $adddata['afs_statues'] = '2';
            $adddata['afs_order'] = $stauasa['order_num'];
            $adddata['afs_serial'] = $stauasa['serial_number'];
            $adddata['afs_sales'] = 1;
            $adddata['afs_paid'] = $valtype??'0';
            $adddata['afs_type'] = $valtype??'0';
            $adddata['afs_granid'] = '120';
            $adddata['afs_pid'] = $stauasa['p_id'];
            $adddata['afs_serid'] = $stauasa['ser_id'];
            $adddata['afs_creactime'] = date('Y-m-d H:i:s');
            $adddata['asf_time'] = date('Y-m-d H:i:s');
            $adddata['afs_day'] = date('Y-m-d');
            $adddata['afs_creacter'] = $admin_acc;
            $adddata['afs_dealer'] = "";
            DB::table("aftersale")->insert($adddata);
            if ($guonian > 5 && $guonian <= 15 && $orderListArr['orli_type'] == 1) {

            } else {
                if ($admins['reward'] == '1') {
                    //DB::table('settlement_money')->insert($moneyjc);
                    //$moneyjc['sem_slid'] = $restSettlementList;
                    //$moneyjc['sem_creacter'] = $admin_acc."(APP)";
                    //$moneyjc['sem_synum'] = $orderListArr['sys_num'];

                    //$sql = "insert into gone_settlement_money (sem_slid,sem_creacter,sem_synum,sem_price,sem_type) values ('".$moneyjc['sem_slid']."','".$moneyjc['sem_creacter']."','".$moneyjc['sem_synum']."',".$moneyjc['sem_price'].",'".$moneyjc['sem_type']."')";
                }
            }
            //if($admins['reward']=='1'){
            $all_price['all_price'] = DB::table('settlement_money')->where('sem_slid',$restSettlementList)->sum('sem_price');
            DB::table('settlement_list')->where('id',$restSettlementList)->update($all_price);
            //}
            //$install_line = M("install_line");
            $install_data['line_serm'] = $orderListArr['serial_number'];
            $install_data['line_sysnum'] = $orderListArr['sys_num'];
            $install_data['line_number'] = $orderListArr['order_num'];
            $install_data['line_status'] = 0;
            $install_data['line_state'] = 1;
            $install_data['line_lasttime'] = date("Y-m-d H:i:s");
            $lins = DB::table('install_line')->insert($install_data);
            // 订单操作时间
            $this->operating_times($orderListArr['serial_number'], '接单时间', date("Y-m-d H:i:s"),$orderListArr['ser_id'], $orderListArr['order_num'],$admin_acc);
            //$this->add_thistory($orderListArr['serial_number'], 'tih_acceptime', date("Y-m-d H:i:s"), '', 2);//添加历史时间
            $temaddtime['acceptance_time']=date("Y-m-d H:i:s");
            $temaddtime['install_id']=$instArr['id'];
            $temaddtime['order_state']=30;
            $this->temaddtime($temaddtime,$orderListArr['serial_number']);
        }
        $shr_phone=DB::table('user')->where('id',$orderListArr['customer_id'])->value('shr_phone');//手机号

        if($restOrderList && $restSettlementList && $lins && $cisis) {

            if(isset($req['daytime'])){
                $executeDayTime=$this->executeDayTime($req,$orderListArr);
                if($executeDayTime['code']!=200){
                    DB::rollback();
                    return response()->json($executeDayTime);
                }
            }
            //$ordestatu=M()->execute("update gone_order_status set st_one=st_one-1,st_two=st_two+1 where st_serid='".$orderListArr['ser_id']."'");
            DB::commit();
            //$this->Json_sendflow($orderListArr['serial_number'], $input['admin_id'], $input['install_id'], $input['admin_id'], $orderListArr['order_num'], $orderListArr['sys_num']);

            //include_once('ApinterfaceAction.class.php');
            //$Api= new ApinterfaceAction();
            //$lidao_interface=$Api->Sales_list($_POST['id']);
            //$ld['ld_orderid']=$_POST['id'];
            //$ld['ld_time']=time();
            //$ld['ld_date']=date("Y-m-d");
            //$ld['ld_type']='0';
            //if($lidao_interface['result']=='true'){
            //	$ld['ld_state']='1';
            //}else{
            //	$ld['ld_state']='2';
            //}
            //M("lidaojk")->add($ld);


            DB::table('management')->where('trace_code', $orderListArr['serial_number'])->update($info);

            if ($returncount <= 1) {
                DB::table('orders')->where('sys_num', $orderListArr['sys_num'])->update($get);
            }
            //*
            $this->probability('1', $orderListArr['ser_id'], $stauas);//计算接单率
            // 日志
            $this->Add_log($orderListArr['ser_id'], $Ip, '派工单(半径)', $is_html, "订单(" . $orderListArr['serial_number'] . ")", $orderListArr['order_num']);

            /*$temp = DB::table('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['admin_acc'],'refusal_id'=>$orderListArr['ser_id'],'category'=>2]);*/
            DB::commit();
            return response()->json(['msg' => '成功', 'code' => 200]);exit;

        }else{
            DB::rollback();
            // 失败
            return response()->json(['msg' => '失败', 'code' => 201]);
            exit;
        }
    }



    /**|*********************************************************************************|
     * @name  半径改单审核
     * @param serial_number  派工单号
     * @param order_num      平台单号
     * @param type           1:商品;2:客户信息;3:客户信息与商品
     * @param shr_name       客户姓名
     * @param shr_phone      客户电话
     * @param shr_sheng      省
     * @param shr_shi        市
     * @param shr_xian       县
     * @param shr_adress     详细地址
     * @param good_id        商品id
     * @param good_name      商品名称
     * @param store_id       门店id
     * @return \Illuminate\Http\JsonResponse
     * @author he  <2020/4/7 10:32>
     *|***********************************************************************************|
     */
    public function edit_order_examine ()
    {
        $req = file_get_contents("php://input");
        $req = json_decode($req, true);
        $Ip = $this->getIp();
        //return response()->json($req);exit;

        //判断参数
        if (empty($req['serial_number']) || empty($req['order_num']) || empty($req['type']) || empty($req['shr_name']) || empty($req['shr_phone']) || empty($req['shr_sheng']) || empty($req['shr_shi']) || empty($req['shr_xian']) || empty($req['shr_adress']) || empty($req['good_id']) || empty($req['good_name']) || empty($req['store_id'])) {
            return response()->json(['code' => '202', 'msg' => '参数错误']);exit;
        }

        //判断工单号
        $orderListArr = DB::table('order_list')->where('order_num', $req['order_num'])->first(['order_num']);
        if (empty($orderListArr)) {
            return response()->json(['code' => '204', 'msg' => '工单号不存在']);exit;
        }

        //判断门店
        $admin_acc = $this->get_admin($req['store_id']);
        if ($admin_acc == 'error') {
            return response()->json(['code' => '206', 'msg' => '门店不存在']);exit;
        }

        //判断商品
        $good_exist = DB::table('pj_goods')->where('pg_id', $req['good_id'])->first();
        if (empty($good_exist)) {
            return response()->json(['code' => '205', 'msg' => '商品不存在']);exit;
        }

        //更换商品
        if ($req['type'] == 1 || $req['type'] == 3) {

            $exist = DB::table('order_replace')->where('deal_state',1)->where('or_serialnum',$req['serial_number'])->orderBy('creact_time','DESC')->limit('1')->first();
            if ($exist) {
                return response()->json(['code' => '207', 'msg' => '该单已申请换货，无需重复申请']);exit;
            }
            $addReplace = DB::table('order_replace')->insert([
                'creact_id' => $req['store_id'],
                'creact_type' => 2,
                'admin_id' => $req['store_id'],
                'creact_name' => $admin_acc,
                'or_num' => $req['order_num'],
                'or_serialnum' => $req['serial_number'],
                'or_goodid' => $req['good_id'],
                'or_goodname' => $req['good_name'],
                'creact_time' => date("Y-m-d H:i:s"),
            ]);
        }


        //更换客户信息
        if ($req['type'] == 2 || $req['type'] == 3) {

            $arr['shr_name']   = $req['shr_name'];//姓名
            $arr['shr_phone']  = $req['shr_phone'];//电话
            $arr['shr_sheng']  = $req['shr_sheng'];//省
            $arr['shr_shi']    = $req['shr_shi'];//市
            $arr['shr_xian']   = $req['shr_xian'];//县
            $arr['shr_adress'] = $req['shr_adress'];//详细地址

            $rest = DB::table('orders')->where('order_num', $req['order_num'])->select('order_num', 'customer_id', 'new_customer_id', 'order_status', 'ser_id','sys_num')->first();
            if ($rest['new_customer_id'] == $rest['customer_id']) {
                $addUserId = DB::table('user')->insertGetId($arr);
                $att['new_customer_id'] = $addUserId;
                $chos = DB::table('orders')->where('order_num', $req['order_num'])->update($att);
            } else {
                $chos = DB::table('user')->where('id', $rest['new_customer_id'])->update($arr);
                $addUserId = $rest['new_customer_id'];
            }
            if (!empty($chos)) {
                if ($rest['order_status'] > 10) {
                    $poss['customer_phone'] = $arr['shr_phone'];
                    $poss['customer_id'] = $addUserId;
                    $upOrderList = DB::table('order_list')->where('order_num', $req['order_num'])->update($poss);
                }
                $content = $rest['order_num'] . "订单，地址";
                $this->inserting_log('(半径)编辑地址，', $rest['sys_num'], $content, '订单管理', $Ip, $admin_acc);//日志
                return response()->json(['msg' => '成功', 'code' => 200]);
                exit;
            } else {
                return response()->json(['msg' => '失败', 'code' => 201]);
                exit;
            }

        }

        if ($req['type'] == 1) {
            if (isset($addReplace) && !empty($addReplace)) {
                return response()->json(['msg' => '成功', 'code' => 200]);
                exit;
            } else {
                return response()->json(['msg' => '失败', 'code' => 201]);
                exit;
            }
        } elseif ($req['type'] == 2) {
            if (isset($upOrderList) && !empty($upOrderList)) {
                return response()->json(['msg' => '成功', 'code' => 200]);
                exit;
            } else {
                return response()->json(['msg' => '失败', 'code' => 201]);
                exit;
            }
        } elseif ($req['type'] == 3) {
            if ((isset($upOrderList) && !empty($upOrderList)) && (isset($addReplace) && !empty($addReplace))) {
                return response()->json(['msg' => '成功', 'code' => 200]);
                exit;
            } else {
                return response()->json(['msg' => '失败', 'code' => 201]);
                exit;
            }
        }
    }



    /**|*********************************************************************************|
     * @name  同步技师状态(抵达、作业、完成)
     * @param serial_number 派工单号
     * @param install_id    门店技师id
     * @param line_state    技师状态 2:出发;3:抵达;5:完成
     * @param longitude     经度
     * @param latitude      纬度
     * @param feedback(array)[type,url] 图片信息（完成时必传）
     * @return \Illuminate\Http\JsonResponse
     * @author he  <2020/4/7 15:36>
     *|***********************************************************************************|
     */
    public function sync_technician_status ()
    {
        $req = file_get_contents("php://input");
        $req = json_decode($req, true);
        $Ip = $this->getIp();


        //检测参数
        if (empty($req['serial_number']) || empty($req['line_state']) || empty($req['longitude']) || empty($req['latitude']) || empty($req['install_id'])) {
            return response()->json(['msg' => '参数错误', 'code' => 202]);
            exit;
        }

        //判断技师
        $bindInstall = $this->check_install_person($req['install_id']);
        if ($bindInstall == 'error') {
            return response()->json(['msg' => '没有匹配的技师', 'code' => 211]);
            exit;
        }
        //判断line_state类型
        if (!in_array($req['line_state'], [2,3,5])) {
            return response()->json(['msg' => '类型错误', 'code' => 207]);
            exit;
        }

        //判断图片
        if ($req['line_state'] == 5) {
            if (empty($req['feedback'])) {
                return response()->json(['msg' => '图片信息不能为空', 'code' => 205]);
                exit;
            }
            foreach ($req['feedback'] as $k => $v) {
                if (!isset($v['type']) || isset($v['url'])) {
                    return response()->json(['msg' => '图片格式错误', 'code' => 209]);
                    exit;
                }
                if (!in_array($v['type'], [1,2,3,4,5,6,7])) {
                    return response()->json(['msg' => '图片type类型错误', 'code' => 210]);
                    exit;
                }
            }
        }

        $insLine = DB::table('install_line')->where(['line_serm'=>$req['serial_number']])->first();
        if($insLine['line_status'] == 1){
            return response()->json(['msg'=>"该订单已终止，无法操作",'code'=>211]);exit;
        }

        $chkOrder = DB::table('order_list')->where(['serial_number'=>$req['serial_number']])->first();

        DB::beginTransaction(); //开启事务
        if ($chkOrder) {

            if ($req['line_state'] == 5) {
                $adminArr = DB::table('admin')->where('id', $chkOrder['ser_id'])->first(['id','company_name']);
                $uploadPic = $this->add_feedback_pic($req['feedback'], $chkOrder['id'], $bindInstall['install_name'], $bindInstall['install_phone'], $adminArr['id'], $adminArr['company_name']);
                if ($uploadPic != 1) {
                    DB::rollBack();
                    return response()->json(['msg'=>"图片上传失败",'code'=>233]);exit;
                }
            }
            $addLineGetId = DB::table('install_line')->insertGetId([
                'line_serm' => $req['serial_number'],
                'line_sysnum' => $chkOrder['sys_num'],
                'line_number' => $chkOrder['order_num'],
                'line_state'  => $req['line_state'],
                'line_lasttime' => date('Y-m-d H:i:s')
            ]);


            $newAddLine = DB::table('install_line')->where('id', $addLineGetId)->first();

            if($newAddLine){
                $line = $req['latitude'] . ','. $req['longitude'];
                $data['line_dynamic'] = $line;
                switch($req['line_state']){
                    case 2:
                        $data['line_start'] = $line;
                        $title = '出发时间';
                        break;
                    case 3:
                        $data['line_arrive'] = $line;
                        $title = '抵达时间';
                        break;
                    case 4:
                        $data['line_task'] = $line;
                        $title = '作业时间';
                        break;
                    case 5:
                        $data['line_end'] = $line;
                        $title = '任务反馈时间';
                        break;
                }

                $endUpInsLine = DB::table('install_line')->where('line_serm',$req['serial_number'])->update($data);

                if ($endUpInsLine) {
                    $this->operating_times($req['serial_number'],$title,date("Y-m-d H-i-s"),$chkOrder['ser_id'],$chkOrder['order_num'],$adminArr['company_name']);//$bindInstall['install_name'].'('.$bindInstall['check_code'].')'

                    //$this->Add_log($input['admin_id'],$input['dediips'],'派工单(App)',$title,"订单(".$input['serm'].")",$info['line_number']);

                    DB::commit();
                    return response()->json(['msg'=>"成功",'code'=>200]);exit;

                }

            }else{
                DB::rollBack();
                return response()->json(['msg'=>"回传失败",'code'=>201]);exit;
            }
        } else {
            DB::rollBack();
            return response()->json(['msg'=>"单号不存在",'code'=>204]);exit;
        }

    }



    /**|*********************************************************************************|
     * @name  绑定门店同步
     * @param ser_id 速电门店id
     * @param type   门店类型：1:补货; 2:派单门店
     * @param state  数据状态  1:添加; 2:删除
     * @return \Illuminate\Http\JsonResponse
     * @author he  <2020/4/11 11:36>
     *|***********************************************************************************|
     */
    public function sync_binding_stores ()
    {
        $req = file_get_contents("php://input");
        $req = json_decode($req, true);

        $Ip = $this->getIp();
        if (empty($req['ser_id']) || empty($req['type']) || empty($req['state'])) {
            return response()->json(['msg' => '参数错误', 'code' => 202]);
            exit;
        }

        //查询数据是否存在
        $exists = DB::table('sync_stores')->where('ser_id', $req['ser_id'])->where('type', $req['type'])->where('is_delete', 1)->exists();
        //dd($exists);
        //添加，如果数据存在，返回结果
        if ($req['state'] == 1) {
            if ($exists) {
                return response()->json(['msg' => '该门店已绑定', 'code' => 205]);
                exit;
            }
            //删除，如果数据不存在，返回结果
        } elseif ($req['state'] == 2) {
            if (!$exists) {
                return response()->json(['msg' => '未找到数据', 'code' => 206]);
                exit;
            }
        }


        if ($req['state'] == 1) { //添加
            $endRes = DB::table('sync_stores')->insert([
                'ser_id'      => $req['ser_id'],
                'type'        => $req['type'],
                'update_time' => date("Y-m-d H:i:s"),
                'is_delete'   => 1
            ]);
        } elseif ($req['state'] == 2) { //删除
            $endRes = DB::table('sync_stores')->where('ser_id', $req['ser_id'])->where('type', $req['type'])->update([
                'update_time' => date("Y-m-d H:i:s"),
                'is_delete'   => 2
            ]);
        }

        if ($endRes) {
            return response()->json(['msg' => '成功', 'code' => 200]);
            exit;
        } else {
            return response()->json(['msg' => '失败', 'code' => 201]);
            exit;
        }



    }



    /**|*********************************************************************************|
     * @name  获取标签
     * @param type  1:拒单标签 2:催单反馈标签
     * @return \Illuminate\Http\JsonResponse
     * @author he  <2020/4/14 14:11>
     *|***********************************************************************************|
     */
    public function get_label ()
    {
        $req = file_get_contents("php://input");
        $req = json_decode($req, true);

        //$Ip = $this->getIp();
        if (empty($req['type']) || in_array($req['type'], [1, 2])) {
            return response()->json(['msg' => '参数错误', 'code' => 202]);
            exit;
        }
        if ($req['type'] == 1) {
            $list = DB::table('setmoney_type')->whereRaw("FIND_IN_SET ('2',lt_group)")->where('lt_parent_id','25')->select('sety_id as lable_id','sety_name as lable_name')->get()->toArray();
        } elseif ($req['type'] == 2) {
            $list = DB::table('setmoney_type')->whereRaw("lt_parent_id=79 and FIND_IN_SET('2',lt_group)")->select('sety_id as lable_id','sety_name as lable_name')->get()->toArray();
        }

        if ($list && $list != []) {
            return response()->json(['data'=> $list, 'msg' => '成功', 'code' => 200]);
            exit;
        } else {
            return response()->json(['data'=> $list, 'msg' => '失败', 'code' => 201]);
            exit;
        }
    }


    /**|*********************************************************************************|
     * @name  门店审核 未完成
     * @param type   1:通过; 2:驳回
     * @param store_id 门店id
     * @return \Illuminate\Http\JsonResponse
     * @author he  <2020/4/14 18:00>
     *|***********************************************************************************|
     */
    public function radius_examine ()
    {
        $req = file_get_contents("php://input");
        $req = json_decode($req, true);
        //$Ip = $this->getIp();

        if (empty($req['platform_number']) || empty($req['type']) || empty($req['store_id'])) {
            return response()->json(['msg' => '参数错误', 'code' => 202]);
            exit;
        }

        if ($req['type'] == 1) {
            return response()->json(['msg' => '成功', 'code' => 200]);
            exit;
        } elseif ($req['type'] == 2) {

        }
    }



    /**|*********************************************************************************|
     * @name  添加反馈图片
     * @param $feedback
     * @param $order_id
     * @param $install_name
     * @param $install_phone
     * @param $admin_id
     * @param $company_name
     * @return \Illuminate\Http\JsonResponse
     * @author he  <2020/4/7 17:38>
     *|***********************************************************************************|
     */
    private function add_feedback_pic ($feedback, $order_id, $install_name, $install_phone, $admin_id, $company_name)
    {
        if (empty($feedback) || empty($order_id) || empty($install_name) || empty($install_phone) || empty($admin_id) || empty($company_name)) {
            return 3;
        }

        $addUrl = [];
        foreach ($feedback as $k => $v) {

            $addUrl[$k]['type']            = $v['type'];
            $addUrl[$k]['gl_id']           = $order_id;
            $addUrl[$k]['install_name']    = $install_name;
            $addUrl[$k]['install_phone']   = $install_phone;
            $addUrl[$k]['admin_id']        = $admin_id;
            $addUrl[$k]['company_name']    = $company_name;
            $addUrl[$k]['feedback_status'] = '2';
            $addUrl[$k]['sys_num']         = 'rwfk' . $order_id;
            $addUrl[$k]['is_type']         = 3;
            $addUrl[$k]['type']            = $v['type'];
            $addUrl[$k]['install_remark']  = 1;
            $addUrl[$k]['feedback_pic']    = $v['url'];
            /*DB::table('feedback')->insert([
                'type'            => $v['type'],
                'gl_id'           => $order_id,
                'install_name'    => $install_name,
                'install_phone'   => $install_phone,
                'install_time'    => date("Y-m-d H:i:s"),
                'admin_id'        => $admin_id,
                'company_name'    => $company_name,
                'feedback_status' => '2',
                'sys_num'         => 'rwfk' . $order_id,
                'is_type'         => 3,
                'install_remark'  => '1',
                'feedback_pic'    => $v['url']
            ]);*/
        }
        $addFeedBack = DB::table('feedback')->insert($addUrl);
        if ($addFeedBack) {
            return 1;
        } else {
            return 2;
        }
    }


    /**|*********************************************************************************|
     * @name  获取服务商名称
     * @param $admin  服务商id
     * @return \Illuminate\Http\JsonResponse
     * @author he  <2020/4/7 15:34>
     *|***********************************************************************************|
     */
    private function get_admin ($admin)
    {
        $admin_acc = DB::table('admin')->where('id', $admin)->value('admin_acc');
        if ($admin_acc) {
            return $admin_acc;
        } else {
            return 'error';
        }
    }



    private function check_install_person ($install_id)
    {
        $bindInstall = DB::table('install_person')->where('id', $install_id)->first(['bind_id', 'install_name','install_phone']);
        if (empty($bindInstall)) {
            return 'error';
        }
        return $bindInstall;
    }

    private function Add_log($ids,$ips,$function_name,$type,$content,$order_num){
        //DB::connection()->enableQueryLog();
        $admin=DB::table('admin')->where('id',$ids)->select('admin_acc')->first();
        //print_r(DB::getQueryLog());
        $data['czrz_name']=$admin['admin_acc']; //登录者
        if($ips){
            $data['czrz_ip']=$ips; //操作ip
        }
        $data['czrz_czsj'] = date("Y-m-d H:i:s");//创建时间
        $data['czrz_czlx'] = $type;//创建类型
        $data['czrz_number'] = $order_num;//平台单号
        $data['czrz_czxq'] = $content;//操作内容
        $data['test_data'] = $function_name;//操作模块名称
        $res = DB::table('czrz')->insert($data);
        return $res;

    }


    /**
     * @name 计算接单率
     * @type 1:接单；2：拒单
     * @ser_id 服务商id
     * @stauas 订单状态 10：未接单；30：已接单
     */
    public function probability ($type,$ser_id,$stauas){
        //$probability=M("probability");
        $res=DB::table('probability')->where('prb_sid',$ser_id)->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;
                }
            }
            DB::table('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->add($poss);
            DB::table('probability')->insert($poss);
        }
    }



    /**|*********************************************************************************|
     * @name  获取ip
     * @param null
     * @return \Illuminate\Http\JsonResponse
     * @author he  <2020/4/6 15:01>
     *|***********************************************************************************|
     */
    public function getIp ()
    {
        if(!empty($_SERVER["HTTP_CLIENT_IP"])){
            $cip = $_SERVER["HTTP_CLIENT_IP"];
        }
        elseif(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
            $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
        }
        elseif(!empty($_SERVER["REMOTE_ADDR"])){
            $cip = $_SERVER["REMOTE_ADDR"];
        }
        else{
            $cip = "无法获取！";
        }
        return $cip;
    }



    /**|-----------------------------------------------------------------------------------
     * @name 订单锁定 （动作）
     * @param sys_num 系统单号
     * @param order_num 平台单号
     * @param p_id 平台id
     * @param note_content 备注内容
     * @return json
     * @author he <2019-04-02>
     * |-----------------------------------------------------------------------------------
     */
    public function lockOrder(Request $request)
    {
        return response()->json(['msg' => '操作成功', 'code' => 200]);
        $req = file_get_contents("php://input");
        $req = json_decode($req, true);

        if (!$req['serial_num']) {
            return response()->json(['msg' => '参数错误', 'code' => 203]);
            exit;
        }


        $input = DB::table('order_list')->where('serial_number',$req['serial_num'])->select('p_id','sys_num','order_num')->first();
        //$input = $request->only('sys_num', 'order_num', 'p_id', 'note_type', 'note_content');
        $submit_stauas = DB::table('submit_please')->where('submit_sys_num', $input['sys_num'])->orderBy('id', 'DESC')->value('submit_stauas');
        if ($submit_stauas == 1) {
            return response()->json(['msg' => '该单售后差额在申请中，请核实', 'code' => 206]);
            exit;
        }
        $restSelist = DB::table('settlement_list')->where('sys_num', $input['sys_num'])->get()->toArray();
        $restSethree = DB::table('settlement_three')->where('sys_num', $input['sys_num'])->get()->toArray();
        if ($restSelist) {
            foreach ($restSelist as $k => $v) {
                if ($v['sett_status'] == 20 || $v['sett_status'] == 65 || $v['sett_status'] == 10) {
                    return response()->json(['msg' => '该单金额在结算中', 'ErrorCode' => 207]);
                    exit;
                }
            }
        }
        if ($restSethree) {
            // 该单金额在收款中
            foreach ($restSethree as $kk => $vv) {
                if ($vv['three_status'] == 20) {
                    return response()->json(['msg' => '该单金额在收款中', 'code' => 205]);
                    exit;
                }
            }
        }
        //$ser_id=$order->where("`sys_num`='".$sys_num."'")->field("ser_id,order_num,order_status")->find();
        $ser_id = DB::table('orders')->where('sys_num', $input['sys_num'])->select('ser_id', 'order_num', 'order_status')->first();
        if ($ser_id['ser_id'] == "617") {
            $url = 'http://order.autocamel.com/api/order.htm';//正式
            $luot['orderid'] = $ser_id['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_post($url, $ParArray);
            $obj = json_decode($resp, true);
            if ($obj['biz']['data']['status'] == 0 || $obj['biz']['data']['rmk'] = "订单正在配送中,取消待定,需回调通知或主动轮询查询确认") {
                $poss['le_error'] = $ParArray;
                $poss['le_ltero'] = $resp;
                $poss['le_number'] = $ser_id['order_num'];
                DB::table('luotuo_error')->insert($poss);
            } else {
                $poss['le_error'] = $ParArray;
                $poss['le_ltero'] = $resp;
                $poss['le_number'] = $ser_id['order_num'];
                DB::table('luotuo_error')->insert($poss);
                return response()->json(['msg' => '通知骆驼失败！', 'code' => 7]);
                exit;
            }
        }
        $orderArr['lock_type'] = 2;
        $orderListArr['locklist_type'] = 2;
        $orderSettArr['locksel_type'] = 2;
        $orderSetteArr['locksee_type'] = 2;


        $returnSettlementList = DB::table('settlement_list')->where('sys_num', $input['sys_num'])->update($orderSettArr);
        $returnOrder = DB::table('orders')->where('sys_num', $input['sys_num'])->update($orderArr);
        $returnOrderList = DB::table('order_list')->where('sys_num', $input['sys_num'])->update($orderListArr);
        $returnSettlementThree = DB::table('settlement_three')->where('sys_num', $input['sys_num'])->update($orderSetteArr);


        $rest = $this->acc_me($input['sys_num'], '订单管理', "锁定（半径锁定订单）", '', '', 1, "半径", 0);

        //$repealData['orderid'] = $ser_id['id'];//订单id
        //$repealData['lock_user'] = $request->get('id')['id']; //session('id');//锁定操作人
        //$repealData['lock_time'] = date('Y-m-d H:i:s');//锁定时间
        /* if ($ser_id['order_status']<=20) {
            $repealData['isneed'] = 2;//是否需要处理，1需要2不需要
        }else{
            $repealData['isneed'] = 1;
        }

        $repealData['isdeal'] = 2;//未处理
        $repealwhere['orderid'] = $ser_id['id'];
        $find_repeal = RepealRecord::where('orderid',$ser_id['id'])->select('id')->first();

        if ($find_repeal) {
            RepealRecord::where($repealwhere)->update($repealData);
        }else{
            RepealRecord::insert($repealData);
        }*/
        if ($rest == 1) {

            $this->inserting_log('锁定，', $input['sys_num'], "订单" . $input['sys_num'], '订单管理', $this->getIp(), "半径");//日志
            return response()->json(['msg' => '操作成功', 'code' => 200]);
            exit;
        } else {
            return response()->json(['msg' => '操作失败', 'code' => 202]);
            exit;
        }
    }


    /**|---------------------------------------------------------------------------------
     * @name   恢复
     * @param  serial_num  派工单号
     * @return \Illuminate\Http\JsonResponse
     * @author he <2020/6/9 15:06>
     *|---------------------------------------------------------------------------------
     */
    public function undoIve ()
    {
        return response()->json(['msg' => '操作成功', 'code' => 200]);
        $req = file_get_contents("php://input");
        $req = json_decode($req, true);

        if (!$req['serial_num']) {
            return response()->json(['msg' => '参数错误', 'code' => 203]);
            exit;
        }

        $Input = DB::table('order_list')->where('serial_number',$req['serial_num'])->select('p_id','sys_num','order_num')->first();
        //$Input = $request->only('type', 'sys_num', 'order_num', 'p_id');

        $order_find = DB::table('orders')->where('sys_num', $Input['sys_num'])->select('order_status', 'id')->first();
        $order_status = $order_find['order_status'];
        $orderArr['lock_type'] = 1;
        $orderListArr['locklist_type'] = 1;
        $orderSettArr['locksel_type'] = 1;
        $orderSetteArr['locksee_type'] = 1;
        try {
            DB::beginTransaction();
            $a = DB::table('settlement_list')->where('sys_num', $Input['sys_num'])->update($orderSettArr);
            $b = DB::table('orders')->where('sys_num', $Input['sys_num'])->update($orderArr);
            $c = DB::table('order_list')->where('sys_num', $Input['sys_num'])->update($orderListArr);
            $d = DB::table('settlement_three')->where('sys_num', $Input['sys_num'])->update($orderSetteArr);
            if ($b) {

                //恢复改已驳回2019/10/8
                DB::table('refund')->where('order_num', $Input['order_num'])->update(['state' => 5]);
                $content = "恢复订单" . $Input['sys_num'];
                $this->inserting_log('恢复，', $Input['sys_num'], $content, '订单管理', $this->getIp(), "半径");
                DB::commit();
                return response()->json(['code' => 200, 'msg' => '操作成功']);
                exit;
            } else {
                DB::rollback();
                return response()->json(['code' => 202, 'msg' => '操作失败']);
                exit;
            }
        } catch (Exception $e) {
            DB::rollback();
            return response()->json(['code' => 204, 'msg' => $e->getMessage()]);
            exit;
        }
    }


    /**|---------------------------------------------------------------------------------
     * @name  门店接单 （同步接单技师）
     * @param  serial_num   工单号
     * @param  install_id   技师id
     * @return \Illuminate\Http\JsonResponse
     * @author he <2020/6/11 9:17>
     *|---------------------------------------------------------------------------------
     */
    public function syncDispatchInstall (Request $request)
    {
        $req = file_get_contents("php://input");
        $req = json_decode($req, true);

        if (!$req['serial_num'] || !$req['bind_id']) {
            return response()->json(['msg' => '参数错误', 'code' => 203]);
            exit;
        }

        $instArr = DB::table('install_person')->where('bind_id', $req['bind_id'])->select('install_name','install_phone','id')->first();
        $orderListArr = DB::table('order_list')->where('serial_number', $req['serial_num'])->select('order_num','id')->first();

        try {
            DB::beginTransaction();
            $restOrder = DB::table('orders')->where('order_num', $orderListArr['order_num'])->update([
                'intall_person' => $instArr['install_name'],
                'intall_phone'  => $instArr['install_phone']
            ]);

            $restOrderList = DB::table('order_list')->where('serial_number',$req['serial_num'])->update([
                'install_id'    => $instArr['id'],
                'intall_person' => $instArr['install_name'],
                'intall_phone'  => $instArr['install_phone'],
            ]);

            $restSettlement = DB::table('settlement_list')->where('list_id', $req['serial_num'])->update([
                'installperson' => $instArr['id'],
                'intall_person' => $instArr['install_name'],
                'intall_phone'  => $instArr['install_phone'],
            ]);

            if ($restOrder && $restOrderList) {
                DB::commit();
                return response()->json(['msg' => 'success', 'code' => 200]);
                exit;
            } else {
                DB::rollBack();
                return response()->json(['msg' => 'error', 'code' => 201]);
                exit;
            }
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json(['msg' => $e->getMessage(), 'code' => 201]);
            exit;
        }

    }
    /**********************************门店对接接口（dou）*******************************************************/
    /**|---------------------------------------------------------------------------------
     * @name 预约安装时间
     * @param daytime 预约时间
     * @param serial_number 工单单号
     * @param ip 访问ip
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/14 20:24>
     * |---------------------------------------------------------------------------------
     */
    public function addDayTime(Request $request){
        $input = json_decode(file_get_contents("php://input"), true);
        //dump($req);
        if(!$this->validationKey($input,['serial_number','daytime','ip'])){
            return response()->json(['msg' => '参数错误s', 'code' => 202]);
        }
        $orderlist=$this->checkSerialNumber($input['serial_number']);
        if(!$orderlist){
            return response()->json(['msg' => '单号不存在', 'code' => 201]);
            exit;
        }
        $executeDayTime=$this->executeDayTime($input,$orderlist);
        return response()->json($executeDayTime);
        return;
    }
    /**|---------------------------------------------------------------------------------
     * @name 添加预约时间执行方法
     * @param $input 请求参数
     * @param $orderlist 工单信息
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/14 20:24>
     * |---------------------------------------------------------------------------------
     */
    public function executeDayTime ( $input,$orderlist){
        $data['day_time']=$input['daytime'];
        $res=DB::table('order_list')->where('serial_number',$input['serial_number'])->update($data);
        DB::table('orders')->where('sys_num',$orderlist['sys_num'])->update($data);
        $yyaz_time=DB::table('order_time')->where('serial_number',$input['serial_number'])->where('is_type','安装预约时间')->orderBy('id','DESC')->value('create_time');//获取奖罚起始时间
        $company_name= DB::table('admin')->where('id', $orderlist['ser_id'])->select('admin_acc','reward')->first();
        $admin_acc = $company_name['admin_acc'];
        if(!$yyaz_time){
            $this->operating_times($orderlist['serial_number'],'安装预约时间',date('Y-m-d H:i:s'),$orderlist['ser_id'],$orderlist['order_num'],$admin_acc);
        }
        if($res){
            $settlement_list=DB::table('settlement_list')->where('list_id',$orderlist['serial_number'])->value('id');
            $settlement_money=DB::table('settlement_money')->where('sem_slid',$settlement_list)->where('sem_type','17')->value('sem_id');
            $payout_time=DB::table('order_time')->where("serial_number",$orderlist['serial_number'])->where("is_type",'接单时间')->orderBy('id','DESC')->value('create_time');//获取奖罚起始时间
            $money_type=DB::table('setmoney_type')->where("sety_id","17")->value("sety_price");//->select();
            $zero1=time();//strtotime (date("Y-m-d H:i:s")); //当前时间  ,注意H 是24小时 h是12小时
            $zero2=strtotime ($payout_time);  //过年时间，不能写2014-1-21 24:00:00  这样不对
            $guonian=($zero1-$zero2)/60; //60s*60min*24h
            $rulesout=$this->rulesout();
            if(!in_array($orderlist['p_id'],$rulesout)){
                if(!empty($settlement_money)){
                    if($guonian<=17 && $company_name['reward']=='1'){
                        $money['sem_slid']=$settlement_list;
                        $money['sem_synum']=$orderlist['sys_num'];
                        $money['sem_creacter']=$company_name['admin_acc'];
                        $money['sem_price']=$money_type;
                        $money['sem_type']=17;
                        DB::table('settlement_money')->insert($money);
                        $all_price['all_price']=DB::table('settlement_money')->where("sem_slid",$settlement_list)->SUM('sem_price');
                        DB::table('settlement_list')->where("id",$settlement_list)->update($all_price);
                    }
                }
            }
            $this->AddLog($orderlist['ser_id'],$input['ip'],'门店同步','预约安装'.$input['daytime'],"订单(".$orderlist['serial_number'].")",$orderlist['sys_num'],$admin_acc);
            return array('msg' => '操作成功', 'code' => 200);
            exit;
        }else{
            return array('msg' => '操作失败', 'code' => 201);
            exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 技师操作记录
     * @param serial_number 工单单号
     * @param ip 访问ip
     * @param state 操作状态
     * @param line 操作坐标
     * @param filePic 图片路径 file1,file2,file3,file4,file5,file2
     * @param install_name 技师姓名
     * @param install_phone 技师电话
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/15 19:28>
     * |---------------------------------------------------------------------------------
     */
    public function installLine(Request $request){
        $input = json_decode(file_get_contents("php://input"), true);
        //dump($req);
        if($input['state']=='5'){
            if(!$this->validationKey($input,['filePic'])){
                return response()->json(['msg' => '参数错误', 'code' => 202]);
            }
        }
        if(!$this->validationKey($input,['serial_number', 'ip','state','install_name','install_phone'])){
            return response()->json(['msg' => '参数错误', 'code' => 202]);
        }
        $check_number=$this->checkSerialNumber($input['serial_number']);
        if(!$check_number){
            return response()->json(['msg' => '单号不存在', 'code' => 204]);
            exit;
        }
        if($check_number['stauas']>30){
            return response()->json(['msg' => '工单状态错误', 'code' => 203]);
            exit;
        }
        $serm = $input['serial_number'];
        $state = $input['state'];
        $line = $input['line']??"0,0";
        if(empty($input['app_achieve_time'])){
            $feedtime=date("Y-m-d H:i:s");
        }else{
            $feedtime=$input['app_achieve_time'];
        }
        $info = DB::table('install_line')->where('line_serm',$input['serial_number'])->value('id');
        if(empty($info)){
            $lines['line_serm'] = $serm;
            $lines['line_sysnum'] = $check_number['sys_num'];
            $lines['line_number'] = $check_number['order_num'];
            $lines['line_state'] = $state;
            $lines['line_lasttime'] = date('Y-m-d H:i:s');
            $info = DB::table('install_line')->insert($lines);
        }
        if(!empty($info)){
            $data['line_lasttime'] = date('Y-m-d H:i:s');
            $data['line_state'] = $state;
            $data['line_dynamic'] = $line;
            $reir=1;
            $a2=1;
            $a1=1;
            switch($state){
                case 2:
                    $data['line_start'] = $line;
                    $title = '出发时间';
                    $temaddtime['start_time']=date("Y-m-d H:i:s");
                    break;
                case 3:
                    $data['line_arrive'] = $line;
                    $title = '抵达时间';
                    $temaddtime['arrive_time']=date("Y-m-d H:i:s");
                    if($check_number['p_id']=='131'){
                        $this->store_syn($check_number['order_num'],$check_number['ser_id'],'number',$check_number['serial_number'],'');
                    }
                    break;
                case 4:
                    $data['line_task'] = $line;
                    $title = '作业时间';
                    $temaddtime['task_time']=date("Y-m-d H:i:s");
                    break;
                case 5:
                    $stauas=DB::table("order_list")->where("serial_number",$check_number['serial_number'])->value("stauas");
                    if($stauas!=30){
                        return response()->json(['msg' => '工单状态错误', 'code' => 201]);
                        exit;
                    }
                    $data['line_end'] = $line;
                    $title = '任务反馈时间';
                    $temaddtime['end_time']=$feedtime;
                    $temaddtime['order_state']=34;
                    $rea=$this->storeUpload($input['filePic'],$check_number,$input['install_name'],$input['install_phone']);
                    if(empty($rea)){
                        return response()->json(['msg' => '操作失败', 'code' => 201]);
                    }
                    $company_name= DB::table('admin')->where('id', $check_number['ser_id'])->select('admin_acc','reward')->first();
                    $settlement_list=DB::table('settlement_list')->where('list_id',$check_number['serial_number'])->value('id');
                    $yy_time=DB::table('order_time')->where("serial_number",$check_number['serial_number'])->where("is_type",'安装预约时间')->orderBy('id','DESC')->value('create_time');//获取奖罚起始时间
                    $payout_time=DB::table('order_time')->where("serial_number",$check_number['serial_number'])->where("is_type",'接单时间')->orderBy('id','DESC')->value('create_time');//获取奖罚起始时间
                    $money_type=DB::table('setmoney_type')->where("sety_id","18")->value("sety_price");//->select();
                    $time1=strtotime($check_number['create_time']);
                    $zero2=strtotime ($payout_time);  //过年时间，不能写2014-1-21 24:00:00  这样不对
//                    $points=2;
                    if($yy_time){
                        $zero3=strtotime ($yy_time);  //过年时间，不能写2014-1-21 24:00:00  这样不对
                        $yyaz=($zero3-$zero2)/60; //60s*60min*24h
                        if($yyaz>10){
//                            $points=1;
                        }
                        if($yyaz>17){
                            $flag=1;
                        }else{
                            $flag=2;
                        }
                    }else{
//                        $points=1;
                        $flag=1;
                    }
                    $rulesout=$this->rulesout();
                    if(!in_array($check_number['p_id'],$rulesout)){
                        if($flag=='1' && $company_name['reward']=='1'){
                            $money['sem_slid']=$settlement_list;
                            $money['sem_synum']=$check_number['sys_num'];
                            $money['sem_creacter']=$company_name['admin_acc'];
                            $money['sem_price']=$money_type;
                            $money['sem_type']=18;
                            DB::table('settlement_money')->insert($money);
                            $all_price['all_price']=DB::table('settlement_money')->where("sem_slid",$settlement_list)->SUM('sem_price');
                            DB::table('settlement_list')->where("id",$settlement_list)->update($all_price);
                        }
                        $res=DB::table('settlement_money')->where("sem_slid",$settlement_list)->where("sem_type","15")->value("sem_type");
                        if(!$res){
                            $zero1=strtotime ($feedtime); //当前时间  ,注意H 是24小时 h是12小时
                            $guonian=($zero1-$time1)/60; //60s*60min*24h
                            if($company_name['reward']=='1'){
                                $money_type=DB::table('setmoney_type')->where("sety_id","7")->value("sety_price");
                                $Install_money=str_replace('，',',',$money_type);
                                $Install_money=explode(',',$Install_money);
                                $money['sem_slid']=$settlement_list;
                                $money['sem_synum']=$check_number['sys_num'];
                                $money['sem_creacter']=$company_name['admin_acc'];
                                $money['sem_type']=7;
                                if($guonian<=41){
                                    $money['sem_price']=$Install_money[0];
                                    DB::table('settlement_money')->insert($money);
                                    $all_price['all_price']=DB::table('settlement_money')->where("sem_slid",$settlement_list)->SUM('sem_price');
                                    DB::table('settlement_list')->where("id",$settlement_list)->update($all_price);
                                }if($guonian>41 && $guonian<=61){
                                    $money['sem_price']=$Install_money[1];
                                    DB::table('settlement_money')->insert($money);
                                    $all_price['all_price']=DB::table('settlement_money')->where("sem_slid",$settlement_list)->SUM('sem_price');
                                    DB::table('settlement_list')->where("id",$settlement_list)->update($all_price);
                                }if($guonian>61 && $guonian<=91){
                                    $money['sem_price']=$Install_money[2];
                                    DB::table('settlement_money')->insert($money);
                                    $all_price['all_price']=DB::table('settlement_money')->where("sem_slid",$settlement_list)->SUM('sem_price');
                                    DB::table('settlement_list')->where("id",$settlement_list)->update($all_price);
                                }
                            }
                        }
                    }
                    $post['stauas']=34;//待完成
                    $post['feeds_time']=$feedtime;//商家提交安装单时间
                    $reir=DB::table("order_list")->where("serial_number",$check_number['serial_number'])->update($post);
                    $lemeArr['list_service_type']='34';//待完成
                    $lemeArr['setfeeds_time']=$feedtime;//待完成
                    $a2 = DB::table("settlement_list")->where("list_id",$check_number['serial_number'])->update($lemeArr);
                    $OrderCount=DB::table("order_list")->whereRaw("`sys_num`='".$check_number['sys_num']."' AND `stauas`=34 AND `after_stauas`!=1 AND `goods_service` NOT IN (2,3) AND `is_delete`=1")->count();
                    if($OrderCount==1){
                        $orderArr['order_status']='34';//待完成
                        $a1 = DB::table("orders")->where("sys_num",$check_number['sys_num'])->update($orderArr);
                    }
                    if($check_number['p_id']=='131'){
                        $this->store_syn($check_number['order_num'],$check_number['ser_id'],'state',$check_number['serial_number'],'34');
                    }
                    break;
            }
            DB::beginTransaction(); //开启事务
            $check = DB::table('install_line')->where('line_serm',$input['serial_number'])->update($data);
            if(!empty($check) && !empty($reir) && !empty($a2) && !empty($a1)){
                DB::commit();
                $this->operating_times($input['serial_number'],$title,$feedtime,$check_number['ser_id'],$check_number['order_num'],'');
                $this->temaddtime($temaddtime,$input['serial_number']);
                $this->AddLog($check_number['ser_id'],$input['ip'],'门店同步',$title,"订单(".$serm.")",$check_number['sys_num'],'');
                return response()->json(['msg' => '操作成功', 'code' => 200]);
                exit;
            }else{
                DB::rollBack();
                return response()->json(['msg' => '操作失败', 'code' => 201]);
                exit;
            }
        }else{
            return response()->json(['msg' => '操作失败', 'code' => 201]);
            exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 保存图片信息
     * @param $file 图片信息
     * @param $ser 服务商信息
     * @param $install_name 技师姓名
     * @param $install_phone 技师电话
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/15 22:19>
     * |---------------------------------------------------------------------------------
     */
    public function storeUpload($file,$ser,$install_name,$install_phone){
        $arr=array();
        $company_name = DB::table('admin')->where('id', $ser['ser_id'])->value('company_name');
        foreach ($file as $k=> $v){
            if(!empty($v)){
                $arr[$k]['type']=10086;//类型
                $arr[$k]['gl_id']=$ser['id'];//关联派工单id
                $arr[$k]['install_name']=$install_name;//安装人员姓名
                $arr[$k]['install_phone']=$install_phone;//安装人员电话
                $arr[$k]['install_time']=date("Y-m-d H:i:s");//安装时间
                $arr[$k]['admin_id']=$ser['ser_id'];//所属服务中心id
                $arr[$k]['company_name']=$company_name;//服务中心名称
                $arr[$k]['feedback_status']='2';//
                $arr[$k]['sys_num']="rwfk".$ser['id'];//派工单id
                $arr[$k]['feedback_pic']=$v['imup_path'];
                $arr[$k]['type_name']=$v['imup_image_name'];
                $arr[$k]['is_type']=2;
            }
        }
        $res=DB::table('feedback')->insert($arr);
        return $res;
    }
    /**|---------------------------------------------------------------------------------
     * @name 售后立即处理
     * @param after_num 售后单号
     * @param ip 访问ip
     * @param sin_bid 反馈标签id
     * @param content 反馈内容
     * @param sin_bcentent 标签内容
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/16 22:04>
     * |---------------------------------------------------------------------------------
     */
    public function immedAfter (Request $request){
        $input = json_decode(file_get_contents("php://input"), true);
        if(!$this->validationKey($input,['after_num','ip','sin_bid','sin_bcentent'])){
            return response()->json(['msg' => '参数错误', 'code' => 202]);exit;
        }
        $lister=DB::table("order_after")->where("after_num",$input['after_num'])->select('deal_serid','sys_num','serial_number','order_num')->first();
        if(empty($lister)){
            return response()->json(['msg' => '售后单不存在', 'code' => 201]);exit;
        }
        $afterdata['status']='10';
        $afterdata['feek_time']=date("Y-m-d",strtotime(date("Y-m-d")." + 1 day"))." 17:30:00";
        $res=DB::table("order_after")->where("after_num",$input['after_num'])->update($afterdata);
        $company_name=DB::table("admin")->where("id",$lister['deal_serid'])->select("company_name")->first();
        $not=$this->Message($lister['deal_serid'],$lister['sys_num'],'【售后】'.$input['content'],'售后反馈（门店）',$company_name['company_name']);
        if(!empty($res) && !empty($not)){
            $this->AddLog($lister['deal_serid'],$input['ip'],"门店同步","售后反馈，",$lister['order_num']."订单(".$lister['serial_number']."),立即处理售后",$lister['sys_num'],$company_name['company_name']);
            return response()->json(['msg' => '操作成功', 'code' => 200]);
            exit;
        }else{
            return response()->json(['msg' => '操作失败', 'code' => 201]);
            exit;
        }

    }
    /**|---------------------------------------------------------------------------------
     * @name 售后日常反馈
     * @param after_num 售后单号
     * @param ip 访问ip
     * @param filePic 图片
     * @param content 备注
     * @param install_name 技师姓名
     * @param install_phone 技师电话
     * @param type 反馈类型 1日常反馈 2完成反馈
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/16 22:04>
     * |---------------------------------------------------------------------------------
     */
    public function feedSales(Request $request){
        $input = json_decode(file_get_contents("php://input"), true);
        if(!$this->validationKey($input,['after_num','ip','content','type'])){
            return response()->json(['msg' => '参数错误', 'code' => 202]);
        }
        $data['data']=json_encode($input);
        $data['api']='feedSales';
        DB::table('store_data')->insert($data);
        $lister=DB::table('order_after')->where("after_num",$input['after_num'])->select('id','status','serial_number','order_num','sys_num','deal_serid')->first();
        if($lister['status']!=10){
            return response()->json(['msg' => '单据状态异常', 'code' => 201]);
            exit;
        }
        $company_name= DB::table('admin')->where('id', $lister['deal_serid'])->select('admin_acc','reward','company_name')->first();
        if(count($input['filePic'])>0){
            $sql = 'INSERT INTO gone_feedsales (`type`,`gl_id`,`install_name`,`install_phone`,`install_time`,`admin_id`,`company_name`,`feedback_status`,`sys_num`,`is_type`,`feedback_pic`) VALUES';
            $num=0;
            foreach ($input['filePic'] as $k=> $v){
                $num++;
                $sqls[]= "('".$num."','".$lister['id']."','".$input['install_name']."','".$input['install_phone']."','".date("Y-m-d H:i:s")."','".$lister['deal_serid']."','".$company_name['company_name']."','2','rwfk".$lister['id']."','5','".$v."')";
            }
            $sql=$sql.implode(',',$sqls);
            DB::insert($sql);
        }
        $not=$this->Message($lister['deal_serid'],$lister['sys_num'],'【售后】'.$input['content'],'售后反馈（门店）',$company_name['company_name']);
        if($input['type']=='2'){
            $arr['status']=30;
            $arr['trigyn']=1;
            $arr['deal_sertime']=date("Y-m-d H:i:s");
            $res=DB::table('order_after')->where("after_num",$input['after_num'])->update($arr);
            $this->AddLog($lister['deal_serid'],$input['ip'],"门店同步","售后反馈，",$lister['order_num']."订单(".$lister['serial_number']."),申请质保完成",$lister['sys_num'],$company_name['admin_acc']);
            $this->operating_times($lister['serial_number'],'申请质保完成时间',date("Y-m-d H-i-s"),$lister['deal_serid'],$lister['order_num'],$company_name['admin_acc']);
        }else{
            $this->AddLog($lister['deal_serid'],$input['ip'],"门店同步","售后反馈，",$lister['order_num']."订单(".$lister['serial_number']."),日常进度反馈",$lister['sys_num'],$company_name['admin_acc']);
            $res=1;
        }
        if(!empty($not) && !empty($res)){
            return response()->json(['msg' => '操作成功', 'code' => 200]);
            exit;
        }else{
            return response()->json(['msg' => '操作失败', 'code' => 201]);
            exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 售后预约时间
     * @param after_num 售后单号
     * @param day_time 预约时间
     * @param ip 访问ip
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/16 23:03>
     * |---------------------------------------------------------------------------------
     */
    public function afterDayTime(Request $request){
        $input = json_decode(file_get_contents("php://input"), true);
        if(!$this->validationKey($input,['after_num','ip','day_time'])){
            return response()->json(['msg' => '参数错误', 'code' => 202]);
        }
        $lister=DB::table('order_after')->where("after_num",$input['after_num'])->select('sys_num','deal_serid','serial_number','order_num')->first();
        $poss['day_time']=$input['day_time'];
        $res=DB::table('order_after')->where("after_num",$input['after_num'])->update($poss);
        if($res){
            $this->AddLog($lister['deal_serid'],$input['ip'],"门店同步","售后预约，",$lister['order_num']."订单(".$lister['serial_number']."),预约售后时间",$lister['sys_num'],'');
            return response()->json(['msg' => '操作成功', 'code' => 200]);
            exit;
        }else{
            return response()->json(['msg' => '操作失败', 'code' => 201]);
            exit;
        }
        return;
    }
    /**|---------------------------------------------------------------------------------
     * @name 催单反馈
     *	@param serial_number 工单单号
     * @param sin_id 催单信息id
     * @param ip 访问ip
     * @param sin_bid 反馈标签id
     * @param content 反馈内容
     * @param sin_bcentent 标签内容
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/17 10:00>
     * |---------------------------------------------------------------------------------
     */
    public function rushOrder(Request $request){
        $input = json_decode(file_get_contents("php://input"), true);
        if(!$this->validationKey($input,['serial_number','ip','sin_bid','content','sin_bcentent'])){
            return response()->json(['msg' => '参数错误', 'code' => 202]);
        }
        $ser_infor=DB::table('ser_infor')->where("sin_serial",$input['serial_number'])->select('sin_sysnum','sin_serid','sin_ordernum','sin_serial')->first();
        $poss['sin_bid']=$input['sin_bid'];
        $poss['sin_centent']=$input['content']."；".$input['sin_bcentent'];
        $poss['sin_state']='2';
        $res=DB::table('ser_infor')->where("sin_serial",$input['serial_number'])->update($poss);
        if(!empty($res)){
            $this->AddLog($ser_infor['sin_serid'],$input['ip'],"门店同步","催单反馈，",$ser_infor['sin_ordernum']."订单(".$ser_infor['sin_serial']."),催单反馈",$ser_infor['sin_sysnum'],'');
            return response()->json(['msg' => '操作成功', 'code' => 200]);
            exit;
        }else{
            return response()->json(['msg' => '操作失败', 'code' => 201]);
            exit;
        }
        return;
    }
    /**|---------------------------------------------------------------------------------
     * @name 驳回账单
     * @param wat_num 结算单号
     * @param apply_note 驳回备注
     * @param ip 访问ip
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/17 16:24>
     * |---------------------------------------------------------------------------------
     */
    public function operation (Request $request)
    {
        $input = json_decode(file_get_contents("php://input"), true);
        if(!$this->validationKey($input,['wat_num','ip','apply_note'])){
            return response()->json(['msg' => '参数错误', 'code' => 202]);
        }
        $ser_id = DB::table('settlement_list')->where('wat_num',$input['wat_num'])->value("ser_id");
        $admin = DB::table('admin')->where('id',$request->input('ser_id'))->select("mouth_pay","admin_acc")->first();

        if($admin['mouth_pay']==2){
            $poss["sett_status"]=63;
        }else{
            $poss["sett_status"]=1;
        }
        $res = DB::table('settlement_list')->where('wat_num',$input['wat_num'])->where('sett_status','!=','10')->first();

        if (!empty($res)){
            return response()->json(['code'=>202,'msg'=>'存在异常订单请联系平台处理']);exit;
        }else{
            try{
                DB::beginTransaction(); //开启事务
                $apply = DB::table('settlement_list')->where('wat_num',$input['wat_num'])->update($poss);
                if(!empty($apply)){
                    $list =DB::table('settlement_list')->where('wat_num',$input['wat_num'])->get();
                    $list_id = "";
                    $sys_num = "";
                    foreach( $list as $k => $v ){
                        $list_id.=",'".$v['list_id']."'";
                        $sys_num.=",'".$v['sys_num']."'";
                    }
                    $list_id=ltrim($list_id,',');
                    $sys_num=ltrim($sys_num,',');
                    $AccArr["account_status"]=1;
                    DB::table("order_list")->whereRaw("serial_number in (".$list_id.")")->update($AccArr);
                    DB::table("orders")->whereRaw("sys_num in (".$sys_num.")")->update($AccArr);
                    $sel['stl_type']=4;
                    //$sel['stl_ticket']="0.00";
                    //$sel['stl_invoice']="0.00";

                    $stl = DB::table('statements_list')->where('stl_wat',$input['wat_num'])->update($sel);
                    $til['til_wats']="";
                    $til['til_state']="10";
                    DB::table('ticket_list')->where('til_wats',$input['wat_num'])->update($til);
                    if($request->input('apply_note') !=""){
                        $post['apply_note'] = $request->input('apply_note');
                        $post['settlement_ids'] = $input['wat_num'];
                        $post['crector'] = $request->get('session_token')['admin_acc'];
                        $post['group_type'] = $request->get('session_token')['admin_groupnew'];
                        $post['public'] = 2;
                        $post['note_model'] = "驳回结算单";
                        $add_note = DB::table('apply_note')->insert($post);
                    }
                    $content=$input['wat_num']."结算号";
                    $this->AddLog($ser_id,$input['ip'],"门店同步","驳回账单，","驳回账单:(".$input['wat_num'].")",$input['wat_num'],$admin['admin_acc']);
                    DB::commit();//提交
                    return response()->json(['msg' => '操作成功', 'code' => 200]);
                    exit;
                }else{
                    DB::rollback();//回滚
                    return response()->json(['msg' => '操作失败', 'code' => 201]);
                    exit;
                }
            }catch(Exception $e){
                DB::rollback();//回滚
                return response()->json(['msg' => $e->getMessage(), 'code' => 201]);
                exit;
            }
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 账单处理
     * @param wat_num 账单单号
     * @param ip 访问ip
     * @param apply_note 驳回备注
     * @return \Illuminate\Http\JsonResponse
     * @author he <2019-04-28>
     * |---------------------------------------------------------------------------------
     */
    public function dealWith (Request $request)
    {
        $input = json_decode(file_get_contents("php://input"), true);
        if(!$this->validationKey($input,['wat_num','ip'])){
            return response()->json(['msg' => '参数错误', 'code' => 202]);
        }
        $wat_num = DB::table('settlement_list')->where("wat_num",$input['wat_num'])->get()->toArray();
        $admin=DB::table('admin')->where("id",$wat_num[0]['ser_id'])->select('admin_acc','admin_groupnew','company_name')->first();
        $serid=$wat_num[0]['ser_id'];
        $apply_for_money = DB::table('statements_list')->where('stl_wat',$wat_num[0]['wat_num'])->value("stl_money");
        $service_center=DB::table('service_center')->where('wat_num',$wat_num[0]['wat_num'])->value('ser_id');
        if($service_center){
            return response()->json(['msg' => '操作成功', 'code' => 200]);
            exit;
        }
        //财务结算信息
        $arr['wat_num'] = $wat_num[0]['wat_num'];//结算单号
        $arr['ser_id'] = $serid;//服务中心id
        $arr['company_name'] = $admin['company_name'];//服务商
        $arr['apply_for_name'] = $admin['admin_acc'];//申请人
        $arr['apply_for_money'] = $apply_for_money??0;//结算金额
        $arr['apply_for_time'] = date("Y-m-d H:i:s");//结算申请时间

        DB::beginTransaction();
        $res = DB::table('service_center')->insert($arr);
        $poss['sett_status']=20;//结算中
        $acc_status= DB::table('settlement_list')->where("wat_num",$input['wat_num'])->update($poss);

        if($acc_status && $res){
            DB::commit();//成功则提交
            $stl_type['stl_type']=2;
            DB::table('statements_list')->where('stl_wat',$wat_num[0]['wat_num'])->update($stl_type);
            $list_id="";
            $sys_num="";
            foreach( $wat_num as $k => $v ){
                $list_id.=",'".$v['list_id']."'";
                $sys_num.=",'".$v['sys_num']."'";
            }
            $list_id=ltrim($list_id,',');

            $AccArr["account_status"]=20;
            DB::table("order_list")->whereRaw("serial_number in (".$list_id.")")->update($AccArr);

            if(!empty($input['apply_note'])){
                $post['apply_note'] = $input['apply_note'];
                $post['settlement_ids'] = $input['wat_num'];
                $post['crector'] = $admin['admin_acc'];
                $post['group_type'] = $admin['admin_groupnew'];
                $post['public']=2;
                $post['note_model']="订单金额确认";
                $add_note = DB::table('apply_note')->insert($post);
            }
            $content=$wat_num[0]['wat_num']."结算号";
            $this->AddLog($serid,$input['ip'],"门店同步","同意账单，","同意账单:(".$input['wat_num'].")",$input['wat_num'],$admin['admin_acc']);
            return response()->json(['msg' => '操作成功', 'code' => 200]);
            exit;
        }else{
            DB::rollback();
            return response()->json(['msg' => '操作失败', 'code' => 201]);
            exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 获取标签
     * @param type 标签类型 1:催单标签 2：拒单标签 3售后标签
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/17 16:24>
     * |---------------------------------------------------------------------------------
     */
    public function searchLable(){
        $input = json_decode(file_get_contents("php://input"), true);
        if(!$this->validationKey($input,['type'])){
            return response()->json(['msg' => '参数错误', 'code' => 202]);
        }
        $type=[1,2,3];
        if(in_array($input['type'],$type)) {
            if($input['type'] == '3'){
                $json[0]['key'] = 1;
                $json[0]['value'] ='已联系';
                $data[0]['type'] = '2';
                $data[0]['childTag'] = array();
                $json[1]['key'] = 2;
                $json[1]['value'] ='技师已出发';
                $data[1]['type'] = '2';
                $data[1]['childTag'] = array();
            }else {
                if ($input['type'] == '1') {
                    $res = DB::table('setmoney_type')->whereRaw("lt_parent_id=79 and FIND_IN_SET('2',lt_group)")->select('sety_id', 'sety_name')->get()->toArray();
                }
                if ($input['type'] == '2') {
                    $res = DB::table('setmoney_type')->whereRaw("lt_parent_id=25 and FIND_IN_SET('2',lt_group)")->select('sety_id', 'sety_name')->get()->toArray();
                }
                $json = [];
                if (!empty($res)) {
                    foreach ($res as $k => $v) {
                        $json[$k]['key'] = $v['sety_id'];
                        $json[$k]['value'] = $v['sety_name'];
                        $next = DB::table('setmoney_type')->where('lt_parent_id', $v['sety_id'])->select('sety_id', 'sety_name')->get()->toArray();
                        if (count($next) > 0) {
                            $json[$k]['type'] = '1';
                            foreach ($next as $ky => $vl) {
                                $data[$ky]['key'] = $vl['sety_id'];
                                $data[$ky]['value'] = $vl['sety_name'];
                                $data[$ky]['childTag'] = array();
                                $data[$ky]['type'] = '2';
                            }
                            $json[$k]['childTag'] = $data;
                        } else {
                            $json[$k]['childTag'] = array();
                            $json[$k]['type'] = '2';
                        }
                    }
                }
            }
            return response()->json(['data' => $json, 'msg' => '操作成功', 'code' => 200]);
            exit;
        }else{
            return response()->json(['msg' => '参数错误', 'code' => 201]);
            exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 添加备注
     * @param serial_number 工单号
     * @param ip 访问ip
     * @param content 备注
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/17 9:22>
     * |---------------------------------------------------------------------------------
     */
    public function addNote(Request $request){
        $input = $request->only('serial_number','ip','content');
        $check_number=$this->checkSerialNumber($input['serial_number']);
        if(!$check_number){
            return response()->json(['msg' => '单号不存在', 'code' => 201]);
            exit;
        }
        $not=$this->Message($check_number['ser_id'],$check_number['sys_num'],$input['content'],'门店备注','');
        if(!empty($not)){
            return response()->json(['msg' => '操作成功', 'code' => 200]);
            exit;
        }else{
            return response()->json(['msg' => '操作失败', 'code' => 201]);
            exit;
        }
        return;
    }
    /**|---------------------------------------------------------------------------------
     * @name 同步瓦尔塔小程序门店信息
     * @param $order_num 订单单号
     * @param $ser_id 门店id
     * @param $type 同步类型
     * @param $serial_number 工单号
     * @param $state 状态
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/15 22:04>
     * |---------------------------------------------------------------------------------
     */
    public function store_syn($order_num,$ser_id,$type,$serial_number,$state){
        $vcode=DB::table('certification')->where('ser_id',$ser_id)->value('ser_varcode');
        $poss['order_num']=$order_num;
        $poss['ser_id']=$vcode?$vcode:'SDKBWH';//$ser_id
        $poss['serial_number']=$serial_number;
        $poss['state']=$state;
        $poss['shouw']='';//test
        $poss['type']=$type;
        $url="https://1.sudianwang.com/index.php/Jicdata/call_way";
        $res=$this->https_post($url,$poss);
        return $res;
    }
    function https_post($url,$data){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        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;
    }
    //http协议post传参
    function http_post($url,$possa){
        $ch = curl_init();
        curl_setopt($ch,CURLOPT_URL,$url);
        curl_setopt($ch,CURLOPT_HEADER,0);
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($ch,CURLOPT_POST,1);
        curl_setopt($ch,CURLOPT_POSTFIELDS,$possa);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
    /**|---------------------------------------------------------------------------------
     * @name 校验工号是否存在
     * @param $serial_number 工单单号
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/15 20:31>
     * |---------------------------------------------------------------------------------
     */
    /**|---------------------------------------------------------------------------------
     * @name 验证参数
     * @param $key 验证键
     * @param $receive 接收参数
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/18 15:22>
     * |---------------------------------------------------------------------------------
     */
    public function validationKey($receive,$key){
        foreach ($key as $k => $v){
            if(empty($receive[$v])){
                return false;
                exit;
            }
        }
        return true;
    }
    public function checkSerialNumber($serial_number){
        $order_list=DB::table('order_list')->where('serial_number',$serial_number)->select('id','serial_number','p_id','sys_num','ser_id','order_num','create_time','stauas')->first();
        return $order_list;
    }
    /**|---------------------------------------------------------------------------------
     * 不参与奖惩平台
     * @author dou <2020/7/15 20:31>
     * |---------------------------------------------------------------------------------
     * */
    public function rulesout ( ){
        $pt_id=array('111','112','108','95','106','110','120','136');
        $pttype = $this ->getPtIdByPtType(2,2);
        $pt_id = array_merge($pt_id,$pttype);
        return $pt_id;
    }
    /**
     * @return mixed
     * @author du
     * @date 2022/4/22
     */
    public static function getPtIdByPtType($pt_type,$type = 1){
        $data = DB::table('pt')->whereRaw('FIND_IN_SET('.$pt_type.',pt_type)',true)->pluck('id')->toarray();
        if(!$data){
            $data = array('453');
        }
        if($type == 1){
            $data = implode(',',$data);
        }
        return $data;

    }
    /**|---------------------------------------------------------------------------------
     * @name 同步数据罗盘过度数据表
     * @param $data 处理数据
     * @param $serial_number 工单号
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/15 21:45>
     * |---------------------------------------------------------------------------------
     */
    public function temaddtime($data,$serial_number){
        $data['update_time']=date("Y-m-d H:i:s");
        DB::table("temporary")->where('serial_number',$serial_number)->where('category','1')->update($data);
        return;
    }
    /**|---------------------------------------------------------------------------------
     * @name 记录操作时间
     * @param $num 工单号
     * @param $type 时间类型
     * @param $time 时间
     * @param $ser_id 服务商id
     * @param $ordernum 订单号
     * @param $admin_acc 门店操作人名称
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/14 20:42>
     * |---------------------------------------------------------------------------------
     */
    function operating_times($num,$type,$time,$ser_id,$ordernum,$admin_acc){
        if($admin_acc=='') {
            $admin_acc = DB::table('admin')->where('id', $ser_id)->value('admin_acc');
        }
        $data['serial_number']=$num;
        $data['create_name']=$admin_acc;
        $data['is_type']=$type;
        $data['create_time']=$time;
        $data['order_num']=$ordernum;
        $result=DB::table('order_time')->insert($data);
        if($result){
            return 1;exit;
        }else{
            return 2;exit;
        }
    }
    /**|---------------------------------------------------------------------------------
     * @name 添加备注
     * @param $ids 门店id
     * @param $sys_num 系统单号
     * @param $content 备注内容
     * @param $type 备注类型
     * @param $admin_acc 操作人名称
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/16 22:39>
     * |---------------------------------------------------------------------------------
     */
    //备注
    function Message($ids,$sys_num,$content,$type,$admin_acc){
        if($admin_acc==''){
            $admin_acc = DB::table('admin')->where('id', $ids)->value('company_name');
        }
        $data['orders_id']=$sys_num;//系统单号
        $data['note_name']=$admin_acc;//备注人
        $data['note_content']=$content;//备注内容
        $data['note_type']=$type;//备注类型
        $data['note_adid']=$ids;//备注类型
        $data['note_group']="2";//备注类型
        $data['public_state']=2;//可见
        $data['note_installid']='0';//可见
        $rest=DB::table('note')->insert($data);
        return $rest;
    }
    /**|---------------------------------------------------------------------------------
     * @name 日志
     * @param $ids 服务商id
     * @param $ips ip
     * @param $function_name 操作模块
     * @param $type 操作类型
     * @param $content 操作内容
     * @param $order_num 操作单号
     * @param $admin_acc 操作人名称
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2020/7/14 21:08>
     * |---------------------------------------------------------------------------------
     */
    function AddLog($ids,$ips,$function_name,$type,$content,$order_num,$admin_acc){
        if($admin_acc==''){
            $admin_acc = DB::table('admin')->where('id', $ids)->value('admin_acc');
        }
        $data['czrz_name'] = $admin_acc;//登录者
        if($ips){
            $data['czrz_ip'] = $ips;//操作ip
        }
        $data['czrz_czsj'] = date("Y-m-d H:i:s");//创建时间
        $data['czrz_czlx'] = $type;//创建类型
        $data['czrz_number'] = $order_num;//平台单号
        $data['czrz_czxq'] = $content;//操作内容
        $data['test_data'] = $function_name;//操作模块名称
        $res=DB::table('czrz')->insert($data);
        return $res;
    }
    /**********************************门店对接接口（dou）*******************************************************/
}
