<?php
namespace App\Http\Controllers\AppApi;

use App\Http\Controllers\BaseController;
use App\Models\Admin;
use App\Models\AdminInfor;
use App\Models\AdminCertificate;
use App\Models\Certification;
use App\Models\GhPrice;
use App\Models\GhXPrice;
use App\Models\GoodsBrand;
use App\Models\PhoneCoke;
use App\Models\InstallPerson;
use App\Models\OrderList;
use App\Models\OrderAfter;
use App\Models\Orders;
use App\Models\Note;
use App\Models\User;
use App\Services\CommonService;
use App\Services\InstallPersonService;
use App\Services\OrderService;
use App\Services\PlatformService;
use Illuminate\Http\Request;
use DB;
use Input;

class InterfaceandroidController extends BaseController
{
    public function JsonMore($json,$type){
        foreach($json as $key=>$value){
            foreach($value as $k=>$v){
                foreach( $v as $ka => $va ){
                    foreach( $va as $kx => $vx ){
                        foreach( $vx as $km => $vm ){
                            $json[$key][$k][$ka][$kx][$km] = urlencode($vm);//JSON格式转换
                        }
                    }
                }
            }
        }
        $json=urldecode(json_encode($json));//JSON格式转换
        if($type=="1"){
            $json=substr($json,1,-1);//截取json数据的中括号
            $json='{"data":'.$json.'}';
        }else if($type=="2"){
            $json='{"data":'.$json.',"desecption":"succes","state":"1"}';
        }else if($type=="4"){
            $json='{"data":'.$json.',"desecption":"succes","state":"4"}';
        }else{
            $json='{"data":'.$json.'}';
        }
        return $json;
    }
	/**|---------------------------------------------------------------------------------
     * @name 原图片域名链接
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/05/07 10:03>
     * |---------------------------------------------------------------------------------
     */
    public function getUrl(){
        return "http://mo2o.sudianwang.com";
        //return "http://mo2oceshi.sudianwang.com";
    }
    /**|---------------------------------------------------------------------------------
     * @name 图片链接获取
     * @param $pic 问价地址链接
     * @return \Illuminate\Http\JsonResponse
     * @author dou <2021/05/07 10:03>
     * |---------------------------------------------------------------------------------
     */
//	public function picurl($pic)
//    {
//        if(strstr($pic,'http')){
//			return $pic;
//        }else{
//	       return $this->getUrl().$pic;
//        }
//    }
	/**
	* int转为字符串
	* @param array $data
	* @return string
	* @author dou <2021/05/07 14:18>
	*/
	public function intToStr($data){
		foreach ($data as $k=>$v){
			if(is_array($v)){
				if($v==false){
					$data[$k]=$v;
				}else{
					$data[$k] = $this->intToStr($v);
				}
			}else{
				$data[$k] = (string)$v;
			}
		}
		return $data;
	}
    /**|---------------------------------------------------------------------------------
     * @name 添加app日志
     * @param int $ids 操作人id
     * @param string $ips 操作人设备ip
     * @param string $function_name 操作模块
     * @param string $type 操作类型
     * @param string $content 操作内容
     * @param string $order_num 操作单号
     * @retrun \Illuminate\Http\JsonResponse /multitype:array
     * @author dou 2022/5/17 9:07
     * |---------------------------------------------------------------------------------
    */
    private function addAppLog($ids,$ips,$function_name,$type,$content,$order_num = ''){
        //DB::connection()->enableQueryLog();
        $admin=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;

    }

    //计算时间差
    private function Compute_Time($begin_time,$end_time){
        if($begin_time < $end_time){
            $starttime = $begin_time;
            $endtime = $end_time;
        }else{
            $starttime = $end_time;
            $endtime = $begin_time;
        }
        //计算天数
        $timediff = $endtime-$starttime;
        $days = intval($timediff/86400);
        //计算小时数
        $remain = $timediff%86400;
        $hours = intval($remain/3600);
        //计算分钟数
        $remain = $remain%3600;
        $mins = intval($remain/60);
        //计算秒数
        $secs = $remain%60;
        //$res = array("day" => $days,"hour" => $hours,"min" => $mins,"sec" => $secs);
        $res = $days.'天'.$hours.'时'.$mins.'分'.$secs.'秒';
        return $res;
    }
    //curl图片上传
    public function curl_basepic($url_type,$param=null){
        if (empty($param) && empty($url_type)) {
            return false;
        }

       if ($url_type == '1'){
            $postUrl = $this->getUrl().'/index.php/Addpic/addpic';//添加
       }elseif ($url_type == '2'){
            $postUrl = $this->getUrl().'/index.php/Addpic/eitpic';//修改
        }elseif ($url_type == '3'){
            $postUrl = $this->getUrl().'/index.php/Addpic/deletpic';//删除
        }
//        return $postUrl;
        $curlPost = $param;
        $ch = curl_init();//初始化curl
        curl_setopt($ch, CURLOPT_URL,$postUrl);//抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($ch);//运行curl
        curl_close($ch);
        $data=(string)$data;

        return $data;
    }

    function curl_basepic44($url_type,$param=null){
        if (empty($param) && empty($url_type)) {
            return false;
        }

        if ($url_type == '1'){
            $postUrl = 'http://mo2oceshi.sudianwang.com/index.php/Addpic/addpic';
        }elseif ($url_type == '2'){
            $postUrl = 'http://mo2oceshi.sudianwang.com/index.php/Addpic/eitpic';
        }elseif ($url_type == '3'){
            $postUrl = 'http://mo2oceshi.sudianwang.com/index.php/Addpic/deletpic';
        }
        $ch = curl_init();
        $timeout = 300;
        $header=array(
            "Accept: application/json",
            "Content-Type: application/json;charset=utf-8",
        );
        $curlPost = $param;
        curl_setopt($ch, CURLOPT_URL, $postUrl);
        //设置头文件的信息作为数据流输出
        // curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //exit;
        //curl_setopt($ch, CURLOPT_REFERER, "http://127.0.0.1/");   //构造来路
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }


    // 登录  1 成功  2 密码错误  3 用户名或手机号为空  4 用户名不存在
    public function Json_login (Request $request){
        if($request->isMethod('post')){
            $time=date('Y-m-d H:i:s');
            $time1=date("Y-m-d H:i:s");

            $input=$request->all();
            //return $input;
            if($request->input('ser_type') == 1){
                if($request->input('is_type') == 1){
                    $admin_id=DB::table('admin_infor')->where(['phone'=>$input['Log_acc']])->value('admin_id');
                    if($admin_id){
                        $rest=DB::table('admin')->where(['id'=>$admin_id,'admin_password'=>md5($input['Log_password']),'enable'=>1,'admin_group'=>2])->first();
                        if($rest){
                            $json['id']=$rest['id']; //id
                            if($rest['admin_pic']){
                                $json['admin_pic']=$this->picurl($rest['admin_pic']); //头像
                            }else{
                                $json['admin_pic']=""; //头像
                            }

                            $json['ad_paper']=$rest['ad_paper']; //是否确认白皮书
                            $json['admin_acc']=$rest['admin_acc'];//登录名
                            $json['admin_name']=$rest['admin_name'];//姓名
                            $json['admin_group']=$rest['admin_group'];//权限
                            $json['company_name']=$rest['company_name'];//服务中心名称
                            $json['login_time']=$time;//登录时间
                            $json['feck_time']=$time1;
                            $poss['UUID']=$input['UUID'];
                            $uuids=DB::table('admin_infor')->where(['admin_id'=>$json['id']])->pluck('UUID');
                            if($uuids==$input['UUID']){
                                $uuid=1;
                            }else{
                                $uuid=DB::table('admin_infor')->where(['admin_id'=>$json['id']])->update($poss);
                            }
                            if($uuid){
                                self::addAppLog($json['id'], $input['dediips'], '登录('.$input['phoneType'].')', '登录', '登录服务商app（'.$input['appVersion'].'）');
                                return response()->json(['data'=>$this->intToStr($json),'desecption'=>'登录成功','state'=>1]);exit;
                            }else{
                                return response()->json(['data'=>0,'desecption'=>'密码错误','state'=>2]);exit;
                            }
                        }else{
                            return response()->json(['data'=>0,'desecption'=>'密码错误','state'=>2]);exit;
                        }
                    }else{
                        return response()->json(['data'=>0,'desecption'=>'用户名不存在','state'=>4]);exit;
                    }
                }else{

                    if(empty($request->input('Log_acc')) || empty($request->input('Log_password'))){
                        return response()->json(['data'=>0,'desecption'=>'密码错误','state'=>3]);
                    }
                    $rea = DB::table('admin')->where(['admin_acc'=>$input['Log_acc'],'enable'=>'1'])->first();
                    if($rea){
                        $rest=DB::table('admin')->where(['admin_acc'=>$input['Log_acc'],'admin_password'=>md5($input['Log_password']),'enable'=>1,'admin_group'=>2])->first();
                        if($rest){
                             $json['id']=$rest['id']; //id
                            if($rest['admin_pic']){
                                $json['admin_pic']=$this->picurl($rest['admin_pic']); //头像
                            }else{
                                $json['admin_pic']=""; //头像
                            }
                            $json['ad_paper']=$rest['ad_paper']; //是否确认白皮书
                            $json['admin_acc']=$rest['admin_acc'];//登录名
                            $json['admin_name']=$rest['admin_name'];//姓名
                            $json['admin_group']=$rest['admin_group'];//权限
                            $json['company_name']=$rest['company_name'];//服务中心名称
                            $json['login_time']=$time;//登录时间
                            $json['feck_time']=$time1;
                            $poss['UUID']=$input['UUID'];
                            $uuids=DB::table('admin_infor')->where(['admin_id'=>$json['id']])->value('UUID');
                            if($uuids==$input['UUID']){
                                $uuid=1;
                            }else{
                                $uuid=DB::table('admin_infor')->where(['admin_id'=>$json['id']])->update($poss);
                            }
                            if($uuid){
                                self::addAppLog($json['id'], $input['dediips'], '登录('.$input['phoneType'].')', '登录', '登录服务商app（'.$input['appVersion'].'）');
                                return response()->json(['data'=>$this->intToStr($json),'desecption'=>'登录成功','state'=>1]);exit;
                            }else{
                                return response()->json(['data'=>0,'desecption'=>'设备号异常','state'=>2]);exit;
                            }
                        }else{
                            return response()->json(['data'=>0,'desecption'=>'密码错误','state'=>3]);exit;
                        }
                    }else{
                        return response()->json(['data'=>0,'desecption'=>'用户名不存在','state'=>4]);exit;
                    }
                }
            }elseif($request->input('ser_type') == 2){
                if(empty($request->input('Log_acc')) || empty($request->input('Log_password'))){
                    return response()->json(['data'=>null,'desecption'=>'账号和密码不能为空','state'=>5]);exit;
                }
                $check = InstallPerson::where(['check_code'=>$input['Log_acc'],'delet_y'=>'1','install_is_type'=>'1'])->value('id');
                if($check){
                    $list = InstallPerson::where(['check_code'=>$input['Log_acc'],'install_password'=>md5($input['Log_password'])])->first();
                    if($list){
                        $json['id']=$list['id'];//id
                        if($list['install_pic']){
                            $json['install_pic']=$this->picurl($list['install_pic']); //头像
                        }else{
                            $json['install_pic']=""; //头像
                        }
                        $json['ad_paper']='';//是否确认白皮书
                        $json['admin_acc']=$list['check_code'];//登录名
                        $json['install_name']=$list['install_name'];//姓名
                        $json['admin_group']=$list['admin_id'];//权限
                        $json['company_name']=Admin::where(['id'=>$list['admin_id']])->value('company_name');//服务中心名称
                        $json['login_time']=$time;//服务中心名称
                        $json['feck_time']=$time1;//服务中心名称
                        $poss['UUID']=$input['UUID'];
                        //$uuids=$install_person->where("`id`='".$json[0]['id']."'")->getField('UUID');
                        $uuids = InstallPerson::where('id',$json['id'])->value('UUID');
                        if($uuids==$input['UUID']){
                            $uuid=1;
                        }else{
                            $uuid=InstallPerson::where('id',$json['id'])->update($poss);
                        }
                        if($uuid){
                            self::addAppLog($json['id'], $input['dediips'], '登录('.$input['phoneType'].')', '登录', '登录技师app（'.$input['appVersion'].'）');
                            return response()->json(['data'=>$this->intToStr($json),'desecption'=>'登录成功','state'=>1]);exit;
                        }else{
                            return response()->json(['data'=>null,'desecption'=>'密码错误','state'=>2]);exit;
                        }
                    }else{
                        return response()->json(['data'=>null,'desecption'=>'密码错误','state'=>3]);exit;
                    }
                }else{
                    return response()->json(['data'=>null,'desecption'=>'用户名不存在','state'=>4]);exit;
                }
            }else{
                return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>9]);exit;
            }
        }
    }

    /**
     * @name 转单记录
     * @param  os_serial    派工单号
     * @param  os_serid     服务商
     * @param  os_installid 安装技师
     * @param  os_parenid   父类id
     * @param  os_ordernum  订单编号
     * @param  os_sysnum    系统单号
     * @return json
     * @author he <2019.2.26>
     */
    private function Json_sendflow($serial_number,$ser_id,$istall_id,$parenid,$order_num,$sys_num) {
        $senl['os_serial']=$serial_number;
        $senl['os_serid']=$ser_id;
        $senl['os_installid']=$istall_id;
        $senl['os_parenid']=$parenid;
        $senl['os_ordernum']=$order_num;
        $senl['os_sysnum']=$sys_num;
        DB::table('order_sendflow')->insert($senl);
    }

    /**
     * @name  添加备注方法
     * @param $ids
     * @param $sys_num  系统单号
     * @param $content  备注内容
     * @param $type     备注类型
     * @param $admin_id 登录id
     * @return string
     * @author he <2019.2.22>
     */
    public function Message($ids,$sys_num,$content,$type,$admin_id) {
//        $rea = OrderList::where('sys_num',$sys_num)->first();
//        if($rea['stauas'] == 60){
//            $poss['order_status'] = "63";
//            $posa['stauas'] = "63";
//            OrderList::where('sys_num',$sys_num)->update($posa);
//            Orders::where('sys_num',$sys_num)->update($poss);
//        }
        $admin_acc = Admin::where('id',$ids)->value('admin_acc');
        $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']=$admin_id;//可见

        $rest = Note::insert($data);

        if($rest){
            return 1;
        }else{
            return "失败";
        }
    }


    //白皮书签署
    public function Json_paper(Request $request){
        if($request->isMethod('post')){
            $id = $request->input('admin_id');
            $res = DB::table('admin')->where(['id' => $id])->update(['ad_paper' => 1]);
            if ($res) {
                //成功 1
                return response()->json(['data' => null, 'desecption' => '成功', 'state' => 1]);
                exit;
            } else {
                //失败 2
                return response()->json(['data' => null, 'desecption' => '失败', 'state' => 2]);
                    exit;
            }

        }

    }

    /**@name 获取签署内容
     * @param type 1:白皮书
     * @param admin_id 服务商id
     * @app_id
     * @return json
     */
    public function Json_papercontent(Request $request){
        if($request->input('type')){
            $type = $request->input('type');
            $app_id = $request->input('app_id');
            if($type == 1){
                $res['content']=DB::table('manageapp')->where('app_type',$type)->value("app_content");
            }elseif($type==5){
                $res['content']=DB::table('manageapp')->where('app_type',$type)->value("app_content");
            }else{
                $res['content']=DB::table('manageapp')->where('app_id',$app_id)->first();
            }
            if($request->input('admin_id')){
                $res['ad_paper'] = DB::table('admin')->where('id',$request->input('admin_id'))->value('ad_paper'); //是否签署白皮书
            }

            if($res){
                // 成功
                return response()->json(['data'=>$this->intToStr($res),'desecption'=>'','state'=>1]);exit;
            }else{
                // 失败
                return response()->json(['data'=>null,'desecption'=>'fail','state'=>2]);exit;
            }
        }


    }


    /**
     * @name  修改密码
     * @param ser_type 用户 1:服务商 2:技师
     * @param admin_pass 原密码
     * @param admin_new_pass 新密码
     * @param admin_id 登录id(服务中心id)
     * @return json
     * @author he <2019.2.22>
     */
    public function Json_editpass(Request $request){

        $input = $request->only('admin_id','ser_type','admin_pass','admin_new_pass');
        $input['admin_new_pass'] = str_replace(' ','',$input['admin_new_pass']);
        if($input['ser_type'] == '1'){
            $password=Admin::where(['id'=>$input['admin_id'],'admin_password'=>md5($input['admin_pass'])])->select('admin_password')->first();
            if(!empty($password) && (md5($input['admin_pass']) == $password['admin_password'])){
                if($password->admin_password == md5($input['admin_new_pass'])){
                    return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
                }
                $arr['admin_password']=md5($input['admin_new_pass']);
                $rest = Admin::where(['id'=>$input['admin_id']])->update($arr);
                $admin_id=$input['admin_id'];
                $data['back_pass']=$input['admin_new_pass'];
                AdminInfor::where(['admin_id'=>$admin_id])->update($data);
                if($rest){
                    //成功
                    return response()->json(['data'=>null,'desecption'=>'修改成功','state'=>1]);exit;
                }else{
                    //失败
                    return response()->json(['data'=>null,'desecption'=>'修改失败','state'=>2]);exit;
                }
            }else{
                return response()->json(['data'=>null,'desecption'=>'原密码错误','state'=>3]);exit;
            }
        }else{

            $password=DB::table('install_person')->where(['id'=>$input['admin_id']])->first();
            //dd($password);
            if(!empty($password) && ($input['admin_pass'] == $password['install_password1'])){
                if($password['install_password']== md5($input['admin_new_pass'])){
                    return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
                }
                $arr['install_password']=md5($input['admin_new_pass']);
                $arr['install_password1']=$input['admin_new_pass'];
                $rest=DB::table('install_person')->where('id',$input['admin_id'])->update($arr);

                if($rest){
                    //成功
                    return response()->json(['data'=>null,'desecption'=>'修改成功','state'=>1]);exit;
                }else{
                    //失败
                    return response()->json(['data'=>null,'desecption'=>'修改失败','state'=>2]);exit;
                }
            }else{
                return response()->json(['data'=>null,'desecption'=>'原密码错误','state'=>3]);exit;
            }
        }
    }

    /**@name 忘记密码修改密码
     * @param Request $request
     * @return json
     */
    public function editpass (Request $request){

        if(!$request->input('ser_type') && !$request->input('admin_pass')){
            return response()->json(['data'=>null,'desecption'=>'参数错误','state'=>4]);exit;
        }
        $input=$request->only('ser_type','admin_pass','phone','Log_acc');
        $input = str_replace(' ','',$input['admin_pass']);
        if($input['ser_type']=='1'){
            $arr['admin_password']=md5($input['admin_pass']);
            $admin = DB::table('admin')->where('admin_acc',$input['Log_acc'])->select('id','admin_password')->first();
            if($admin['admin_password'] == $arr['admin_password']){
                return response()->json(['data'=>null,'desecption'=>'修改成功','state'=>1]);exit;
            }
            $infor = DB::table('admin_infor')->where(['admin_id'=>$admin['id'],'phone'=>$input['phone']])->first();
            if($infor){
                $rest=DB::table('admin')->where('admin_acc',$input['Log_acc'])->update($arr);
                $data['back_pass']=$input['admin_pass'];
                DB::table('admin_infor')->where('admin_id',$admin['id'])->update($data);
            }else{
                return response()->json(['data'=>null,'desecption'=>'手机号用户名不匹配','state'=>5]);exit;
            }

        }else{
            $infor =DB::table('install_person')->where(['check_code'=>$input['Log_acc'],'install_phone'=>$input['phone']])->first();
            if($infor){
                $arr['install_password']=md5($input['admin_pass']);
                $arr['install_password1']=$input['admin_pass'];
                if($infor['install_password'] == md5($input['admin_pass'])){
                    return response()->json(['data'=>null,'desecption'=>'修改成功','state'=>1]);exit;
                }
                $rest=DB::table('install_person')->where('id',$infor['admin_id'])->update($arr);
            }else{
                return response()->json(['data'=>null,'desecption'=>'手机号用户名不匹配','state'=>5]);exit;
            }

        }
        if($rest){
            // 成功
            return response()->json(['data'=>null,'desecption'=>'修改成功','state'=>1]);exit;
        }else{
            // 失败
            return response()->json(['data'=>null,'desecption'=>'修改失败','state'=>2]);exit;
        }
    }

    /*服务中心信息
	admin_pic 头像   service_name：公司名称    admin_number：公司编号 	ad_project:经营项目	company_name:服务中心名称	admin_principal：负责人	admin_address：办公地址	ad_brand：代理品牌		admin_longitude：坐标经度	admin_principal：坐标纬度		phone：电话	qq：QQ		email:邮箱		cer_business:营业执照		cer_bustype:营业执照验证		cer_account：开户许可证		admin_acctype：开户许可证验证
	*/
    public function Json_admin_show(Request $request){
        $res1 = Admin::where('id',$request->input('admin_id'))->select(['admin_pic','company_name','ad_brand','ad_project'])->first()->toArray();
        //return $res1;exit;
        if($res1){
            $res2 = AdminInfor::where('admin_id',$request->input('admin_id'))->first()->toArray();
            $res3 = DB::table('admin_certificate')->where('admin_id',$request->input('admin_id'))->first();
            $certification_num = DB::table('certification')->where('ser_id',$request->input('admin_id'))->value('certification_num');
            //return $res3;
            $json['brand']=GoodsBrand::select('brand_name','id')->get()->toArray();

            $json['project']=[['id'=>1,'project'=>'蓄电池更换'],['id'=>2,'project'=>'轮胎更换'],['id'=>3,'project'=>'汽车救援'],['id'=>4,'project'=>'汽车保养'],['id'=>5,'project'=>'汽车保险'],['id'=>6,'project'=>'其他']];


            if($res1['admin_pic'] == ''){
                $json['admin_pic']=$res1['admin_pic']; //头像
            }else{
                $json['admin_pic']=$this->picurl($res1['admin_pic']);//头像
            }
            $ad_project=ltrim(rtrim($res1['ad_project'],','),',');//经营项目
            $json['ad_project']=explode(',',$ad_project);
            if($res2['service_name'] == ""){
                $json['service_name']=$res1['company_name'];
            }else{
                $json['service_name']=$res2['service_name']; //公司名称
            }
            $json['admin_number']=$certification_num;//公司编号
            $json['admin_principal']=$res2['admin_principal'];//负责人
            $json['admin_address']=$res2['admin_address'];//办公地址
            $json['admin_dressi']=$res2['admin_dressi'];//公司绑定地址
            $ad_brand=ltrim(rtrim($res1['ad_brand'],','),',');//代理品牌
            $json['ad_brand']=explode(',',$ad_brand);
            $json['admin_longitude']=$res2['admin_longitude'];//坐标经度
            $json['admin_latitude']=$res2['admin_latitude'];//坐标纬度
            $json['phone']=$res2['phone'];//电话
            $json['qq']=$res2['qq'];//QQ
            $json['email']=$res2['email'];//邮箱
            if($res3['cer_business'] != ""){
                $json['cer_business']=$this->picurl($res3['cer_business']); //营业执照
            }else{
                $json['cer_business']=$res3['cer_business'];
            }
            $json['cer_bustype']=$res3['cer_bustype'];//营业执照验证1：已验证；2：未验证
            if($res3['cer_account']!=""){
                $json['cer_account']=$this->picurl($res3['cer_account']);//开户凭证
            }else{
                $json['cer_account']=$res3['cer_account'];//开户凭证
            }
            $json['admin_acctype']=$res3['admin_acctype'];//开户许可证验证 1：已验证；2：未验证
            //return $json;
            return response()->json(['data'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
        }
    }

    /**
     * @param is_type修改类型： 1：头像 2：负责人 3：办公地址 4：营业执照 5：开户许可证 6：服务区域 7：手机号 8：邮箱 9：qq
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年6月1日上午9:19:48
     */
    public function Json_admin_edit(Request $request){
//        $upPath='./Uploads/admin';
//        $param['path'] = $upPath;
//        $param['file'] = $this->ceshi_pic();
//        $param['type'] = 1;
//        $curl_data = $this->curl_basepic('1',$param);
//        $curl_data = iconv('gbk','utf-8',$curl_data);
//        echo $curl_data;
//        exit;
        $res1=DB::table('admin')->where('id',$request->get('admin_id'))->value('admin_pic');

        if($request->isMethod('post')){
            $input = $request->all();
            if($request->input('is_type') == 1){
                $res1=DB::table('admin')->where('id',$request->get('admin_id'))->value('admin_pic');

                $file = $request->input('admin_pic');

                if($file){
                    //return '11123';exit;
                    //dd($file);
                    //if (preg_match('/(?<=\/)[^\/]+(?=\;)/',$file,$pregR)) $streamFileType ='.' .$pregR[0];
                    //$streamFileRand = time().str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                    //$dir='./Uploads/admin';
//                     $upPath='./Uploads/admin';
//                     $param['path'] = $upPath;
//                     $param['file'] = $file;//$this->ceshi_pic();
//                     $param['type'] = 1;
//                     $param['deletpath'] = $res1['admin_pic']??'';
//                     $curl_data = $this->curl_basepic('2',$param);
//                     if($curl_data!='error'){
                        $streamFilename = $file;
                        $psos['admin_pic'] = $streamFilename;
                        $res = Admin::where('id',$request->input('admin_id'))->update($psos);
                        if($res){
                            $streamFilename = trim($streamFilename,'.');
                            $data=$this->picurl($streamFilename);
                            return response()->json(['data'=>$data,'desecption'=>'成功','state'=>1]);exit;
                        }else{
                            return response()->json(['data'=>null,'desecption'=>'失败','state'=>4]);exit;
                        }
//                     }else{
//                         return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
//                     }


                    /*$streamFilename = $upPath."/".$streamFileRand .$streamFileType;

                    preg_match('/(?<=base64,)[\S|\s]+/',$file,$streamForW);

                    if (file_put_contents($streamFilename,base64_decode($streamForW[0]))===false){
                        return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                    }else{
                        $streamFilename=trim($streamFilename,".");
                        $psos['admin_pic']="/".$streamFilename;
                        $data=$this->getUrl().$streamFilename;
                        $aa=ltrim($res1,'/');
                        if(file_exists($aa)){
                            unlink($aa);
                        }
                        $res = Admin::where('id',$request->input('admin_id'))->update($psos);
                        //dump($psos);
                        if($res){
                            return response()->json(['data'=>$data,'desecption'=>'成功','state'=>1]);exit;
                        }else{
                            return response()->json(['data'=>null,'desecption'=>'失败','state'=>4]);exit;
                        }
                    }*/
                }else{
                    return response()->json(['data'=>null,'desecption'=>'请选择图片','state'=>5]);exit;
                }


            }elseif($request->get('is_type') == 2){
                $poss['admin_principal']=$request->get('admin_principal');
                $res = AdminInfor::where('admin_id',$request->input('admin_id'))->update($poss);
                if($res){
                    $this->addAppLog($request->input('admin_id'),$request->input('dediips'),'派工单('.$input['phoneType'].')','修改','负责人姓名');
                    return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
                }
            }elseif($request->input('is_type') == 3){
                $res = AdminInfor::where('admin_id',$request->input('admin_id'))->update(['admin_address'=>$request->input('admin_address')]);
                if($res){//$ids,$ips,$function_name,$type,$content,$order_num
                    $this->addAppLog($request->input('admin_id'),$request->input('dediips'),'派工单('.$input['phoneType'].')','修改','办公地址');
                    return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
                }
            }elseif($request->input('is_type') == 4){
                $res1=AdminCertificate::where('admin_id',$request->input('admin_id'))->first();
                if($request->filled('cer_business')){
                    $file1=$request->input('cer_business');
                    /*if (preg_match('/(?<=\/)[^\/]+(?=\;)/',$file1,$pregR)) $streamFileType ='.' .$pregR[0];
                    $streamFileRand = time().str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                    $dir='./Uploads/admin/'.date('Ym').'/';
                    $upPath='./Uploads/admin/'.date('Ym').'/';
                    if(!is_dir($dir)){
                        mkdir($dir,0777,true);
                    }
                    $streamFilename = $upPath."/".$streamFileRand .$streamFileType;
                    //处理base64文本，用正则把第一个base64,之前的部分砍掉
                    preg_match('/(?<=base64,)[\S|\s]+/',$file1,$streamForW);
                    if (file_put_contents($streamFilename,base64_decode($streamForW[0]))===false){
                        return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                    }else{
                       // $streamFilename=trim($streamFilename,".");
                       // $arr_a['feedback_pic']='/.'.$streamFilename;
                        $streamFilename=trim($streamFilename,".");
                        $psos['cer_business']="/".$streamFilename;
                        if($res1){
                            $aa=ltrim($res1['ce_business'],'/');
                            // unlink($aa);
                            if(file_exists($aa)){
                                unlink($aa);
                            }
                            $res=AdminCertificate::where('admin_id',$request->input('admin_id'))->update($psos);
                        }else{
                            $psos['admin_id']=$request->input('admin_id');
                            $res=AdminCertificate::insert($psos);
                        }*/
                    /* $upPath='./Uploads/certificate';
                    $param['path'] = $upPath;
                    $param['file'] = $file1;//$this->ceshi_pic();
                    $param['type'] = 1;
                    $param['deletpath'] = $res1['ce_business']??'';
                    $curl_data = $this->curl_basepic(2,$param); */
                    //echo $curl_data;exit;
                    if($file1){
                       // $streamFilename = $file1;
                        $psos['cer_business'] = $file1;
                        if (isset($res1)){
                            $res = AdminCertificate::where('admin_id',$request->input('admin_id'))->update($psos);
                        }else{
                            $psos['admin_id'] = $request->input('admin_id');
                            $res = AdminCertificate::insert($psos);
                        }
                    }else{
                        return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                    }
                    if($res){
                        $this->addAppLog($request->input('admin_id'),$request->input('dediips'),'派工单('.$input['phoneType'].')','修改','营业执照');
                        return response()->json(['data'=>null,'desecption'=>'上传成功','state'=>1]);exit;
                    }else{
                        return response()->json(['data'=>null,'desecption'=>'失败','state'=>4]);exit;
                    }
                }else{
                    return response()->json(['data'=>null,'desecption'=>'请选择图片','state'=>5]);exit;
                }


            }elseif ($request->input('is_type') == 5){
                $res1=AdminCertificate::where('admin_id',$request->input('admin_id'))->first();
                //$file=$request->file('cer_account'); //开户许可证
                if($request->filled('cer_account')){
                    $file1=$request->input('cer_account');
                    /*if (preg_match('/(?<=\/)[^\/]+(?=\;)/',$file1,$pregR)) $streamFileType ='.' .$pregR[0];
                    $streamFileRand = time().str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                    $dir='./Uploads/admin/'.date('Ym').'/';
                    $upPath='./Uploads/admin/'.date('Ym').'/';
                    if(!is_dir($dir)){
                        mkdir($dir,0777,true);
                    }
                    $streamFilename = $upPath."/".$streamFileRand .$streamFileType;
                    //处理base64文本，用正则把第一个base64,之前的部分砍掉
                    preg_match('/(?<=base64,)[\S|\s]+/',$file1,$streamForW);
                    if (file_put_contents($streamFilename,base64_decode($streamForW[0]))===false){
                        return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                    }else{

                        $streamFilename=trim($streamFilename,".");
                        $psos['cer_account']="/".$streamFilename;
                        if($res1){
                            $aa=ltrim($res1['cer_account'],'/');
                            // unlink($aa);
                            if(file_exists($aa)){
                                unlink($aa);
                            }
                            $res=AdminCertificate::where('admin_id',$request->input('admin_id'))->update($psos);
                        }else{
                            $psos['admin_id']=$request->input('admin_id');
                            $res=AdminCertificate::insert($psos);
                        }
                        if($res){
                            $this->addAppLog($request->input('admin_id'),$request->input('dediips'),'派工单('.$input['phoneType'].')','修改','营业开户许可证','');
                            return response()->json(['data'=>null,'desecption'=>'上传成功','state'=>1]);exit;
                        }else{
                            return response()->json(['data'=>null,'desecption'=>'失败','state'=>4]);exit;
                        }
                    }*/
                 /*    $upPath='./Uploads/certificate';
                    $param['path'] = $upPath;
                    $param['file'] = $file1;//$this->ceshi_pic();
                    $param['type'] = 1;
                    $param['deletpath'] = $res1['cer_account']??'';
                    $curl_data = $this->curl_basepic(2,$param); */

                    if($file1){
                       // $streamFilename = $curl_data;
                        $psos['cer_account'] = $file1;
                        if (isset($res1)){
                            $res=AdminCertificate::where('admin_id',$request->input('admin_id'))->update($psos);
                        }else{
                            $psos['admin_id']=$request->input('admin_id');
                            $res=AdminCertificate::insert($psos);
                        }
                        if ($res){
                            $this->addAppLog($request->input('admin_id'),$request->input('dediips'),'派工单('.$input['phoneType'].')','修改','开户许可证');
                            return response()->json(['data'=>null,'desecption'=>'上传成功','state'=>1]);exit;
                        }else{
                            return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>2]);exit;
                        }
                    }else{
                        return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                    }
                    /*if(isset($curl_data)){
                        $curlData = json_decode($curl_data,true);
                        if($curlData['ErrorCode'] == 2){
                            return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                        }else{
                            $streamFilename = $curlData['Data']['streamFilename'];
                            $psos['cer_account'] = $streamFilename;
                            //$streamFilename = trim($streamFilename,'.');
                            //$psos['cer_business']=$streamFilename;
                            if ($res1){
                                $res=AdminCertificate::where('admin_id',$request->input('admin_id'))->update($psos);
                            }else{
                                $psos['admin_id']=$request->input('admin_id');
                                $res=AdminCertificate::insert($psos);
                            }
                        }
                    }*/
                }else{
                    return response()->json(['data'=>null,'desecption'=>'fail','state'=>5]);exit;
                }

            }elseif ($request->input('is_type') == 6){//地址修改
                //return 11;exit;
                if($request->input('admin_longitude') == '' || $request->input('admin_latitude') == ''){
                    return response()->json(['data'=>null,'desecption'=>'fail','state'=>3]);exit;
                }else{
                    $poss['admin_longitude'] = $request->input('admin_longitude');
                    $poss['admin_latitude'] = $request->input('admin_latitude');
                    $poss['admin_dressi'] = $request->input('admin_dressi');
                    $res = AdminInfor::where('admin_id',$request->input('admin_id'))->update($poss);
                    if($res){
                        $this->addAppLog($request->input('admin_id'),$request->input('dediips'),'派工单('.$input['phoneType'].')','绑定','门店坐标','');
                        return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
                    }else{
                        return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
                    }
                }
            }elseif ($request->input('is_type') == 7){//手机号修改

                $pp=PhoneCoke::where(['phc_coke'=>$request->input('phc_coke'),'phc_phone'=>$request->input('phc_phone')])->where('phc_expirationtime','>',date("Y-m-d H:i:s"))->first();
                //return $pp;exit;
                if(!$pp){
                    return response()->json(['data'=>null,'desecption'=>'验证码已失效','state'=>4]);exit;
                }
                $rea = AdminInfor::where('admin_id','!=',$request->input('admin_id'))->where('phone',$request->input('phc_phone'))->first();
                //return $rea;exit;
                if(!$rea){
                    $poss['phone']=$request->input('phc_phone');
                    $res = AdminInfor::where('admin_id',$request->input('admin_id'))->update($poss);
                    if($res){
                        $this->addAppLog($request->input('admin_id'),$request->input('dediips'),'派工单('.$input['phoneType'].')','修改','手机号码');
                        return response()->json(['data'=>null,'desecption'=>'手机号修改成功','state'=>1]);exit;
                    }else{
                        return response()->json(['data'=>null,'desecption'=>'手机号修改失败','state'=>2]);exit;
                    }
                }else{
                    return response()->json(['data'=>null,'desecption'=>'该手机号已注册','state'=>3]);exit;
                }
            }elseif ($request->input('is_type') == 8){ //邮箱
                $poss['email']=$request->input('email');
                $res=AdminInfor::where('admin_id',$request->input('admin_id'))->update($poss);
                if($res){
                    $this->addAppLog($request->input('admin_id'),$request->input('dediips'),'派工单('.$input['phoneType'].')','修改','邮箱');
                    return response()->json(['data'=>null,'desecption'=>'邮箱修改成功','state'=>1]);exit;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'邮箱修改失败','state'=>1]);exit;
                }
            }elseif ($request->input('is_type') == 9){ //QQ
                $poss['qq']=$request->input('qq');
                //dd($poss);
                $res=AdminInfor::where('admin_id',$request->input('admin_id'))->update($poss);
                if($res){
                    $this->addAppLog($request->input('admin_id'),$request->input('dediips'),'派工单('.$input['phoneType'].')','修改','QQ');
                    return response()->json(['data'=>null,'desecption'=>'QQ修改成功','state'=>1]);exit;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'QQ修改失败','state'=>2]);exit;
                }
            }else{
            	return response()->json(['data'=>null,'desecption'=>'修改类型不存在','state'=>6]);exit;
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>7]);exit;
        }
    }

    /**
     * 添加安装人
     * install_name :姓名		install_phone :电话		admin_id :安装中心id
     */
    public function Json_add_install(Request $request){
        //$admin_acc = Admin::where('id','618')->select('install_name')->first();
        //dd($admin_acc);
        //return $request->input("admin_id");exit;
        if($request->isMethod('post')){
            $input=$request->all(); //获取请求数据
            //判断参数
            if(empty($request->input('userName')) || empty($request->input('userPhone'))){
                return response()->json(['data'=>null,'desecption'=>'用户名和手机号不能为空','state'=>4]);exit;
            }
            if($request->input('userPass') <> $request->input('userPass1')){
                return response()->json(['data'=>null,'desecption'=>'两次密码输入不一致','state'=>6]);exit;
            }
            if($request->input('ser_type') == 1){
                $arr['install_pid'] = '0';//父id
                $list = InstallPerson::where(['admin_id'=>$input['admin_id'],'install_name'=>$input['userName'],'install_pid'=>$arr['install_pid'],'delet_y'=>1])->first();
                $all_show = Admin::where('id',$request->input('admin_id'))->value('all_show');
            }else{
                $adminid = InstallPerson::where('id',$input['admin_id'])->select('admin_id','install_pid','all_show')->first()->toArray();
                $all_show=$adminid['all_show'];
                $arr['install_pid']=$adminid['install_pid'].','.$input['admin_id'];
                $input['admin_id']=$adminid['admin_id'];
                $list=InstallPerson::where(['install_name'=>$input['userName'],'install_pid'=>$arr['install_pid'],'delet_y'=>1])->first();
            }
            if(!empty($list)){
                return response()->json(['data'=>null,'desecption'=>'该姓名和手机号已存在','state'=>5]);exit;
            }

            //dd($all_show);
            $check_code = InstallPerson::where('admin_id',$input['admin_id'])->where('check_code','>',10000000)->where('check_code','<',1000000000)->orderBy('check_code','desc')->limit(1)->value('check_code');
            $length = strlen($check_code);
            if(in_array($length,[8,9])){
                $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 = Certification::where('ser_id',$request->input('admin_id'))->value('certification_num');
                $check_code = InstallPerson::whereRaw("check_code like '".$certification_num."%'")->orderBy('check_code','DESC')->limit('1')->value("check_code");
                $length = strlen($check_code);
                if(in_array($length,[8,9])){
                    $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 {
                    $arr['check_code'] = $certification_num . "1001";
                }
            }
            //上传头像图片
            $file = $request->input('userPic');
            if($file){
                $arr['install_pic']= $file;
            }
            $arr['all_show']=$all_show;
            $arr['installation']=40;//安装费
            $input['userPass']=str_replace(' ','',$input['userPass']);
            $arr['admin_id']=$input['admin_id'];//所属服务中心id
            $arr['install_name']=$input['userName'];//安装人员姓名
            $arr['install_phone']=$input['userPhone'];//安装人员电话
            $arr['install_password']=md5($input['userPass']);//安装人员密码
            $arr['install_password1']=$input['userPass'];//安装人员原密码
            $arr['install_carid']=$input['userIDCard'];//安装人身份证号码
           // $arr['install_remark']=$input['userNote'];//安装人备注
            $arr['install_type']=$input['userWorkType'];//安装人类型 1：全职 2:兼职 3:转单
            $arr['install_is_type']=$input['userIsUsed'];//安装人员是否启用
            $arr['install_year']=$input['userYear'];//入职年份
            $arr['company_id']=$input['admin_id'];
            $rest=InstallPerson::insert($arr);
            if($rest){
                if($input['ser_type'] == 1){
                    //日志
                    $this->addAppLog($input['admin_id'],$request->input('dediips'),"安装人员(".$input['phoneType'].")",'添加技师','1');
                }else{
                    // 日志
                    $this->Add_PersonLog($input['admin_id'],$input['dediips'],"安装人员(".$input['phoneType'].")",'添加技师','1');
                    //$ids,$ips,$function_name,$type,$order_num
                }
                $data=['check_code'=>$arr['check_code'], 'id'=>$rest];
                return response()->json(['data'=>$arr['check_code'],'desecption'=>'添加成功','state'=>1]);exit;
            }else{
                return response()->json(['data'=>null,'desecption'=>'添加失败','state'=>2]);exit;
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'访问失败','state'=>3]);exit;
        }
    }

    //技师日志
    /**
     * @param $ids
     * @param $ips
     * @param $function_name
     * @param $type
     * @param $content
     * @param $order_num
     * @return mixed
     */
    private function Add_PersonLog($ids,$ips,$function_name,$type,$content,$order_num = ''){
        $admin_acc = DB::table('install_person')->where('id',$ids)->select('install_name')->first();
        $data['czrz_name']=$admin_acc['install_name'].'(技师)';
        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  添加备注
     * @param ser_type

     * @param serial_number 工单系统号
     * @param admin_id 登录id(服务中心id)
     * @param content 备注内容
     * @return json
     * @author he <2019.2.22>
     */
    public function Json_add_message(Request $request){
        //$a = DB::table('admin_infor')->where('admin_id','618')->first();
        //dd($a);
        if($request->isMethod('post')){
            $input=$request->all();
            if(empty($input['serial_number']) || empty($input['admin_id']) || empty($input['content'])){
                return response()->json(['data'=>null,'desecption'=>'参数不能为空','state'=>4]);exit;
            }
            if($request->input('ser_type') == 2){
                $admin_id=$input['admin_id'];
                $info = InstallPerson::where('id',$input['admin_id'])->first();
                $input['admin_id'] = $info['admin_id'];
                $input['content'] = $input['content'].'('.$info["install_name"].')';
                //return $info;exit;
            }else{
                $admin_id=0;
            }
            $list = OrderList::where('serial_number',$input['serial_number'])->select('sys_num','serial_number')->first();
           //dd($list);exit;
            $rest = $this->Message($input['admin_id'],$list['sys_num'],$input['content']."(".$list['serial_number'].")","派工单(App-android)",$admin_id);
            if($rest){
                if($rest == "失败"){
                    return response()->json(['data'=>null,'desecption'=>'添加备注失败','state'=>2]);exit;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'添加备注成功','state'=>1]);exit;
                }

            }else{
                return response()->json(['data'=>null,'desecption'=>'添加备注失败','state'=>5]);exit;
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);exit;
        }
    }

    // 首页订单显示数目
    /**
     * @name 首页显示订单数目
     * @param admin_id 服务商id
     * @param
     * @return json
     * @author he <2019.3.4>
     */
    public function Json_index_num(Request $request) {
        if($request->isMethod('post')){
            $input = $request->only('admin_id');
            $reminder =DB::table('ser_infor as a')->join('order_list as b','a.sin_serial','=','b.serial_number')->where(['sin_serid'=>$input['admin_id'],'sin_state'=>'1'])->where('stauas','<','34')->count();
            if($reminder < 1){

            }else{
                return response()->json(['data'=>null,'desecption'=>'有未处理催单记录','state'=>13]);exit;
            }
            $lidao = Admin::where('id',$input['admin_id'])->select('children_id','is_lidao','owner','ad_paper')->first()->toArray();
            if(!$lidao){
                return response()->json(['data'=>null,'state'=>'2','desecption'=>'参数错误']);
            }
            //dd($lidao);
            if($lidao['is_lidao']=='2' && $lidao['owner']=='1'){
                $lidaotype=1;
                $ser_ids = $input['admin_id'].','.$lidao['children_id'];
                $sql=" and ser_id in (".$ser_ids.")";
            }else{
                $lidaotype=2;
                $ser_ids="";
                $sql=" and ser_id='".$input['admin_id']."'";
            }
            //顶部显示
            $time=date("Y-m");//获取当前月份
           //$time='2018-12';

            $order_num = OrderList::whereRaw("create_time like'%".$time."%' and stauas != 5 and ser_id=".$input['admin_id'])->count();//派单量
            $install_num =DB::table('settlement_list')->whereRaw("setfeeds_time like'%".$time."%' and list_service_type>30 and list_service_type!=50 and list_service_type!=55 and ser_id=".$input['admin_id'])->count();//安装量
            $check_code =InstallPerson::where('admin_id',$input['admin_id'])->value('check_code');
            if (isset($check_code)){
                $evaluate = DB::table('install_evaluation')->whereRaw("ineva_time like '%".$time."' and ineva_coke=".$check_code."")->count();//客户评价
            }else{
                $evaluate = 0;
            }


            $sqlorderList='select count(1),stauas from gone_order_list where `invalid`=1 and is_delete=1 and line_status=1 and (create_time>"2016-08-01 00:00:01" or day_time>"2016-08-01 00:00:01")'.$sql.' group by stauas';

            $price=$this->Json_gain_price($time,$input['admin_id'],$lidaotype,$ser_ids);
            $money=0;
            foreach ($price as $kp=>$vp){
                $money=$money+$vp['price'];
            }
            $orderList_is = DB::select($sqlorderList);
            $one_num = 0;
            foreach($orderList_is as $k=>$v){
                // 可领取
                if($v['stauas']==10){
                    $one_num=$one_num+$v['count(1)'];
                    // 施工中
                }if($v['stauas']==20){
                    $one_num=$one_num+$v['count(1)'];
                    // 施工中
                }if($v['stauas']==30){
                    $two_num=$v['count(1)'];
                    // 待审核
                }if($v['stauas']==34){
                    //$three_num = $v['count(1)'];

                    $four_num  = $v['count(1)'];
                    // 已完成
                } /*if($v['stauas']==40){
                    $four_num=$v['count(1)'];
                    // 售后
                }if($v['stauas']==63){
                    $six_num=$v['count(1)'];
                    // 售后
                }if($v['stauas']==65){
                    $six_num=$six_num+$v['count(1)'];
                } */
            }

            $order_after = DB::table("order_after");

           // DB::connection()->enableQueryLog();

            $six_num = $order_after->whereRaw(str_replace("ser_id","deal_serid",rtrim(ltrim($sql," and "),' and store_type!=5'))." and status<30")->count();




            //催单记录
           // $cd_order = DB::table('ser_infor')->where(['sin_serid'=>$input['admin_id'],'sin_state'=>1])->count();

            $cd_order = DB::table('ser_infor as a')->join('order_list as b','a.sin_serial','=','b.serial_number')->where(['sin_serid'=>$input['admin_id'],'sin_state'=>'1'])->where('stauas','<','34')->count();


            if($lidaotype=='1'){
                $bill_num =DB::table('statements_list')->whereRaw("stl_type=1 AND stl_serid in (".$ser_ids.")")->count();
            }else{
                $bill_num=DB::table('statements_list')->whereRaw("stl_type=1 AND stl_serid='".$input['admin_id']."'")->count();
            }


            $manageapp_show = DB::table("manageapp_show");

            $app_id =  DB::table("manageapp")->whereRaw("app_type=2 and app_sort=2")->orderBy('app_time','DESC')->select('app_id','app_tittle')->first();
            if($app_id){

            	$push = $manageapp_show->whereRaw("map_appid='".$app_id['app_id']."' and map_serid='".$input['admin_id']."'")->value('map_id');

            	if($push){
            		$json['push'] = null;//首页推送
            	}else{
            		$json['push'] = $app_id['app_id'];//首页推送
            		$json['push_name'] = $app_id['app_tittle'];//首页推送
            	}
            }else{
            	$json['push'] = null;//首页推送
            }

			$json['comp_score'] = '--';//综合评分
			$json['service_score'] = '--';//服务评分
			$json['aging_score'] = '--';//时效评分
			$json['bad_review'] = '--';//差评数量
            $json['money'] = $money;//本月金额
            $json['dispatch_num'] = $order_num; //派单量
            $json['install_num'] = $install_num; //安装量
            $json['order_rate'] = '--'; //接单率
            $json['evaluate_num'] = $evaluate; //客户评价数量
            $json['complaints_rate'] = '--'; //客诉率
            $json['order_timeout'] = '--'; //接单超时
            $json['reminder_tate'] = '--'; //催单率

            $json['one_num'] = $one_num??'0'; //可领取订单数量
            $json['two_num'] = $two_num??'0'; //安装中订单数量
            $json['cd_num'] = $cd_order??'0'; //催单数量
            $json['four_num'] = $four_num??'0'; //待审核订单数量
            $json['bill_num'] = $bill_num??'0';//账单管理数量
            $json['six_num'] = $six_num??'0';//售后订单数量
            $json['ad_paper'] = $lidao['ad_paper']??'1';//白皮书签署情况
           // print_r(DB::getQueryLog());

            $refund_num = DB::table('refund')->where('ser_id',$input['admin_id'])->where('state',0)->count('id');

            $ticket_num = DB::table('ticket_list')->where('til_serid',$input['admin_id'])->where('til_state',1)->count('til_id');

            $evaluateForm_num = DB::table('evaluation_form')->where('ser_id',$input['admin_id'])->where('eva_status',3)->count('eva_id');

            $json['refund_num'] = $refund_num??0; //退款管理
            $json['ticket_num'] = $ticket_num??0;//扣款管理
            $json['evaluationForm_num'] = $evaluateForm_num??0;//客户评价管理

            return response()->json(['data'=>$this->intToStr($json),'state'=>'1']);
        }
    }

    //计算本月金额
    public function Json_gain_price ($time,$admin_id ,$lidaotype,$ser_ids){
        $type = DB::table('setmoney_type')->select('sety_id','sety_name')->get()->toArray();
        if($lidaotype=='1'){
            $subsidy_money = DB::table('settlement_list')->whereRaw("create_time like'%".$time."%' and  list_service_type=55 and `ser_id` in (".$admin_id.")")->sum('subsidy_money');
            $sql="SELECT SUM(`sem_price`) as price,b.sem_type FROM `gone_settlement_list` as a left join `gone_settlement_money` as b on a.id=b.sem_slid WHERE `setfeeds_time` like'%".$time."%' and `list_service_type`>30 and `list_service_type`!=50 and `list_service_type`!=55 and `ser_id` in (".$admin_id.") group by `sem_type`";
            //
        }else{
            $subsidy_money = DB::table('settlement_list')->whereRaw("create_time like'%".$time."%' and  list_service_type=55 and `ser_id`='".$admin_id."'")->sum('subsidy_money');

            $sql="SELECT SUM(`sem_price`) as price,b.sem_type FROM `gone_settlement_list` as a left join `gone_settlement_money` as b on a.id=b.sem_slid WHERE `setfeeds_time` like'%".$time."%' and `list_service_type`>30 and `list_service_type`!=50 and `list_service_type`!=55 and `ser_id`='".$admin_id."' group by `sem_type`";

        }

        $price = DB::select($sql);
        //dd($price);
        foreach( $price as $k => $v){
            $pricedata[$v['sem_type']]=$v['price'];
        }
        foreach( $type as $kt => $vt){
            //dump($kt);
            if($vt['sety_id']=='4'){
                $type[$kt]['price']=$subsidy_money?$subsidy_money:'0';
            }else{
                $type[$kt]['price']=$pricedata[$vt['sety_id']]??'0';
            }
        }
        return $type;

    }

    /**
     * @name  订单操作（获取安装人员）
     * @param admin_id
     * @param order_id
     * @param ser_type
     * @return json
     * @author he <2019.2.22>
     */
    public function Json_personnel(Request $request) {
        if($request->isMethod('post')){
            $input = $request->all(); //获取请求参数

            $after_id = $input['order_id'];


            if($request->input('state')=='12'){
                $serial_number = DB::table("order_after")->where('id',$input['order_id'])->value('serial_number');
                $input['order_id'] = OrderList::where('serial_number',$serial_number)->value('id');
            }
            $order_infor = OrderList::where('id',$input['order_id'])->select('ser_id','customer_id','install_id')->first();

            $ser_id = $order_infor['ser_id'];
            if($input['ser_type'] == 1){

            	if(isset($input['search_type']) && $input['search_type']=='after_list'){
            		//DB::connection()->enableQueryLog();
            		$af_install_id = DB::table("order_after")->where('id',$after_id)->value('install_id');
            		//echo $af_install_id;
            		//DB::connection()->enableQueryLog();
            		$list = InstallPerson::where(['admin_id'=>$input['admin_id'], 'install_is_type'=>'1','delet_y'=>'1', 'install_pid'=>'0','install_state'=>'1'])
		            		->where('id','!=',$af_install_id)
		            		->orderBy('id','desc')
		            		->get()->toArray();
            		//print_r(DB::getQueryLog());

            	}else{

	               // DB::connection()->enableQueryLog();
	                $list = InstallPerson::where(['admin_id'=>$input['admin_id'], 'install_is_type'=>'1','delet_y'=>'1', 'install_pid'=>'0','install_state'=>'1'])->where('id','!=',$order_infor['install_id'])->orderBy('id','desc')->get()->toArray();
	                //print_r(DB::getQueryLog());
	                //dd($list);
            	}

            }else{

                $install_id=DB::table('install_person')->where('id',$input['admin_id'])->first();
                //dd($install_id);
                $install_pid=$install_id['install_pid'].','.$install_id['id'];
                //dd($install_pid);
                $list=DB::table('install_person')->whereRaw("`admin_id`='".$ser_id."' AND `install_is_type`=1 AND `delet_y`=1 and (install_pid='".$install_pid."' or id='".$input['admin_id']."') and `install_state`=1 and id!='".$order_infor['install_id']."'")->orderBy('id','DESC')->get()->toArray();
                //$list = DB::table('install_person')->whereRaw("`admin_id`='".$ser_id."' AND `install_is_type`=1 AND `delet_y`=1 and (install_pid='".$install_pid."' or id='".$input['admin_id']."') and `install_state`=1 and id!='".$order_infor['install_id']."'")->get()->toArray();
            }
            //dd($list);
            if($list){
                foreach($list as $k=>$v){
                    $json[$k]['id']=$v['id'];//id
                    $json[$k]['ser_id']=$v['admin_id'];//安装中心id
                    $json[$k]['install_name']=$v['install_name'].'('.$v['check_code'].')';//安装人姓名
                }
                return response()->json(['data'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);exit;
            }else{
                return response()->json(['data'=>null,'desecption'=>'无更多技师请前往技师管理添加技师','state'=>2]);exit;
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);exit;
        }
    }

    /**
     * @name 获取当前服务中心下-安装人员列表
     * @param ser_type  1：服务商
     * @param admin_id  服务商id
     * @param page      页数
     * @return json
     * @author he <2019.2.22>
     */
    public function Json_Install_Person(Request $request) {

        if($request->isMethod('post')){
            $input =$request->only('ser_type','admin_id','page'); //获取请求参数
            $pagesize=10;
            $offset = ($input['page'] - 1) * $pagesize; //计算偏移量
            if($input['ser_type'] == 1){
                $list = InstallPerson::where(['admin_id'=>$input['admin_id'],'delet_y'=>'1','install_pid'=>'0'])->offset($offset)->limit($pagesize)->get()->toArray();
                //return $list;
            }else{
                $parentID = InstallPerson::where('id',$input['admin_id'])->value('install_pid');
                //dd($parentID);
                $parentID = $parentID.','.$input['admin_id'];
                //return $parentID;exit;
                $list = InstallPerson::where(['install_pid'=>$parentID, 'delet_y'=>'1'])->offset($offset)->limit($pagesize)->get()->toArray();
                //dd($list);
            }

            if($list){
                foreach ($list as $k=>$v){
                    $json[$k]['id']=$v['id'];//id
                    $json[$k]['install_state']=$v['install_state'];//在线状态
                    $json[$k]['install_name']=$v['install_name'];//安装人员姓名
                    $json[$k]['install_phone']=$v['install_phone'];//安装人员电话
                    $json[$k]['isUserd']=$v['install_is_type'];
                    $json[$k]['check_code']=$v['check_code'];//获取校验码
                    $json[$k]['install_remark']=$v['install_remark'];//备注
                    if($v['install_password']==''){
                        $json[$k]['password']='2';//获取校验码
                    }else{
                        $json[$k]['password']='1';//获取校验码
                    }
                    //dd($v['install_year']);
                    if($v['install_year']){
                        if(count(explode('-',$v['install_year'])) >='2') {
                            $year = date('Y') - explode('-', $v['install_year'])[0];
                            $mounth = date('m') - explode('-', $v['install_year'])[1];
                            if ($mounth == 0) {
                                $install_year = $year . "年";
                            }
                            if ($mounth > 0) {
                                $install_year = $year . "年-" . $mounth . "个月";
                            }
                            if ($mounth < 0) {
                                $install_year = ($year - 1) . "年-" . (12 + $mounth) . "个月";
                            }
                        }
                    }


                    $json[$k]['install_year']=$install_year??'0';//获取年嫌
                    $json[$k]['year']=$v['install_year']??'0';//获取年嫌
                    $json[$k]['install_type']=$v['install_type'];//服务类型
                    if($v['install_pic']!=''){
                        $json[$k]['install_pic']=$this->picurl($v['install_pic']);//头像
                    }else{
                        $json[$k]['install_pic']='';
                    }
                    $json[$k]['install_carid']=$v['install_carid'];//获取身份证号
                }
                return response()->json(['data'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);
            }else{
                return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>4]);
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);
        }
    }


    public function Json_install_detail(Request $request){
        $input = $request->only('id');
        $install = InstallPerson::where('id',$input['id'])->first()->toArray();
        //dd($install);

        if($install['install_year']){
            $yearl=$install['install_year'];
        }else{
            $yearl=substr($install['create_time'],0,10);
        }
        if(count(explode('-',$yearl)) >='2') {
            $year = date('Y') - explode('-', $yearl)[0];
            $mounth = date('m') - explode('-', $yearl)[1];
            if ($mounth == 0) {
                $install_year = $year . "年";
            }
            if ($mounth > 0) {
                $install_year = $year . "年-" . $mounth . "个月";
            }
            if ($mounth < 0) {
                $install_year = ($year - 1) . "年-" . (12 + $mounth) . "个月";
            }
        }

        if($install['install_pic']!=''){
            $json['install_pic']=$this->picurl($install['install_pic']);//头像
        }else{
            $json['install_pic']='';
        }

        $json['id']=$install['id'];//id
        $json['install_name']=$install['install_name'];//安装人员姓名
        $json['install_phone']=$install['install_phone'];//安装人员电话
        $json['isUserd']=$install['install_is_type'];
        $json['check_code']=$install['check_code'];//获取校验码
        $json['install_remark']=$install['install_remark'];//备注
        $json['install_year']=$install_year?? '0';//获取年嫌
        $json['year']=$install['install_year'];//获取年嫌
        $json['install_type']=$install['install_type'];//服务类型
        $json['install_carid']=$install['install_carid'];
        $json['install_password1']=$install['install_password1'];

        return response()->json(['data'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);
    }



    //测试图片上传
//    public function Ceshi(Request $request) {
//        $file=$request->file('ceshi'); //上传图片
//        //dd($file);exit;
//        if($file){
//            $filedir='./Uploads/admin/';
//            $imagesName=$file->getClientOriginalName();
//            $extension = $file -> getClientOriginalExtension(); //后缀
//            //dd($extension);
//            $allow=['jpg','gif','png','jpeg'];
//            if(in_array($extension,$allow)){
//                return response()->json(['data'=>null,'desecption'=>'不支持的图片格式','state'=>2]);exit; //图片格式无效
//            }
//            $newImagesName=time().rand(0,100).".".$extension;
//            $file->move($filedir,$newImagesName);
//            if(!$file->move($filedir,$newImagesName)){
//                return response()->json(['data'=>null,'desecption'=>'上传图片失败','state'=>3]);exit; //上传失败
//            }else{
//                $psos['admin_pic']="/".$filedir.$newImagesName;
//                 $aa=ltrim($res1,'/');
//                unlink($aa);
//                $res = Admin::where('id',$request->input('admin_id'))->update();
//                if($res){
//                    return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit; //上传失败
//                }else{
//                    return response()->json(['data'=>null,'desecption'=>'失败','state'=>4]);exit;
//                }
//            }
//        }
//    }

    /**
     * @name 启用、停用，修改，删除安装人员
     * @param is_type 1:启用，停用 2:修改 3：删除
     * @param id 用户id号
     * @param install_is_type 状态 1:启用 2:停用
     * @param userName
     * @return json
     * @author he <2019.2.22>
     */

    public function Json_Install_Oper(Request $request) {
        //$a =DB::table('install_person')->where('id','710')->first();
        //dd($a);
        //dd('11');exit;
        //$a =DB::table('install_person')->where('id','738')->first();
        //dd($a);
        if($request->isMethod('post')){
            //$input = $request->all();
            $input = $request->only('id','phoneType');
            if($request->input('is_type') == '1'){ //启用、停用
                //dd($input);
                $names = Admin::where('id',$input['id'])->value('admin_name');
                if($request->input('install_is_type')== '1'){
                    $arr['install_is_type']=1;//启用
                }else{
                    $names = InstallPerson::where('id',$input['id'])->value('install_name');
                    $arr['install_is_type']=2;//启用
                }
                //DB::connection()->enableQueryLog();
                $rest = InstallPerson::where('id',$input['id'])->update($arr);
               // print_r(DB::getQueryLog());

            }elseif ($request->input('is_type') == '2'){ //修改
                if($request->input('ser_type') == '1'){
                   $list = InstallPerson::where(['admin_id'=>$request->input('admin_id'),'install_name'=>$request->input('userName'),'install_pid'=>'0'])->where('id','!=',$request->input('userId'))->where('delet_y','!=','2')->first();
                }else{
                    $adminid = InstallPerson::where(['id'=>$request->input('admin_id')])->select('admin_id','install_pid')->first()->toArray();

                    $adminid = $adminid['install_pid'].','.$request->input('admin_id');//父id
                    $list =InstallPerson::where(['admin_id'=>$request->input('admin_id'),'install_name'=>$request->input('userName'),'install_pid'=>$adminid])->where('id','!=',$request->input('userId'))->where('delet_y','!=','2')->first();
                }
                if(!empty($list)){
                    return response()->json(['data'=>null,'desecption'=>'该姓名和手机号已存在','state'=>4]);exit;
                }
                //dd($list);
                //图片上传
                $file=$request->input('userPic'); //上传图片
                if($file){
                    /*if (preg_match('/(?<=\/)[^\/]+(?=\;)/',$file,$pregR)) $streamFileType ='.' .$pregR[0];
                    $streamFileRand = time().str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                    $dir='./Uploads/admin/'.date('Ym').'/';
                    $upPath='./Uploads/admin/'.date('Ym').'/';
                    if(!is_dir($dir)){
                        mkdir ($dir);
                    }
                    $streamFilename = $upPath."/".$streamFileRand .$streamFileType;
                    //处理base64文本，用正则把第一个base64,之前的部分砍掉
                    preg_match('/(?<=base64,)[\S|\s]+/',$file,$streamForW);
                    if (file_put_contents($streamFilename,base64_decode($streamForW[0]))===false){
                        return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                    }else{
                        $pic =InstallPerson::where('id',$request->input('userId'))->value('install_pic');
                        $aa=ltrim($pic,'/');
                        if(file_exists($aa)){
                            unlink($aa);
                        }
                        $arr['install_pic']='/.'.$streamFilename;

                    }*/
                 /*    $pic =InstallPerson::where('id',$request->input('userId'))->value('install_pic');
                    $upPath='./Uploads/install';
                    $param['path'] = $upPath;
                    $param['file'] = $file;//$this->ceshi_pic();
                    $param['deletpath'] = $pic??'';
                    $param['type'] = 1;
                    $curl_data = $this->curl_basepic(2,$param);
                    if($curl_data!='error'){
                        $streamFilename = $curl_data;
                        $arr['install_pic']= $streamFilename;

                    }else{
                        return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                    } */

                	$arr['install_pic']=$file;
                }


                $arr['install_name']=$request->input('userName');//安装人员姓名
                $arr['install_phone']=$request->input('userPhone');//安装人员电话
                $arr['install_carid']=$request->input('userIDCard');//安装人身份证号码
                //$arr['install_remark']=$request->input('userNote');//安装人备注
                $arr['install_type']=$request->input('userWorkType');//安装人类型
                $arr['install_is_type']=$request->input('userIsUsed');//安装人员是否启用
                if($request->input('userYear')!=""){
                    $arr['install_year']=substr($request->input('userYear'),0,7);//入职年份
                }
                if($request->input('userPass')!=''){
                    $input['userPass']=str_replace(' ','',$request->input('userPass'));
                    $arr['install_password']=md5($request->input('userPass'));//安装人员密码
                    $arr['install_password1']=$request->input('userPass');//安装人员原密码
                }
                //dd($arr);
                $rest = InstallPerson::where('id',$request->input('userId'))->update($arr);
            }elseif ($request->input('is_type') == '3'){ //删除
               $install_id = OrderList::where(['install_id'=>$request->input('id'), 'stauas'=>'30'])->first();
                if($install_id){
                    return response()->json(['data'=>null,'desecption'=>'访问方式不正确','state'=>5]);exit;
                }else{
                    $post['delet_y']=2;
                    $rest = InstallPerson::where('id',$request->input('id'))->update($post);
                }
            }
            if($rest) {
                if ($request->input('is_type') == '1') {
                    if ($request->input('install_is_type') == '1') {
                        $is_eng = '启用';
                    } else {
                        $is_eng = '停用';
                    }
                    if ($request->input('ser_type') == 1) {
                        // 日志
                        $this->addAppLog($request->input('admin_id'), $request->input('dediips'), "服务商(".$input['phoneType'].")", $is_eng,$request->input('dediips'));
                    } else {
                        // 日志
                        $this->Add_PersonLog($request->input('admin_id'), $request->input('dediips'), "安装人员(".$input['phoneType'].")", $is_eng, $request->input('dediips'));
                    }

                } else if ($request->input('is_type') == '2') {
                    if ($request->input('ser_type') == 1) {
                        // 日志
                        $this->addAppLog($request->input('admin_id'), $request->input('dediips'), "服务商(".$input['phoneType'].")", '修改',$request->input('dediips'));
                    } else {
                        // 日志
                        $this->Add_PersonLog($request->input('admin_id'), $request->input('dediips'), "安装人员(".$input['phoneType'].")", '修改', $request->input('dediips'));
                    }

                }else if($request->input('is_type')=='3'){
                    if($request->input('ser_type') == 1){
                        // 日志
                        $this->addAppLog($request->input('admin_id'),$request->input('dediips'),"服务商(".$input['phoneType'].")",'删除',$request->input('dediips'));
                    }else{
                        // 日志
                        $this->Add_PersonLog($request->input('admin_id'),$request->input('dediips'),"安装人员(".$input['phoneType'].")",'删除',$request->input('dediips'));
                    }
                }
                return response()->json(['data'=>null,'desecption'=>'保存成功','state'=>1]);exit;
            }else{
                return response()->json(['data'=>null,'desecption'=>'操作失败','state'=>2]);exit;
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);exit;
        }
    }

    /**
     * @name 金额明细
     * @param list_id 派工单编号
     * @return json
     * @author he <2019.2.25>
     */
    public function Json_money_detail(Request $request) {
        if($request->isMethod('post')) {
            $input = $request->only('list_id');
            $orsc_slid = DB::table('settlement_list')->where('list_id',$input['list_id'])->select('id','list_service_type')->first();
            $orsc_slid = CommonService::dataToArray($orsc_slid);
            $money_type = DB::table('setmoney_type')->pluck('sety_name','sety_id');
            //dd($orsc_slid['id']);exit;
            $num=0;
            if($orsc_slid['list_service_type']=="55"){
                $money = DB::table('settlement_money')->where(['sem_slid'=>$orsc_slid['id'],'sem_type'=>4])->value('sem_price');
                $json[$num]['money_type']=$money_type[4];
                $json[$num]['money']=$money;
            }else{
               // DB::connection()->enableQueryLog();#开启执行日志
                //$money = DB::table('settlement_money')->where('sem_slid',$orsc_slid['id'])->select('sem_type','sem_price')->get();
                $money = DB::table('settlement_money')->where('sem_slid',$orsc_slid['id'])->get();
                //print_r(DB::getQueryLog());
                //dd($money);exit;
                foreach( $money as $k => $v ){
                    $json[$num]['money_type']=$money_type[$k];
                    $json[$num]['money']=$money[$k];
                    $num=$num+1;
                }
            }
            return response()->json(['data'=>$json,'desecption'=>'成功','state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);exit;
        }

    }

    /**
     * @name 已出账单
     * @param admin_id 服务商id
     * @param limit 页数
     * @return json
     * @author he <2019.2.25>
     */
    public function Json_Order_Ybill(Request $request){
        $input = $request->only('admin_id','limit','stl_wat');
        if($input['admin_id']==""){
            return response()->json(['data'=>null,'desecption'=>'参数错误','state'=>4]);
        }
        $pts=DB::table('pt')->select('id','p_oname')->get()->toArray();
        $p_oname=[];
        foreach( $pts as $kpt => $vpt ){
            if($vpt['p_oname']==''){
                $p_oname[$vpt['id']]='速电救援';
            }else{
                $p_oname[$vpt['id']]=$vpt['p_oname'];
            }
        }

        $lidao = Admin::where('id',$input['admin_id'])->select('children_id','is_lidao','owner')->first()->toArray();
        if($lidao['is_lidao']=='2' && $lidao['owner']=='1'){
            $lidaotype=1;
            $ser_ids = $input['admin_id'].','.$lidao['children_id'];
            $sql="`stl_serid` in (".$ser_ids.")";
        }else{
            $lidaotype=2;
            $ser_ids="";
            $sql="`stl_serid`='".$input['admin_id']."'";
        }
        $where1=$sql;
        $sql1=" AND stl_type!=4";
        $group=" ORDER BY stl_type ASC,stl_startime DESC";
        if($input['limit']){
            $limit=($input['limit']-1)*10;
            $limits=" LIMIT ".$limit.",10";
        }
        if($request->input('stl_wat')){
            $sql1=" AND stl_wat='".$input['stl_wat']."'";
        }
        //
        $list = DB::table('statements_list')->whereRaw($where1.$sql1.$group.$limits)->select('stl_id','stl_wat','stl_startime','stl_endtime','stl_type','stl_money','stl_ticket')->get()->toArray();
        //dd($list);
        $listNums=DB::table('statements_list')->whereRaw($where1.$sql1)->count();
        if($list){
            foreach ($list as $k=>$v){
                $json[$k]['id'] = $v['stl_id']; //id号
                $json[$k]['serial_number'] = $v['stl_wat']; //结算单号
                $json[$k]['time'] = date('Y-m',strtotime($v['stl_startime']));
                $json[$k]['stl_money'] = $v['stl_money'];//账单金额
                $json[$k]['stl_ticket'] = '-'.$v['stl_ticket'];//处罚金额
                $json[$k]['stl_type'] = $v['stl_type'];
                $json[$k]['excel'] = "";
                $res=DB::table('settlement_list')->where('wat_num',$v['stl_wat'])->value('sett_status');
                if($res=='10'){
                    $json[$k]['pd_status']='1';
                }else{
                    $json[$k]['pd_status']='2';
                }

                /*if($v['stl_type']=="3"){
                    $json[$k]['whether_inv']=DB::table('service_center')->where('wat_num',$v['stl_wat'])->value("whether_inv");
                    if($json[$k]['whether_inv']==2 || $json[$k]['whether_inv']==1){
                        $json[$k]['whether_inv']="0";
                        $json[$k]['upload_pictures']="";
                    }
                    $upload_pictures=DB::table('pictures')->where('sett_wat_num',$v['stl_wat'])->value("upload_pictures");
                    if($upload_pictures!=""){
                        $json[$k]['upload_pictures']=$this->getUrl().$upload_pictures;
                    }else{
                        $json[$k]['upload_pictures']="";
                    }
                }else{
                    $json[$k]['whether_inv']="0";
                    $json[$k]['upload_pictures']="";
                }*/
                if($v['stl_type']=="3"){
                    $json[$k]['whether_inv']=DB::table('service_center')->where('wat_num',$v['stl_wat'])->value("whether_inv");
                    if($json[$k]['whether_inv']==2){
                        $json[$k]['whether_inv']="0";
                    }
                    $upload_pictures=DB::table('pictures')->where('sett_wat_num',$v['stl_wat'])->value("upload_pictures");
                    if($upload_pictures!=""){
                        $json[$k]['upload_pictures']=$this->picurl($upload_pictures);
                    }else{
                        $json[$k]['upload_pictures']="";
                    }
                }elseif($v['stl_type']=="4"){
                    $json[$k]['stl_type']="2";
                    $json[$k]['upload_pictures']="";
                    $json[$k]['whether_inv']="0";
                }elseif($v['stl_type']=="1"){
                    $json[$k]['upload_pictures']="";
                    $json[$k]['whether_inv']="0";
                }elseif($v['stl_type']=="2"){
                    $json[$k]['upload_pictures']="";
                    $json[$k]['whether_inv']=DB::table('service_center')->where('wat_num',$v['stl_wat'])->value("whether_inv");
                    if($json[$k]['whether_inv']==2){
                        $json[$k]['whether_inv']="0";
                    }
                }
            }
//             $json[0]['total']['count'] = $listNums;
            //$json['count'] = $listNums;
            return response()->json(['data'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);exit;
        }

        //return $list;exit;
    }

    /**
     * @name 已出账单详情
     * @param stl_wat 结算单号
     * @param admin_id 服务商id
     * @param limit 页数
     * @return json
     * @author he <2019.2.25>
     */
    public function Json_ybill_detail(Request $request){

        $input = $request->only('stl_wat','admin_id','limit');
        //return $input;die;
        $sta_info =DB::table('statements_list')->where(['stl_wat'=>$input['stl_wat'],'stl_serid'=>$input['admin_id']])->select('stl_ids','stl_money','stl_startime','stl_endtime')->first();
        if($request->input('limit')){
        	$limit=$input['limit']-1;
        	$limit=$limit*10;
        }else{
        	$limit=0;
        }
        $lists=DB::table('settlement_list')->whereRaw("id in (".$sta_info['stl_ids'].") and locked=1 and ser_id ='".$input['admin_id']."'")->select('list_id','sel_type','all_price','create_time','p_id','id','sel_type')->limit(5)->offset($limit)->get()->toArray(); //列表
        $arr=[];
        foreach ($lists as $ks=>$vs){
            $arr[]=$vs['list_id'];
        }
		if($limit==0){

	        $commonnum=DB::table('settlement_list')->whereRaw("id in (".$sta_info['stl_ids'].") and sel_type=1 and locked=1 and ser_id ='".$input['admin_id']."'")->count();//普通订单

	        $urgentnum=DB::table('settlement_list')->whereRaw("id in (".$sta_info['stl_ids'].") and sel_type=2 and locked=1 and ser_id ='".$input['admin_id']."'")->count();//加急订单
	        $nightnum=DB::table('settlement_list')->whereRaw("id in (".$sta_info['stl_ids'].") and sel_type=3 and locked=1 and ser_id ='".$input['admin_id']."'")->count();//夜间订单
	        $commonmoney=DB::table('settlement_list')->whereRaw("id in (".$sta_info['stl_ids'].") and locked=1 and ser_id ='".$input['admin_id']."'")->sum('all_price');//总金额
	        $ticketlist = DB::table('ticket_list')->whereIn('til_sernum',$arr)->where('til_creactime','<',$sta_info['stl_endtime'])->select('til_price','til_sernum')->get();
	        $ticketnum =DB::table('ticket_list')->whereIn('til_sernum',$arr)->where('til_creactime','<',$sta_info['stl_endtime'])->count();
	        $ticketmoney =DB::table('ticket_list')->whereIn('til_sernum',$arr)->where('til_creactime','<',$sta_info['stl_endtime'])->sum('til_price');
		}
        //return $arr;exit;
        //dd($lists);
        $pts=DB::table('pt')->select('id','p_oname')->get()->toArray();
        //dump($pts);die;
        $p_oname=[];
        foreach( $pts as $kpt => $vpt ){
        	if($vpt['p_oname']==''){
        		$p_oname[$vpt['id']]='速电快保';
        	}else{
        		$p_oname[$vpt['id']]=$vpt['p_oname'];
        	}
        }
        foreach ($lists as $k=>$v){
        	$json[$k]['p_name'] = $p_oname[$v['p_id']];//平台名称
            $json[$k]['serial_number'] =$v['list_id'];//工单号
            $json[$k]['all_price'] =$v['all_price'];//总金额
            $json[$k]['create_time']=date('m/d',strtotime($v['create_time']));
            $json[$k]['sel_type']=$v['sel_type'];
            $json[$k]['id']=$v['id'];
            //$json[$k]['orli_type']=$v['sel_type'];
			if($v['sel_type'] == '1'){
				$json[$k]['orli_type'] = '普通订单';
			}elseif($v['sel_type'] == '20'){
				$json[$k]['orli_type'] = '1小时订单';
			}elseif($v['sel_type'] == '10'){
				$json[$k]['orli_type'] = '夜间订单';
			}else{
				$json[$k]['orli_type'] = '普通订单';
			}

        }

//         foreach($ticketlist as $kt=>$vt){
//         	if($vt['til_sernum'] == $v['list_id']){
//         		$json[$k]['sel_type'] = '78';
//         		$json[$k]['all_price'] ='-'.$vt['til_price'];
//         	}
//         }

//         $re['total']['time']=$sta_info['stl_startime']."至".$sta_info['stl_endtime'];
//         $re['total']['nightnum']=$nightnum;
//         $re['total']['urgentnum']=$urgentnum;
//         $re['total']['commonnum']=$commonnum;
//         $re['total']['commonmoney']=$commonmoney?$commonmoney:"0.00";
//         $re['total']['ticketnum']=$ticketnum;
//         $re['total']['ticketmoney']=$ticketmoney?$ticketmoney:"0.00";
        if($limit==0){
	        $data['time']=$sta_info['stl_startime']."至".$sta_info['stl_endtime'];
	        $data['nightnum']=$nightnum;
	        $data['urgentnum']=$urgentnum;
	        $data['commonnum']=$commonnum;
	        $data['commonmoney']=$commonmoney?$commonmoney:"0.00";
	        $data['ticketnum']=$ticketnum;
	        $data['ticketmoney']=$ticketmoney?$ticketmoney:"0.00";
	        $data['sendnum'] = 0; //派送订单
        }
//         $data['comm']=$re;
        if($lists){
        	$data['list']=$json;
            return response()->json(['data'=>$this->intToStr($data),'desecption'=>'成功','state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>'无更多数据','state'=>2]);exit;
        }
    }

    /**
     * @name 未出账单
     * @param admin_id 服务商id
     * @param limit   页数
     * @return json
     * @author he <2019.3.1>
     */
    public function Json_order_wbill(Request $request){
        //dd('1');
        $input = $request->only('admin_id','limit','admin_name','user_phone','stl_wat','start_time','end_time');
        if($request->input('admin_id')==""){
            return response()->json(['data'=>null,'desecption'=>'参数错误','state'=>4]);
        }
        $pts=DB::table('pt')->select('id','p_oname')->get()->toArray();
        //dump($pts);die;
        $p_oname=[];
        foreach( $pts as $kpt => $vpt ){
            if($vpt['p_oname']==''){
                $p_oname[$vpt['id']]='速电快保';
            }else{
                $p_oname[$vpt['id']]=$vpt['p_oname'];
            }
        }
        $lidao = Admin::where('id',$input['admin_id'])->select('children_id','is_lidao','owner')->first()->toArray();
        //dd($lidao);
        if($lidao['is_lidao']=='2' && $lidao['owner']=='1'){
            $lidaotype=1;
            $ser_ids = $input['admin_id'].','.$lidao['children_id'];

            $ssql="ser_id in (".$ser_ids.")";
            $ssql1="stl_serid in (".$ser_ids.")";
        }else{
            $lidaotype=2;
            $ser_ids="";
            $ssql="ser_id='".$input['admin_id']."'";
            $ssql1="stl_serid='".$input['admin_id']."'";
        }
        $where=" AND ".$ssql;
        $time=DB::table('statements_list')->whereRaw($ssql1)->orderBy('stl_id', 'DESC')->value("stl_endtime");
        //dd($time);
        if($time==""){
            $startime='2016-08-01';
        }else{
            if($time==date('Y-m-d')){
                $startime=$time;
            }else{
                $startime=date('Y-m-d', strtotime(date($time)) + 86400);
            }
        }
        $endtime=date("Y-m-d");
        $sql="sett_status in (1,60,63) AND ((list_service_type=40 and setfeeds_time > '2016-08-01 00:00:01') or (list_service_type=55 and `create_time` > '".$startime." 00:00:01'))";
        $sqla="sett_status in (1,60,63) AND list_service_type=40 AND setfeeds_time > '2016-08-01 00:00:01'";
        $sqlb="sett_status in (1,60,63) AND `list_service_type`=55 AND `create_time` > '".$startime." 00:00:01'";
        $group=" ORDER BY sel_type DESC,id DESC";
        if($request->input('limit')){
            $limit=($input['limit']-1)*10;
            $limits=" LIMIT ".$limit.",10";
        }
        //结算单号
        /*if(!empty($request->input('stl_wat'))){
            $sql1=" AND stl_wat='".$input['stl_wat']."'";
        }*/
        // 客户姓名		客户电话
      /*   if(!empty($request->input('admin_name')) && empty($request->input('user_phone'))){

           // $user_sql="`shr_name`='".$input['admin_name']."'";
            $user_sql = "shr_name = ".$input['admin_name'];
        }else if(empty($request->input('admin_name')) && !empty($request->input('user_phone'))){
            $user_sql="`shr_phone`='".$input['user_phone']."'";
        }else{
           $user_sql="`shr_name`='".$request->input('admin_name')."' and `shr_phone`='".$request->input('user_phone')."'";

        } */
        // 开始时间		结束时间
        if(!empty($request->input('start_time')) && !empty($request->input('end_time'))){
            $sql=$sql." AND `create_time` >= '".$input['start_time']." 00:00:00' AND `create_time` <='".$input['end_time']." 23:59:59'";
        }else if(!empty($request->input('start_time')) && empty($request->input('end_time'))){
            $sql=$sql." AND `create_time` >= '".$input['start_time']." 00:00:00' AND `create_time` <='".date("Y-m-d")." 23:59:59'";
        }
        if($request->input('selKey')){
	        $selKey=array("2","3","4","5","6","7");
	        if(in_array($request->input('selKey'), $selKey)){
	            switch ($request->input('selKey')){
	                case '2'://一小时
	                    $orli_type=20;
	                    break;
	                case '3'://夜间
	                    $orli_type=10;
	                    break;
	                case '4'://正常
	                    $orli_type=1;
	                    break;
	                case '5'://40分钟
	                    $orli_type=15;
	                    break;
	                case '6'://90分钟
	                    $orli_type=25;
	                    break;
	                case '7'://两小时
	                    $orli_type=30;
	                    break;
	                default:
	                    break;
	            }

	            $sql=$sql." AND `sel_type`='".$orli_type."'";
	        }
        }
        $ticketlist=[];
        if($request->input('admin_name') || $request->input('user_phone')){

        	if(!empty($request->input('admin_name')) && empty($request->input('user_phone'))){

        		// $user_sql="`shr_name`='".$input['admin_name']."'";


        		$user_rest = DB::table('user')->where('shr_name',$input['admin_name'])->get()->toArray();
        	}else if(empty($request->input('admin_name')) && !empty($request->input('user_phone'))){
        		//$user_sql="`shr_phone`='".$input['user_phone']."'";
        		$user_rest = DB::table('user')->where('shr_phone',$input['user_phone'])->get()->toArray();
        	}else{

        		//$user_sql="`shr_name`='".$request->input('admin_name')."' and `shr_phone`='".$request->input('user_phone')."'";

        		$user_rest = DB::table('user')->where('shr_phone',$input['user_phone'])->where('shr_name',$input['admin_name'])->get()->toArray();

        	}



            //$user_rest=$user->where($user_sql)->select();
        	//DB::connection()->enableQueryLog();
           /// $user_rest = DB::table('user')->where($user_sql)->get()->toArray();
          //  print_r(DB::getQueryLog());


            if(empty($user_rest)){
            	return response()->json(['data'=>null,'desecption'=>'无此用户','state'=>2]);
            }

            $ids='';
            foreach($user_rest as $kk=>$vv){
                $ids.=$vv['id'].",";
            }
            if($request->input('limit')==1){
                $urgentnum=DB::table('settlement_list')->whereRaw($sqla." AND `customer_id` in (".trim($ids,",").")".$where." AND sel_type=20")->count();//加急

                $nightnum=DB::table('settlement_list')->whereRaw($sqla." AND `customer_id` in (".trim($ids,",").")".$where." AND sel_type=10")->count();//夜间

                $commonnum=DB::table('settlement_list')->whereRaw($sqla." AND `customer_id` in (".trim($ids,",").")".$where." AND sel_type=1")->count();//普通
                $commonmoney1=DB::table('settlement_list')->whereRaw($sqla." AND `customer_id` in (".trim($ids,",").")".$where)->sum("all_price");//
                $commonmoney2=DB::table('settlement_list')->whereRaw($sqlb." AND `customer_id` in (".trim($ids,",").")".$where)->sum("subsidy_money");
            }
            $list=DB::table('settlement_list')->whereRaw($sql." AND `customer_id` in (".trim($ids,",").")".$where.$group.$limits)->get()->toArray();
            $listNums=DB::table('settlement_list')->whereRaw($sql." AND `customer_id` in (".trim($ids,",").")".$where)->count();

        }else{
            if($request->input('limit')==1){
                $ticketlist=DB::table('ticket_list')->whereRaw("til_state<20  and til_serid='".$input['admin_id']."'")->orderBy('til_state','ASC')->orderBy('til_creactime','ASC')->get()->toArray();
                //dd($ticketlist);
                if($ticketlist){
                    foreach( $ticketlist as $kt => $vt ){
                        if($vt['til_watnum']==""){
                            $ticketlist[$kt]['til_watnum']="无";
                        }if($vt['til_wats']==""){
                            $ticketlist[$kt]['til_wats']="无";
                        }
                        if($vt['til_state'] == '1'){
                            $ticketlist[$kt]['orli_type']='新罚单';
                        }elseif($vt['til_state'] == '5'){
                            $ticketlist[$kt]['orli_type']='申诉中';
                        }elseif($vt['til_state'] == '10'){
                            $ticketlist[$kt]['orli_type']='已确认';
                        }
                        $ticketlist[$kt]['all_price']=$vt['til_price'];
                        $time=strtotime($vt['til_creactime'])+3*24*60*60;
                        $time1=time();
                        $time3=$time-$time1;
                        $ticketlist[$kt]['time']=(string)$time3;
                        if($time3>0){
                        }else{
                            if($vt['til_state']=='1'){
                                $ticketlist[$kt]['til_state']="10";
                            }
                        }
                    }
                    $ticketnum=count($ticketlist);
                    $ticketnum=(string)$ticketnum;
                    //dd($ticketnum);
                    $ticketmoney=DB::table('ticket_list')->whereRaw("til_state<20  and til_serid='".$input['admin_id']."'")->sum("til_price");
                    $ticketmoney=sprintf("%.2f",$ticketmoney);

                }else{
                    $ticketlist=[];
                }

                $urgentnum=DB::table('settlement_list')->whereRaw($sqla.$where." AND sel_type=20")->count();
                $nightnum=DB::table('settlement_list')->whereRaw($sqla.$where." AND sel_type=10")->count();
                $commonnum=DB::table('settlement_list')->whereRaw($sqla.$where." AND sel_type=1")->count();
                $commonmoney1=DB::table('settlement_list')->whereRaw($sqla.$where)->sum("all_price");
                $commonmoney2=DB::table('settlement_list')->whereRaw($sqlb.$where)->sum("subsidy_money");

            }
            $list=DB::table('settlement_list')->whereRaw($sql.$where.$group.$limits)->get()->toArray();
            $listNums=DB::table('settlement_list')->whereRaw($sql.$where)->count();
          // dd($ticketlist);
        }

        if($list) {
            foreach ($list as $k => $v) {
                $json[$k]['id'] = $v['id'];//id
                $json[$k]['p_name'] = $p_oname[$v['p_id']];//平台名称
                //$json[$k]['lock']=$v['locked'];
                $json[$k]['orli_type'] = $v['sel_type'];
                if ($v['sel_type'] == 1) {
                    $json[$k]['orli_type'] = '普通订单';
                } elseif ($v['sel_type'] == 10) {
                    $json[$k]['orli_type'] = '夜间订单';
                } elseif ($v['sel_type'] == 20) {
                    $json[$k]['orli_type'] = '1小时订单';
                }
                $json[$k]['now'] = date('Y年m月');
                //$json[$k]['is_schedule']='';
                $json[$k]['sel_type'] = $v['sel_type']; //1普通 2 一小时  3 夜间
                $json[$k]['serial_number'] = $v['list_id'];
                $json[$k]['create_time'] = date('m/d', strtotime($v['create_time']));//时间
                $json[$k]['all_price'] = $v['all_price']; //总价
                $json[$k]['total_nums'] = $listNums;// 订单总数
                if ($v['list_service_type'] == 55) {
                    $json[$k]['all_price'] = $v['subsidy_money'];
                } else {
                    $json[$k]['all_price'] = $v['all_price'];
                }

            }
        }
            if($ticketlist){
                foreach ($ticketlist as $kt=>$vt){
                    $jone[$kt]['serial_number']=$vt['til_ticnum'];
                    $jone[$kt]['sel_type']=78; //处罚

                    $jone[$kt]['til_id'] = $vt['til_id'];

                    $jone[$kt]['all_price']=$vt['til_price'];
                    $jone[$kt]['create_time']=date('m/d',strtotime($vt['til_creactime']));//$vt['til_creactime'];
                    $jone[$kt]['p_name']='速电快保';
                }
                //$js['total']['ticketnum']=$ticketnum;
                $js['ticketnum'] = $ticketnum;

               //$js['total']['ticketmoney']=$ticketmoney?$ticketmoney:"0.00";
                $js['ticketmoney']=$ticketmoney?$ticketmoney:"0.00";

            }else{

               // $js['total']['ticketnum']="0";
            	$js['ticketnum']="0";

                //$js['total']['ticketmoney']="0.00";
            	$js['ticketmoney']="0.00";
            }

            if($request->input('limit') == '1'){
            	$commonmoney1 = $commonmoney1??0;
            	$commonmoney2 = $commonmoney2??0;
                $commonmoney3=$commonmoney1+$commonmoney2;

                $urgentnum = $urgentnum??0;
                //$js['total']['urgentnum']=$urgentnum;
                $js['urgentnum']=$urgentnum; //1小时
                $nightnum = $nightnum??0;
               // $js['total']['nightnum']=$nightnum;
                $js['nightnum']=$nightnum;  //夜间

                $commonnum = $commonnum??0;
               // $js['total']['commonnum']=$commonnum;
                $js['commonnum']=$commonnum; //普通

                $js['sendnum'] = 0; //派送订单

                //$js['total']['installnum']=$install_num;
               // $js['total']['commonmoney']=$commonmoney3?$commonmoney3:"0.00";
                $js['commonmoney']=$commonmoney3?$commonmoney3:"0.00";

                //$js['total']['time']=$startime."至".$endtime;
                $js['time']=$startime."至".$endtime;
            }

       // if($list || $ticketlist){
            if($list){
            //$data['comm'] = $js;
            $data = $js;

            if($request->input('limit') == '1'){

                if($ticketlist){

                    $data['list'] = array_merge($jone,$json);
                }else{
                    $data['list']=$json;
                }
            }else{
                $data['list']=$json;
            }

            return response()->json(['data'=>$this->intToStr($data),'desecption'=>'成功','state'=>1]);exit;
            //return response()->json(['data'=>$json,'desecption'=>'成功','state'=>'1']);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>3]);exit;
        }

    }





    /**
     * @name 订单列表
     * @param admin_id
     * @param admin_name 客户姓名
     * @param limit
     * @param state 订单状态
     * @return json
     * @author he <2019.2.25>
     */
    public function Json_Order_List(Request $request){
        //return 1;exit;
        //$a = DB::table('order_list')->where('serial_number','P20190401093704868')->first();
        //dd($a);
        if($request->isMethod('post')){
            if(!in_array($request->input('state'),[1,2,3,4,5])){
                return response()->json(['data'=>null,'desecption'=>'参数错误','state'=>4]);exit;
            }
            $input = $request->only('admin_id','limit','state','admin_name','admin_phone','start_time','end_time','sel_key');
            $lidao = Admin::where('id',$input['admin_id'])->select('children_id','is_lidao','owner')->first()->toArray();
            if($lidao['is_lidao'] == '2' && $lidao['owner'] == '1'){
                $lidaotype=1;
                $ser_ids = $input['admin_id'].','.$lidao['children_id'];
                $ssql="ser_id in (".$ser_ids.")";
                $nodeaid = "note_adid in (".$ser_ids.")";
            }else{
                $lidaotype=2;
                $ser_ids="";
                $ssql="ser_id='".$input['admin_id']."'";
                //$ssql = ['ser_id'=>$input['admin_id']];
                $nodeaid = "note_adid = '".$input['admin_id']."'";
            }
            if($request->input('limit')){
                $offset =($input['limit']-1)*10; //($input['limit']-1)*10;
            }else{
                $offset =0;

            }
            //return 1;exit;
            if ($request->input('state') == '1'){
                $ssql.=" AND is_delete=1 AND (stauas=10 or stauas=20) AND invalid=1";
            }elseif($request->input('state') == '2'){
                $ssql.=" AND is_delete=1 AND line_status=2 AND stauas=30 AND invalid=1";
            }elseif($request->input('state') == '3'){
                $ssql.=" AND is_delete=1 AND stauas=30 AND  invalid=1 AND line_status=1";
            }elseif($request->input('state') == '4'){
                $ssql.=" AND is_delete=1 AND line_status=1 AND stauas=34 AND invalid=1";
            }elseif($request->input('state') == '5'){
                $ssql.=" AND is_delete=1 AND line_status=1 AND stauas>34 AND stauas !=50 AND stauas!=55 AND invalid=1";
            }

            if(!empty($request->input('admin_name')) && empty($request->input('user_phone'))){
                $ssql.=" AND `shr_name`='".$request->input('admin_name')."'";

            }elseif(empty($request->input('admin_name')) && !empty($request->input('user_phone'))){
                $ssql.=" AND `shr_phone`='".$request->input('user_phone')."'";

            }elseif(empty($request->input('admin_name')) && !empty($request->input('user_phone'))){
                //$arr=[];
            }else{

            }

            // 开始时间		结束时间
            if(!empty($request->input('start_time')) && !empty($request->input('end_time'))){
                $ssql.= " AND gone_a.create_time >= '".$request->input('start_time')." 00:00:00' AND gone_a.create_time <='".$request->input('end_time')." 23:59:59'";
            }elseif(!empty($request->input('start_time')) && empty($request->input('end_time'))){
                $ssql.=" AND gone_a.create_time >= '".$request->input('start_time')." 00:00:00' AND gone_a.create_time <='".date("Y-m-d")." 23:59:59'";
            }else{
                $ssql.=" AND (gone_a.create_time > '2016-08-01 00:00:01' or gone_a.day_time>'2016-08-01 00:00:01') ";
            }
            $selKey=array("2","3","4","5","6","7");
            if(in_array($request->input('selKey'), $selKey)){
                switch ($request->input('selKey')){
                    case '2'://一小时
                        $orli_type=20;
                        break;
                    case '3'://夜间
                        $orli_type=10;
                        break;
                    case '4'://正常
                        $orli_type=1;
                        break;
                    case '5'://40分钟
                        $orli_type=15;
                        break;
                    case '6'://90分钟
                        $orli_type=25;
                        break;
                    case '7'://两小时
                        $orli_type=30;
                        break;
                    default:
                        break;
                }

                $ssql.=" AND orli_type =".$orli_type;
            }
            //DB::connection()->enableQueryLog();
            $list =DB::table('order_list as a')->leftJoin('user as b','b.id','=','a.customer_id')->select('a.id','a.stauas','a.sys_num','a.serial_number','a.locklist_type','a.create_time','a.feeds_time','a.day_time','a.install_id','a.order_goods_id','a.orli_type','b.shr_name','b.shr_phone','b.shr_sheng','b.shr_shi','b.shr_xian','b.shr_adress','b.car_make','b.car_line','b.car_model','a.line_status')->whereRaw($ssql)->orderByRaw("FIELD(orli_type, 10,15,20,25,30,1)")->orderBy('a.create_time','DESC')->offset($offset)->limit('10')->get()->toArray();
            //print_r(DB::getQueryLog());
            if($list){
                $serm = '';
                $pic = '';
                foreach ($list as $k=>$v){
                    $serm .= "'".$v['serial_number']."',";
                    $pic .= "'".$v['install_id']."',";
                }

                $serm=rtrim($serm,',');
                $pic = rtrim($pic,',');

                $timeList =DB::table('order_time')->whereRaw("serial_number in (".$serm.")")->where('is_type','接单时间')->select('create_time','serial_number')->get()->toArray();

                if($timeList){
                    foreach ($timeList as $ks=>$vs){
                        $timeArr[$vs['serial_number']]=$vs['create_time'];
                        $serial_number[]=$vs['serial_number'];
                    }
                    foreach ($list as $ks=>$vs){
                        //if($serial_number){
                            if(in_array($vs['serial_number'],$serial_number)) {
                                $list[$ks]['ricvetime'] =$timeArr[$vs['serial_number']];
                            }else{
                                $list[$ks]['ricvetime']=date('Y-m-d h:i:s');
                            }
                       // }

                    }
                }

                //头像
                $picList = DB::table('install_person')->whereRaw("id in (".$pic.")")->select('id','install_pic','install_name','check_code')->get()->toArray();
                //dump($picList);
                if($picList){
                    foreach ($picList as $kp=>$vp){
                        $picArr[$vp['id']]=$vp;
                        $picNull[]=$vp['id'];
                    }
                }else{
                    $picNull=[];
                }

                foreach ($list as $kq=>$vq){

                    if ($vq['stauas'] == '10'){
                        $list[$kq]['shr_phone'] = substr_replace($vq['shr_phone'], '****', 3, 4);
                    }
					$goods_name = DB::table('order_replace')->where('or_serialnum',$vq['serial_number'])->where('deal_state','1')->orderBy('creact_time','DESC')->select('or_goodname','deal_state','deal_price','or_goodnum')->first();
	                if ($goods_name){
	                    $list[$kq]['goods_name']=$goods_name['or_goodname'];
	                    $list[$kq]['deal_state']=$goods_name['deal_state']??0;
	                    $list[$kq]['deal_price']=$goods_name['deal_price']??0;
	                    $list[$kq]['goods_num']=$goods_name['or_goodnum']??0;
	                }else{
	                    $goods_name=DB::table('order_msg')->where('id',$vq['order_goods_id'])->select('goods_name','goods_num')->first();
	                    $list[$kq]['goods_name']=$goods_name['goods_name']??'暂无';
	                    $list[$kq]['goods_num']=$goods_name['goods_num']??'0';
	                    $list[$kq]['deal_state']=0;
	                }

                    if(in_array($vq['install_id'],$picNull)){
                        $pic =$picArr[$vq['install_id']]['install_pic']??'';
                        if($pic){
                            $list[$kq]['ins_pic'] = $this->picurl($pic);
                        }else{
                            $list[$kq]['ins_pic'] = '';
                        }

                        $list[$kq]['ins_name']=$picArr[$vq['install_id']]['install_name']??'';
                        $list[$kq]['ins_code']=$picArr[$vq['install_id']]['check_code']??'';
                    }else{
                        $list[$kq]['ins_pic']='';
                        $list[$kq]['ins_name']='';
                        $list[$kq]['ins_code']='';
                    }

                    $note_num = DB::table('note')->whereRaw("`orders_id`='".$vq['sys_num']."' AND `public_state`=2 AND (note_group!=2 or note_adid='".$input['admin_id']."')")->count();
                    if($note_num){
                        $list[$kq]['note_num'] = $note_num;
                    }else{
                        $list[$kq]['note_num'] = 0;
                    }
                    //$list[$kq]['create_time'] ='2021-06-18 10:25:26';
                }

               $json=$list;
                return response()->json(['data'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);exit;
            }else{
                return response()->json(['data'=>null,'desecption'=>'无数据','state'=>2]);exit;
            }

        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);exit;
        }
    }

    /**
     * @name 订单详情
     * @serial_number 派工单号
     * @param limit
     * @param state 1：订单信息 2：订单记录 3：订单资料
     * @return json
     * @author he <2019.2.26>
     */
    public function Json_order_details(Request $request) {
        if($request->isMethod('post')) {
            $input = $request->only('serial_number','after_num','state','admin_id');
            //$a =OrderList::where('serial_number',$input['serial_number'])->first();
            //dd($a);
            $line_state =DB::table('install_line')->where('line_serm',$input['serial_number'])->first(); //接受，出发，抵达，作业，完成

            DB::connection()->enableQueryLog();
            $info = OrderList::where(['is_delete'=>'1'])->where('serial_number',$input['serial_number'])->select('id','sys_num','serial_number','locklist_type','order_num','create_time','feeds_time','day_time','customer_id','goods_id','ser_id','install_id','stauas','order_goods_id','p_id','line_status')->first();
            //print_r(DB::getQueryLog());exit;
            if(empty($info)){
                return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
            }
            $info=$info->toArray();
            if($request->has('after_num')){//判断是否为售后单
                $afterInfo = DB::table('order_after')->where('after_num',$input['after_num'])->select('create_time','deal_time','status')->first();
                $info['aft_create_time'] = $afterInfo['create_time'];
                $info['aft_deal_time'] = $afterInfo['del_time']??'';
                $info['aft_status'] = $afterInfo['status'];
            }
            //dd(DB::getQueryLog());
            //商品修改 ---------------------------
            //$goods_name = DB::table('order_replace')->where('or_serialnum',$info['serial_number'])->where('deal_state','1')->orderBy('creact_time','DESC')->select('or_goodname','deal_state','deal_price')->limit('1')->first();
            //if($goods_name){
            //    $info['ordermsg']['goods_name'] = $goods_name['or_goodname'];
            //    $info['ordermsg']['deal_state'] = $goods_name['deal_state'];
            //    $info['ordermsg']['deal_price'] = $goods_name['deal_price'];
            //}else{
            //    $goods_name=DB::table('order_msg')->where('id',$info['order_goods_id'])->value('goods_name');
            //    $info['ordermsg']['goods_name']=$goods_name??'暂无';
            //    $info['ordermsg']['deal_state']=0;

            //}user
			$goods_name = DB::table('order_replace')->where('or_serialnum',$info['serial_number'])->where('deal_state','1')->orderBy('creact_time','DESC')->select('or_goodname','deal_state','deal_price','or_goodnum')->first();
            if ($goods_name){
                $info['goods_name']=$goods_name['or_goodname'];
                $info['deal_state']=$goods_name['deal_state']??0;
                $info['deal_price']=$goods_name['deal_price']??0;
                $info['goods_num']=$goods_name['or_goodnum']??0;
            }else{
                $goods_name=DB::table('order_msg')->where('id',$info['order_goods_id'])->select('goods_name','goods_num')->first();
                $info['goods_name']=$goods_name['goods_name']??'暂无';
                $info['goods_num']=$goods_name['goods_num']??'0';
                $info['deal_state']=0;
            }
			$user = DB::table('user')->where('id',$info['customer_id'])->select('shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress')->first();
            $info['shr_name'] = $user['shr_name'];

            if ($info['stauas'] == '10'){
            	 $info['shr_phone'] = substr_replace($user['shr_phone'], '****', 3, 4);
            }else{
            	$info['shr_phone'] = $user['shr_phone'];

            }
           // $info['shr_phone'] = $user['shr_phone'];



            $info['shr_sheng'] = $user['shr_sheng'];
            $info['shr_shi'] = $user['shr_shi'];
            $info['shr_xian'] = $user['shr_xian'];
            $info['shr_adress'] = $user['shr_adress'];
            $company_name = Admin::where('id',$info['ser_id'])->select('company_name')->first();
            $p_oname = DB::table('pt')->where('id',$info['p_id'])->value('p_oname');
            //承接服务

            //汽车车牌
            $plate = DB::table('carplate_info')->where('or_number',$info['serial_number'])->select('or_number','can_plate','vehicleID','bar_code')->first();
            //车辆信息
            $zt_sid =DB::table('zt_bml')->where(['zt_vehicle'=>$plate['vehicleID']])->value('zt_sid');
            $xinghao = DB::table('pj_carmatnew')->where('pjc_id',$zt_sid)->first();


            //技师
            $person =DB::table('install_person')->where(['id'=>$info['install_id']])->select('id as install_id','install_name','install_phone','install_year','install_type','install_pic','check_code')->first();
            $orsc_slid=DB::table('settlement_list')->where('list_id',$input['serial_number'])->select('id','list_service_type')->first();
            //dd($orsc_slid);30
            $money_type=DB::table('setmoney_type')->pluck('sety_name','sety_id')->toArray();
            //dump($money_type);
            //dd($info['stauas']);
            if($info['stauas'] == '10'){
                $supply_price = DB::table('gh_price')->where(['goods_id'=>$info['goods_id'],'ser_id'=>'0'])->orderBy('id',"DESC")->value('supply_price');
                if(!$supply_price){
                    $supply_price='0';
                }
                $info['supply_price']=$supply_price;
            }else{
                $num=0;
                $countMoney=0;
                if($orsc_slid['list_service_type']=="55"){
                    $money=DB::table('settlement_money')->where(['sem_slid'=>$orsc_slid['id'],'sem_type'=>'4'])->value('sem_price');
                    $my[$num]['money_type']=$money_type[4];
                    $my[$num]['money']=$money;

                }else{
                    $my=DB::table('settlement_money')->where('sem_slid',$orsc_slid['id'])->pluck('sem_price','sem_type')->toArray();
                    //dd($my);
                    foreach( $my as $k => $v ){
                        $countMoney=$countMoney+$v;
                        if($k != '0'){
                            $m[$num]['money_type']=$money_type[$k];
                            //dump($k);
                            $m[$num]['money']=$my[$k];
                            $num=$num+1;
                        }
                    }
                    //dd($m);
                }
            }


            if($person['install_year'] == ""){
                $year="未登记";
            }else{
                if(count(explode('-',$person['install_year'])) >='2'){
                    $install_year=explode('-',$person['install_year']);
                    $year=date('Y')-$install_year[0];
                    $mounth=date('m')-$install_year[1];
                    if($mounth>0){
                        $year=$year+1;
                    }
                    $year=$year."年技师";
                }else{
                    $year ='未登记';
                }


            }
            if($person['install_pic']==""){

            }else{
                $person['install_pic']=$this->picurl($person['install_pic']);
            }
            //评分
           /* $scores = DB::table('install_score')->where('inscore_serial',$info['serial_number'])->select('inscore_grade','inscore_type')->get()->toArray();

            //综合评分
            $ineva_score = DB::table('install_evaluation')->where('ineva_serial',$info['serial_number'])->value('ineva_score');*/

            $score=DB::table('order_score')->where('orsc_sernum',$info['serial_number'])->select('orsc_grade','orsc_type')->get()->toArray();

            $scores['fen1'] = $score[0]['orsc_grade']??'0';
            $scores['fen2'] = $score[1]['orsc_grade']??'0';

            $scores['fen3'] = '5';

            $ineva_score = ($scores['fen1']+$scores['fen2']+$scores['fen3'])/3;
            $timeList =DB::table('order_time')->where('serial_number',$info['serial_number'])->where('is_type','接单时间')->select('create_time','serial_number')->first();

            $info['company_name']=$company_name['company_name']??'速电快保';

            $info['plate'] = $plate['can_plate']??'未知';//车牌号
            $info['year']=$year??''; //技师年限
            //车辆信息

            if($xinghao){
                $info['carinfo'] = $xinghao['car_series'].$xinghao['car_year'].$xinghao['car_model'].$xinghao['car_models'];//车辆信息
            }else{
                $info['carinfo'] ='未知';
            }
            $info['bar_code']=$plate['bar_code']??''; //条形码
            $info['or_number'] = $plate['or_number']??'未知';
            $info['can_plate'] = $plate['can_plate']??'未知'; //车牌号

            $info['countMoney']=$countMoney??'0';
            $info['moneys'] = $m??[];
            $info['p_oname'] = $p_oname??'速电平台';//订单来源
            $info['service_name']='换电瓶'; //服务项目
            $info['parentname']='速电快保-承接服务';//承接服务
            //技师plate
            $info['install_id']=$person['install_id']??'';
            $info['install_name']=$person['install_name']??'';
            $info['install_phone']=$person['install_phone']??'';
            $info['install_year']=$person['install_year']??'';
            $info['install_type']=$person['install_type']??'';
            $info['install_pic']=$person['install_pic']??'';
            $info['check_code']=$person['check_code']??'';
            //综合评分
            $info['ineva_score'] =$ineva_score??'1';
            $info['ineva_score']=sprintf("%.1f",$info['ineva_score']);//评分
            $info['jd_time']=$timeList['create_time']??date('Y-m-d h:i:s');
            //评分
            $info['scores'] =$scores;
            $info['line_state']=$line_state['line_state']?? '1';



            $note_num = DB::table('note')->whereRaw("`orders_id`='".$info['sys_num']."' AND `public_state`=2 AND (note_group!=2 or note_adid='".$input['admin_id']."')")->count();
            if($note_num){
                $info['note_num'] = $note_num;
            }else{
                $info['note_num'] = 0;
            }



            //获取客户地址
            $jingwei =$this->jingwei($info['shr_sheng'],$info['shr_sheng'].$info['shr_shi'].$info['shr_xian'].$info['shr_adress']);
            $info['jingwei']=$jingwei;
            if($info){
                return response()->json(['data'=>$this->intToStr($info),'desecption'=>'成功','state'=>1]);exit;
            }else{
                return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);exit;
        }
    }


    /**
     * @name 订单详情订单记录
     * @serial_number
     * @param state
     * @param sin_type
     * @return json
     * @author he <2019.3.19>
     */
    public function Json_order_record(Request $request){
        //$timeList = DB::table('order_time')->where('serial_number',$request->input('serial_number'))->get()->toArray();
        $serial_number =$request->input('serial_number');
        $sql="select max(create_time) as time,is_type from gone_order_time where serial_number = '".$serial_number."' and is_type != '起始时间' and is_type != '下单时间' group by is_type order by create_time asc";
        $timeList =DB::select($sql);
        //dump($timeList);
        $arr = [];
        $info=[];
        if($timeList){
            foreach ($timeList as $k=>$v){
                switch ($v['is_type']){
                    case '派单时间':
                        $info['pd_time'] = $v['time'];
                        break;
                    case '接单时间':
                        $info['jd_time'] = $v['time'];
                        break;
                    case '安装预约时间':
                        $info['yy_time'] = $v['time'];
                        break;
                    case '出发时间':
                        $info['cf_time'] = $v['time'];
                        break;
                    case '抵达时间':
                        $info['dd_time'] = $v['time'];
                        break;
                    case '作业时间':
                        $info['zy_time'] = $v['time'];
                        break;
                    case '任务反馈时间':
                        $info['fk_time'] = $v['time'];
                        break;
                    case '完成时间':
                        $info['wc_time'] = $v['time'];
                        break;
                }
            }
            //dump($info);
            foreach ($timeList as $k=>$v){
                /*if($v['is_type'] == '派单时间'){
                    $arr[$k]['top_time']=$v['time'];
                    $arr[$k]['name']='系统派单！';
                    $arr[$k]['type']='派单时间：';
                    $arr[$k]['time_type']=$v['time'];
                }else*/
                if($v['is_type'] == '接单时间'){
                    $arr[$k]['top_time']=$v['time'];
                    $arr[$k]['name']='接受订单';
                    $arr[$k]['type']='接单耗时';
                    $type =$this->time_diff($info['pd_time'],$info['jd_time']);
                    $arr[$k]['time_type']=$type;
                }elseif($v['is_type'] == '抵达时间'){
                    $arr[$k]['top_time']=$v['time'];
                    $arr[$k]['name']='抵达客户位置，开始作业！';
                    $arr[$k]['type']='路程耗时';
                    $type =$this->time_diff($info['cf_time'],$info['dd_time']);
                    $arr[$k]['time_type']=$type;
                }elseif($v['is_type'] == '任务反馈时间'){
                    $arr[$k]['top_time']=$v['time'];
                    $arr[$k]['name']='反馈时间';
                    $arr[$k]['type']='反馈耗时';
                    $type =$this->time_diff($info['cf_time'],$info['fk_time']);
                    $arr[$k]['time_type']=$type;
                }else{
                    $arr[$k]['top_time']=$v['time'];
                    $arr[$k]['name']=$v['is_type'];
                    $arr[$k]['type']=$v['is_type'];
                    $arr[$k]['time_type']=$v['time'];
                }
            }
            return response()->json(['data'=>$arr,'desecption'=>'成功','state'=>1]);
        }else{
            return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);
        }
    }

    /**计算时间 天、时、分、秒
     * @param $begin_time
     * @param $end_time
     * @return string
     */
    protected function time_diff($begin_time,$end_time){
        if(!$begin_time && !$end_time){
            return '00天00时00分00秒';
        }
        $begin_time=strtotime($begin_time);
        $end_time=strtotime($end_time);
        if($begin_time < $end_time){
            $starttime = $begin_time;
            $endtime = $end_time;
        }else{
            $starttime = $end_time;
            $endtime = $begin_time;
        }

        //计算天数
        $timediff = $endtime-$starttime;
        $days = intval($timediff/86400)??'00';
        //计算小时数
        $remain = $timediff%86400;
        $hours = intval($remain/3600)??'00';
        //计算分钟数
        $remain = $remain%3600;
        $mins = intval($remain/60)??'00';
        //计算秒数
        $secs = $remain%60??'00';
        return $days.'天'.$hours.'时'.$mins.'分'.$secs.'秒';
    }

    /**
     * @name 查看上传的图片或音频
     * @serial_number 派工单号
     * @param limit 页数
     * @param state 状态
     * @param sin_type  信息类型 1：催单
     * @return json
     * @author he <2019.2.26>
     */
    public function LookPicOrAudio(Request $request){
        //dd('11');
        $input = $request->only('serial_number');
        $order_id = OrderList::where('serial_number',$input['serial_number'])->value('id');
        $array = array('img1'=>'','img2'=>'','img3'=>'','img4'=>'','img5'=>'');
        $data = array('images'=>$array,'voice'=>array());
        $picArr = DB::table('feedback')->where('gl_id',$order_id)->get()->toArray();
        //dd($picArr);
        $audioArr = DB::table('feedsound')->where('gl_id',$order_id)->get()->toArray();
       // dd($audioArr);
        foreach($picArr as $key=>$val){
            switch($val['type']){
                case 5:
                    $array['img5'] = $this->picurl($val['feedback_pic']);
                    break;
                case 3:
                    $array['img3'] = $this->picurl($val['feedback_pic']);
                    break;
                case 1:
                    $array['img1'] = $this->picurl($val['feedback_pic']);
                    break;
                case 7:
                    $array['img4'] = $this->picurl($val['feedback_pic']);
                    break;
                case 2:
                    $array['img2'] = $this->picurl($val['feedback_pic']);
                    break;
            }
        }

        $bar_code = DB::table('carplate_info')->where('or_number',$input['serial_number'])->where('bar_code','!=','')->orderBy('can_id','DESC')->value('bar_code');
        $data['bar_code'] = $bar_code ? $bar_code : '';
        foreach($audioArr as $key=>$val){
            $arr=ltrim($val['feedback_sound'],'/.');

            $data['voice'][] = array('baseed'=>$this->getUrl().'/'.$arr,'record_Lang'=>$val['sound_length'],'record_time'=>$val['install_time']);
        }

        $data['images'] = $array;//图片
        if($data){
            return response()->json(['data'=>$this->intToStr($data),'desecption'=>'成功','state'=>1]);
        }else{
            return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);
        }

    }

    /**
     * @name 催单列表
     * @admin_id 派工单号
     * @param limit 页数
     * @param state 状态
     * @return json
     * @author he <2019.2.26>
     */
    public function Json_Ser_Infor(Request $request) {
        if ($request->isMethod('post')){
            $input = $request->only('state','limit','admin_id');
            if($input['state']=='1'){
                $state="sin_state='1' and stauas<34"; // sin_state 1未处理；2：已处理；3：已审核',
            }else{
                $state="sin_state>'1' and stauas<34";
            }
            if($input['limit']){
                $limit = ($input['limit']-1)*10;
                //$limits=" LIMIT ".$limit.",10";
            }else{
                $limit = 0;
                //$limits=" LIMIT 0,10";
            }
            $state.=" AND sin_serid=".$input['admin_id']."";
            //DB::connection()->enableQueryLog();#开启执行日志

            $res = DB::table('ser_infor as a')->join('order_list as b','a.sin_serial','=','b.serial_number')->whereRaw($state)->orderBy('sin_creactime','DESC')->offset($limit)->limit('10')->get()->toarray();

            if(!empty($res)){
            	foreach ($res as $k =>$v){
            		$rusers = DB::table('user')->where('id',$v['customer_id'])->select('shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress')->first();
            		$res[$k]['shr_name'] = $rusers['shr_name'];
            		$res[$k]['shr_phone'] = $rusers['shr_phone'];
            		$res[$k]['shr_sheng'] = $rusers['shr_sheng'];
            		$res[$k]['shr_shi'] = $rusers['shr_shi'];
            		$res[$k]['shr_xian'] = $rusers['shr_xian'];
            		$res[$k]['shr_adress'] = $rusers['shr_adress'];

            		$goods = DB::table('order_msg')->where('id',$v['customer_id'])->select('goods_name','goods_num')->first();
            		$res[$k]['goods_num'] = $goods['goods_num'];
            		$res[$k]['goods_name'] = $goods['goods_name'];

            	}

                return response()->json(['data'=>$this->intToStr($res),'desecption'=>'成功','state'=>1]);;exit;
            }else{
                return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);;exit;
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);;exit;
        }


    }

    /**
     * @name 售后订单（售后列表）
     * @param type 1:服务商登录 2：技师登录
     * @param state  售后单状态 1:未处理 2:处理中 3:审核中 4:已完成
     * @param limit 页码
     * @return json
     * @author he <2019.3.5>
     */

    public function After_list(Request $request){

        $input = $request->only('admin_id','state','limit');

        $where = "deal_serid='".$input['admin_id']."'";


        switch ( $input['state'] )
        {
            case 1:
                $where.=" and status=1";
                break;
            case 2:
                $where.=" and status=10";
                break;
            case 3:
                $where.=" and status=30";
                break;
            case 4:
                $where.=" and status=40";
                break;
        }

        if($input['limit']){
            $limit=($input['limit']-1)*10;
        }else{
            $limit=0;
        }

        if($request->input('type') == 2){
        	$where.=" and install_id=". $input['admin_id'];
        }

        $where .= " and store_type!=5";

        //DB::connection()->enableQueryLog();
        $list = DB::table('order_after')->whereRaw($where)->select('id','after_num','sys_num','serial_number','create_time','shr_name','shr_phone','shr_address','p_id','ser_id','status','shr_sheng','shr_shi','shr_xian','good_names','deal_sertime','deal_firstime','finish_time','install_id')->offset($limit)->limit('10')->get()->toArray();
       // print_r(DB::getQueryLog());

        //return $list;exit;
        //P20170424092336037 P20170214090738135
        if($list){

            foreach( $list as $ks => $vs ){

                $serial_number[]="'".$vs['serial_number']."'";

            }
            if(isset($serial_number)){

                $serial_number=implode(',',$serial_number);
                if($request->input('type') == 2){
                    $line_time =DB::table('install_line')->whereRaw("line_serm in (".$serial_number.")")->select('line_state','line_serm')->get()->toArray();//查询状态
                    if($line_time){
                        foreach ($line_time as $k=>$v){
                           $lineArr[$v['line_serm']]=$v['line_state'];
                           $linesen[]=$v['line_serm'];
                        }
                    }
                    foreach ($list as $k=>$v){

                        if(in_array($v['serial_number'],$linesen)){
                            $list[$k]['line_type']=$lineArr[$v['serial_number']];
                        }else{
                            $list[$k]['line_type']='';
                        }


                    }
                }

                $time = DB::table('order_time')->whereRaw("serial_number in (".$serial_number.") and (`is_type`='下单时间' or `is_type`='接单时间' or `is_type`='任务反馈时间')")->select('create_time','is_type','serial_number')->get()->toArray();

                if($time){
                    foreach( $time as $km => $vm ){
                        if($vm['is_type']=='下单时间'){
                            $xd_number[]=$vm['serial_number'];
                            $times[$vm['serial_number']]['xd_time']=$vm['create_time'];
                        }elseif($vm['is_type']=='接单时间'){
                            $jd_number[]=$vm['serial_number'];
                            $times[$vm['serial_number']]['jd_time']=$vm['create_time'];
                        }else{
                            $fk_number[]=$vm['serial_number'];
                            $times[$vm['serial_number']]['fk_time']=$vm['create_time']?$vm['create_time']:date("Y-m-d H:i:s");
                        }
                    }

                }

                //$score = DB::table('install_evaluation')->whereRaw("ineva_serial in (".$serial_number.")")->select('ineva_score','ineva_serial')->get();

                /*$score=DB::table('order_score')->where('orsc_sernum',$info['serial_number'])->select('orsc_grade','orsc_type')->get()->toArray();

                $scores['fen1'] = $score[0]['orsc_grade'];
                $scores['fen2'] = $score[0]['orsc_grade'];
                $scores['fen3'] = '5';*/
                //$ineva_score = ($scores['fen1']+$scores['fen2']+$scores['fen3'])/3;
                /*foreach ($score as $k=>$v){
                    $fen[$v['ineva_serial']]=$v['ineva_score'];
                }*/
                //dd($fen);exit;
                foreach ($list as $k=>$v){
                    $scores=DB::table('order_score')->where('orsc_sernum',$v['serial_number'])->select('orsc_grade','orsc_type')->get()->toArray();
                    if($scores){
                        $fen1 = $scores[0]['orsc_grade']?? '0';
                        $fen2 = $scores[1]['orsc_grade']?? '0';
                        $fen3 = 5;
                        $score = ($fen1+$fen2+$fen3)/3;
                    }else{
                        $score = 0;
                    }

                    $install_info = InstallPerson::where('id',$v['install_id'])
		                    		->select('check_code','install_name','install_phone','install_pic')
				            		->first();


                    $json[$k]['install_name'] = $install_info['install_name'];
                    $json[$k]['install_phone'] = $install_info['install_phone'];
                    $json[$k]['check_code'] = $install_info['check_code'];
                    $json[$k]['install_pic'] = $install_info['install_pic'];
                    $json[$k]['install_id'] = $v['install_id'];

                    $json[$k]['id']=$v['id'];
                    $json[$k]['status']=$v['status'];
                    $json[$k]['serial_number']=$v['serial_number'];
                    $json[$k]['after_num']=$v['after_num'];//售后单号
                    $json[$k]['shr_name']=$v['shr_name'];//客户姓名
                    $json[$k]['good_name']=$v['good_names'];//客商品名称
                    $json[$k]['score']=$score??'1'; //分数
                    $json[$k]['score']=sprintf("%.1f",$json[$k]['score']);
                    $json[$k]['user_address']=trim($v['shr_sheng']).trim($v['shr_shi']).trim($v['shr_xian']).trim($v['shr_address']); //地址
                    $json[$k]['order_action']=$input['state']; //售后单状态码
                    $json[$k]['shr_phone']=$v['shr_phone'];

                    $json[$k]['create_time']=$v['create_time'];

                    $json[$k]['deal_firstime'] = $v['deal_firstime']??'';

                    $json[$k]['time20'] = date("Y-m-d H:i:s",strtotime($v['create_time'])+20*60);
                    $json[$k]['finish_time'] = $v['finish_time'];

                    $json[$k]['deal_sertime']=$v['deal_sertime'];
                    $json[$k]['xd_time']=$times[$v['serial_number']]['xd_time']??date('Y-m-d h:i:s');
                    $json[$k]['jd_time']=$times[$v['serial_number']]['jd_time']??date('Y-m-d h:i:s');
                    $json[$k]['fk_time']=$times[$v['serial_number']]['fk_time']??date('Y-m-d h:i:s');

                    $note_num = DB::table('note')->whereRaw("`orders_id`='".$v['sys_num']."' AND `public_state`=2 AND (note_group!=2 or note_adid='".$input['admin_id']."')")->count();
                    if($note_num){
                        $json[$k]['note_num'] = $note_num;
                    }else{
                        $json[$k]['note_num'] = 0;
                    }

                }
                return response()->json(['data'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);exit;
            }
            return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);exit;

        }else{
            return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);exit;
        }

    }


    /**
     * 售后首次处理
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年6月16日上午9:35:18
     */
    public function Json_after_deal(Request $request){

    	if(!$request->filled('id')||!$request->filled('content') ){
    		return response()->json(['data'=>null,'desecption'=>'缺少参数','state'=>3]);exit;
    	}

    	$input = $request->only('id','finish_time','lable','content','admin_id');

    	$list = DB::table('order_after')->where("id",$input['id'])->select('sys_num','serial_number')->first();
    	$afterdata['status'] = '10';
    	$afterdata['deal_firstime'] = date("Y-m-d H:i:s");
    	$afterdata['feek_time'] = date("Y-m-d",strtotime(date("Y-m-d")." + 1 day"))." 17:30:00";
    	if($request->filled('finish_time')){
    		$afterdata['finish_time'] = $input['finish_time'];
    		$afterdata['trigyn'] = 1;
    	}
    	DB::table("order_after")->where("id",$input['id'])->update($afterdata);

    	if($request->filled('lable')){
    		$input['content']='【售后】'.$input['lable'].''.$input['content'];
    	}else{
    		$input['content']='【售后】'.$input['content'];
    	}

    	$rest = $this->Message($input['admin_id'],$list['sys_num'],$input['content'].'预约时间：'.$input['finish_time']."(".$list['serial_number'].")","售后单(App-android)",$input['admin_id']);
    	if($rest){
    		if($rest=="失败"){
    			return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
    		}else{
    			return response()->json(['data'=>null,'desecption'=>'提交成功','state'=>1]);exit;
    		}
    	}else{
    		return response()->json(['data'=>null,'desecption'=>'失败','state'=>5]);exit;
    	}
    }

    /**
     * 获取售后标签
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年6月17日上午9:00:59
     */
    public function Json_after_lable(){

    	$lable = array('已联系','技师已出发');
    	 return response()->json(['data'=>$this->intToStr($lable),'desecption'=>'获取成功','state'=>1]);exit;
    }

    /**
     * 获取售后处理标签
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年6月17日上午10:23:35
     */
    public function Json_afterdeal_lable(){

    	$lable = array('换新处理','充电处理','退单处理','电话处理');
    	return response()->json(['data'=>$this->intToStr($lable),'desecption'=>'获取成功','state'=>1]);exit;
    }


    //催单反馈标签获取
    public function Json_urge_acquiring (){
        $res = DB::table('setmoney_type')->whereRaw("lt_parent_id=79 and FIND_IN_SET('2',lt_group)")->get();
        foreach( $res as $k => $v ){
            $json[$k]['key']=$v['sety_id'];
            $json[$k]['value']=$v['sety_name'];
            //$next = $setmoney_type->where(array('lt_parent_id'=>$v['sety_id']))->select();
            $next = DB::table('setmoney_type')->where('lt_parent_id',$v['sety_id'])->get();
            if((int)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'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);exit;
    }


    /**
     * @name 申请完成
     * @param admin_id 服务商id
     * @param order_id 工单id
     * @param myFile4  图片1
     * @param myFile5  图片2
     * @param myFile6  图片3
     * @param dediips  ip地址
     * @param battery_old
     * @param battery_new
     * @return json
     * @author he <2019.3.19>
     */
    /**
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年5月26日下午3:12:56
     */
    public function Json_application(Request $request){
        $input = $request->only('admin_id','order_id','battery_old','battery_new','dediips','myFile4','myFile5','myFile6','lable','phoneType');
        if(empty($request->input('admin_id')) && empty($request->input('order_id'))){
            //echo '{"data":null,"desecption":"fail","state":5}';exit;
            return response()->json(['data'=>null,'desecption'=>"访问参数错误",'state'=>5]);
        }
        $order_id = $input['order_id'];
        //$lister=$order_after->where("`id`='".$order_id."'")->find();
        $lister = DB::table('order_after')->where('id',$order_id)->first();
        if($lister['status']==1 || $lister['status']==10){
            //$company_name=$admin->where("`id`='".$_POST['admin_id']."'")->field("`admin_acc`,`company_name`,`reward`")->find();//服务中心名称
            //$inst=$install_person->where("`admin_id`='".$_POST['admin_id']."'")->find();//安装人员
            $company_name = DB::table('admin')->where('id',$input['admin_id'])->select('admin_acc','company_name','reward')->first();
            $inst = DB::table('install_person')->where('admin_id',$input['admin_id'])->first();
            //$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';


            $file4 = $request->input('myFile4'); //上传图片 车牌号
            if($file4){
                /* $filedir='./FeekUploads/feedsales/'.date('Ym').'/';
                $imagesName=$file4->getClientOriginalName();
                $extension = $file4 -> getClientOriginalExtension(); //后缀
                $allow=['jpg','gif','png','jpeg'];
                if(!in_array($extension,$allow)){
                    return response()->json(['data'=>null,'desecption'=>'fail','state'=>2]);exit; //图片格式无效
                }
                $name = time().'4'.str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                //设置命名规则
                if(!$file1->move($filedir,$name)){
                    return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit; //上传失败
                }else{
                    //$psos['qualification_pr']="/".$filedir.$name;
                    $arr_a['feedback_pic']='/'.$filedir.$name;
                } */

                $arr_a['feedback_pic'] = $file4;
            }

            $file5= $request->input('myFile5');//不断电安装
            if($file5){
               /*  $filedir='./FeekUploads/feedsales/'.date('Ym').'/';
                $imagesName=$file5->getClientOriginalName();
                $extension = $file5 -> getClientOriginalExtension(); //后缀
                $allow=['jpg','gif','png','jpeg'];
                if(!in_array($extension,$allow)){
                    return response()->json(['data'=>null,'desecption'=>'fail','state'=>2]);exit; //图片格式无效
                }
                $name = time().'5'.str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                if(!$file5->move($filedir,$name)){
                    return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit; //上传失败
                }else{
                    $arr_b['feedback_pic']="/".$filedir.$name;
                } */

            	$arr_b['feedback_pic'] = $file5;
            }

            $file6 = $request->input('myFile6');//生产日期
            if($file6){
                /* $filedir='./FeekUploads/feedsales/'.date('Ym').'/';
                $imagesName=$file1->getClientOriginalName();
                $extension = $file1 -> getClientOriginalExtension(); //后缀
                $allow=['jpg','gif','png','jpeg'];
                if(!in_array($extension,$allow)){
                    return response()->json(['data'=>null,'desecption'=>'fail','state'=>2]);exit; //图片格式无效
                }
                $name = time().'6'.str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                if(!$file6->move($filedir,$name)){
                    return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit; //上传失败
                }else{
                    $psos['qualification_pr']="/".$filedir.$name;
                    //$psos['admin_pic']="/".$filedir.$newImagesName;
                    $arr_c['feedback_pic']="/".$filedir.$name;
                } */
            	$arr_c['feedback_pic'] = $file6;
            }
            //`type`,`gl_id`,`install_name`,`install_phone`,`install_time`,`admin_id`,`company_name`,`feedback_status`,`sys_num`,`is_type`,`feedback_pic`


            $arr_a['type']=4;
            $arr_a['gl_id']=$order_id;
            $arr_a['install_name']=$inst['install_name'];
            $arr_a['install_phone']=$inst['install_phone'];
            $arr_a['install_time']=date("Y-m-d H:i:s");
            $arr_a['iadmin_id']=$input['admin_id'];
            $arr_a['company_name']=$company_name['company_name'];
            $arr_a['feedback_status']=2;
            $arr_a['sys_num']='rwfk'.$order_id;
            $arr_a['is_type']=2;
            DB::table('feedsales')->insert($arr_a);
            //
            $arr_b['type']=4;
            $arr_b['gl_id']=$order_id;
            $arr_b['install_name']=$inst['install_name'];
            $arr_b['install_phone']=$inst['install_phone'];
            $arr_b['install_time']=date("Y-m-d H:i:s");
            $arr_b['iadmin_id']=$input['admin_id'];
            $arr_b['company_name']=$company_name['company_name'];
            $arr_b['feedback_status']=2;
            $arr_b['sys_num']='rwfk'.$order_id;
            $arr_b['is_type']=2;
            DB::table('feedsales')->insert($arr_b);

            $arr_c['type']=4;
            $arr_c['gl_id']=$order_id;
            $arr_c['install_name']=$inst['install_name'];
            $arr_c['install_phone']=$inst['install_phone'];
            $arr_c['install_time']=date("Y-m-d H:i:s");
            $arr_c['iadmin_id']=$input['admin_id'];
            $arr_c['company_name']=$company_name['company_name'];
            $arr_c['feedback_status']=2;
            $arr_c['sys_num']='rwfk'.$order_id;
            $arr_c['is_type']=2;
            DB::table('feedsales')->insert($arr_c);

            if($request->input('car_plate')!=""){
                //$info=$carplate_info->where("can_plate='".$_POST['car_plate']."' and or_number='".$lister['serial_number']."'")->find();
                $info = DB::table('carplate_info')->where(['car_plate'=>$input['car_plate'],'or_number'=>$lister['serial_number']])->first();
                if($info){

                }else{
                    $this->carPlate($request->input('car_plate'),$lister['serial_number']);
                }
            }

            DB::beginTransaction();//开启事务
            $arr['status']=30;
            $data['trigyn']=1;
            $res=DB::table('order_after')->where('id',$input['order_id'])->update($arr);
            if($res){
                if($request->input('battery_old')){
                    $add_old=$this->add_batterydata($input['battery_old'],'3',$order_id);
                }
                if($request->input('battery_new')){
                    $add_new=$this->add_batterydata($input['battery_new'],'4',$order_id);
                }
                // 订单操作时间
                DB::commit();
                $this->addAppLog($input['admin_id'],$input['dediips'],"派工单(".$input['phoneType'].")","售后反馈，",$lister['order_num']."订单(".$lister['serial_number']."),申请质保完成",$lister['sys_num']);
                $this->Message($input['admin_id'],$lister['sys_num'],'【售后】'.$input['lable'].''.$input['content'],"派工单(App-android)",'0');
                $this->operating_time($lister['serial_number'],'申请质保完成时间',date("Y-m-d H-i-s"),$company_name['admin_acc']);
                //echo '{"data":null,"desecption":"succes","state":1}';exit;//成功
                return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
            }else{
                DB::rollback();
                return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
            }
        }
    }


    /**
     * @name 售后反馈
     * @param type  1:日常反馈 2：售后反馈
     * @param admin_id 服务商id
     * @param order_id 工单id
     * @param myFile1  图片1
     * @param myFile2  图片2
     * @param myFile3  图片3
     * @param dediips  ip地址
     * @param battery_old
     * @param battery_new
     * @return json
     * @author he <2019.3.15>
     */
    /**
     *
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年5月26日下午3:15:01
     */
    public function Json_feedsales(Request $request){
        $input = $request->only('type','ser_type','admin_id','order_id','battery_old','battery_new','dediips','myFile1','myFile2','myFile3','message','lable','finish_time','phoneType');
        if(empty($request->input('admin_id')) && empty($request->input('order_id'))){
            return response()->json(['data'=>null,'desecption'=>"访问参数错误",'state'=>5]);
        }
        $order_id = $input['order_id'];
        $lister = DB::table('order_after')->where('id',$order_id)->first();
        if($lister['status']==1 || $lister['status']==10){
            if($request->input('ser_type') == '1'){
                $company_name = DB::table('admin')->where('id',$input['admin_id'])->select('admin_acc','company_name','reward')->first();
                $inst = DB::table('install_person')->where('admin_id',$input['admin_id'])->first();
            }else{
                $inst= DB::table('install_person')->where('id',$input['admin_id'])->first();
            }

            //dump($install_name);

            //dd($inst);
            if($request->input('myFile1')){
                $file1=$request->input('myFile1');
                /*if (preg_match('/(?<=\/)[^\/]+(?=\;)/',$file1,$pregR)) $streamFileType ='.' .$pregR[0];
                $streamFileRand = time().str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                $dir='./FeekUploads/feedsales/'.date('Ym').'/';
                $upPath='./FeekUploads/feedsales/'.date('Ym').'/';
                if(!is_dir($dir)){
                    mkdir($dir,0777,true);
                }
                $streamFilename = $upPath."/".$streamFileRand .$streamFileType;
                //处理base64文本，用正则把第一个base64,之前的部分砍掉
                preg_match('/(?<=base64,)[\S|\s]+/',$file1,$streamForW);
                if (file_put_contents($streamFilename,base64_decode($streamForW[0]))===false){
                    return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                }else{
                    $streamFilename=trim($streamFilename,".");
                    $arr_a['feedback_pic']='/.'.$streamFilename;
                }*/
              /*   $upPath='./FeekUploads/feedsales/'.date('Ym');
                $param['path'] = $upPath;
                $param['file'] = $file1;//$this->ceshi_pic();
                $param['type'] = 1;
                $curl_data = $this->curl_basepic(1,$param);
                //echo $curl_data;exit;
                if($curl_data!='error'){
                    $streamFilename = $curl_data;
                    $arr_a['feedback_pic'] = $streamFilename;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                } */

                $arr_a['feedback_pic'] = $file1;

            }

            if($request->input('myFile2')){
                $file2=$request->input('myFile2');
                /*if (preg_match('/(?<=\/)[^\/]+(?=\;)/',$file2,$pregR)) $streamFileType ='.' .$pregR[0];
                $streamFileRand = time().str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                $dir='./FeekUploads/feedsales/'.date('Ym').'/';
                $upPath='./FeekUploads/feedsales/'.date('Ym').'/';
                if(!is_dir($dir)){
                    mkdir($dir,0777,true);
                }
                $streamFilename = $upPath."/".$streamFileRand .$streamFileType;
                //处理base64文本，用正则把第一个base64,之前的部分砍掉
                preg_match('/(?<=base64,)[\S|\s]+/',$file2,$streamForW);
                if (file_put_contents($streamFilename,base64_decode($streamForW[0]))===false){
                    return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                }else{
                    $streamFilename=trim($streamFilename,".");
                    $arr_a['feedback_pic']='/.'.$streamFilename;
                }*/
                /* $upPath='./FeekUploads/feedsales/'.date('Ym');
                $param['path'] = $upPath;
                $param['file'] = $file2;//$this->ceshi_pic();
                $param['type'] = 1;
                $curl_data = $this->curl_basepic(1,$param);
                if($curl_data!='error'){
                    $streamFilename = $curl_data;
                    $arr_b['feedback_pic'] = $streamFilename;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                } */

                $arr_b['feedback_pic'] = $file2;
            }
            if($request->input('myFile3')){
                $file3=$request->input('myFile3');
                /*if (preg_match('/(?<=\/)[^\/]+(?=\;)/',$file3,$pregR)) $streamFileType ='.' .$pregR[0];
                $streamFileRand = time().str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                $dir='./FeekUploads/feedsales/'.date('Ym').'/';
                $upPath='./FeekUploads/feedsales/'.date('Ym').'/';
                if(!is_dir($dir)){
                    mkdir($dir,0777,true);
                }
                $streamFilename = $upPath."/".$streamFileRand .$streamFileType;
                //处理base64文本，用正则把第一个base64,之前的部分砍掉
                preg_match('/(?<=base64,)[\S|\s]+/',$file3,$streamForW);
                if (file_put_contents($streamFilename,base64_decode($streamForW[0]))===false){
                    return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                }else{
                    $streamFilename=trim($streamFilename,".");
                    $arr_a['feedback_pic']='/.'.$streamFilename;
                }*/
               /*  $upPath='./FeekUploads/feedsales/'.date('Ym');
                $param['path'] = $upPath;
                $param['file'] = $file3;//$this->ceshi_pic();
                $param['type'] = 1;
                $curl_data = $this->curl_basepic(1,$param);
                if($curl_data!='error'){
                    $streamFilename = $curl_data;
                    $arr_c['feedback_pic'] = $streamFilename;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                } */

                $arr_c['feedback_pic'] = $file3;
            }

            //`type`,`gl_id`,`install_name`,`install_phone`,`install_time`,`admin_id`,`company_name`,`feedback_status`,`sys_num`,`is_type`,`feedback_pic`
            if($request->input('type') == '1'){
                if($request->filled('myFile1')){
                    $arr_a['type']=3;
                    $arr_a['gl_id']=$order_id;
                    $arr_a['install_name']=$inst['install_name'];
                    $arr_a['install_phone']=$inst['install_phone'];
                    $arr_a['install_time']=date("Y-m-d H:i:s");
                    $arr_a['admin_id']=$input['admin_id'];
                    if($request->input('ser_type') == '1'){
                        $arr_a['company_name']=$company_name['company_name'];
                    }else{
                        $arr_a['company_name']=$inst['install_name'];
                    }

                    $arr_a['feedback_status']=2;
                    $arr_a['sys_num']='rwfk'.$order_id;
                    $arr_a['is_type']=2;
                    DB::table('feedsales')->insert($arr_a);
                }

                if($request->filled('myFile2')){
                    $arr_b['type']=2;
                    $arr_b['gl_id']=$order_id;
                    $arr_b['install_name']=$inst['install_name'];
                    $arr_b['install_phone']=$inst['install_phone'];
                    $arr_b['install_time']=date("Y-m-d H:i:s");
                    $arr_b['admin_id']=$input['admin_id'];
                    if($request->input('ser_type') == '1'){
                        $arr_b['company_name']=$company_name['company_name'];
                    }else{
                        $arr_b['company_name']=$inst['install_name'];
                    }
                    //$arr_b['company_name']=$company_name['company_name'];
                    $arr_b['feedback_status']=2;
                    $arr_b['sys_num']='rwfk'.$order_id;
                    $arr_b['is_type']=2;
                    DB::table('feedsales')->insert($arr_b);
                }
                if($request->filled('myFile3')){
                    $arr_c['type']=1;
                    $arr_c['gl_id']=$order_id;
                    $arr_c['install_name']=$inst['install_name'];
                    $arr_c['install_phone']=$inst['install_phone'];
                    $arr_c['install_time']=date("Y-m-d H:i:s");
                    $arr_c['admin_id']=$input['admin_id'];
                    if($request->input('ser_type') == '1'){
                        $arr_c['company_name']=$company_name['company_name'];
                    }else{
                        $arr_c['company_name']=$inst['install_name'];
                    }
                    //$arr_c['company_name']=$company_name['company_name'];
                    $arr_c['feedback_status']=2;
                    $arr_c['sys_num']='rwfk'.$order_id;
                    $arr_c['is_type']=2;
                    DB::table('feedsales')->insert($arr_c);
                }




            }else{
                if($request->input('myFile1')){
                    $arr_a['type']=10;
                    $arr_a['gl_id']=$order_id;
                    $arr_a['install_name']=$inst['install_name'];
                    $arr_a['install_phone']=$inst['install_phone'];
                    $arr_a['install_time']=date("Y-m-d H:i:s");
                    $arr_a['admin_id']=$input['admin_id'];
                    if($request->input('ser_type') == '1'){
                        $arr_a['company_name']=$company_name['company_name'];
                    }else{
                        $arr_a['company_name']=$inst['install_name'];
                    }
                    //$arr_a['company_name']=$company_name['company_name'];
                    $arr_a['feedback_status']=2;
                    $arr_a['sys_num']='rcfk'.$order_id;
                    $arr_a['is_type']=2;
                    DB::table('feedsales')->insert($arr_a);
                }

                if($request->input('myFile2')){
                    $arr_b['type']=10;
                    $arr_b['gl_id']=$order_id;
                    $arr_b['install_name']=$inst['install_name'];
                    $arr_b['install_phone']=$inst['install_phone'];
                    $arr_b['install_time']=date("Y-m-d H:i:s");
                    $arr_b['admin_id']=$input['admin_id'];
                    if($request->input('ser_type') == '1'){
                        $arr_b['company_name']=$company_name['company_name'];
                    }else{
                        $arr_b['company_name']=$inst['install_name'];
                    }
                    //$arr_b['company_name']=$company_name['company_name'];
                    $arr_b['feedback_status']=2;
                    $arr_b['sys_num']='rcfk'.$order_id;
                    $arr_b['is_type']=2;
                    DB::table('feedsales')->insert($arr_b);
                }
                if($request->input('myFile3')){
                    $arr_c['type']=10;
                    $arr_c['gl_id']=$order_id;
                    $arr_c['install_name']=$inst['install_name'];
                    $arr_c['install_phone']=$inst['install_phone'];
                    $arr_c['install_time']=date("Y-m-d H:i:s");
                    $arr_c['admin_id']=$input['admin_id'];
                    if($request->input('ser_type') == '1'){
                        $arr_c['company_name']=$company_name['company_name'];
                    }else{
                        $arr_c['company_name']=$inst['install_name'];
                    }
                    //$arr_c['company_name']=$company_name['company_name'];
                    $arr_c['feedback_status']=2;
                    $arr_c['sys_num']='rcfk'.$order_id;
                    $arr_c['is_type']=2;
                    DB::table('feedsales')->insert($arr_c);
                }
            }


            if($request->input('car_plate')!=""){
                //$info=$carplate_info->where("can_plate='".$_POST['car_plate']."' and or_number='".$lister['serial_number']."'")->find();
                $info = DB::table('carplate_info')->where(['car_plate'=>$input['car_plate'],'or_number'=>$lister['serial_number']])->first();
                if($info){

                }else{
                    $this->carPlate($request->input('car_plate'),$lister['serial_number']);
                }
            }

            DB::beginTransaction();//开启事务
            if($input['type'] == '1'){

                $arr['status']=10; //日常 反馈

            }elseif($input['type'] == '2'){
                $arr['status']=30;
                $arr['deal_sertime'] = date('Y-m-d h:i:s');
            }

            $arr['finish_time'] = $input['finish_time']??'';
            $data['trigyn']=1;
            $res=DB::table('order_after')->where('id',$input['order_id'])->update($arr);
            if($lister['status'] == '10' && $input['type'] == '1'){
                $res =1;
            }

            if($res){
                if($request->filled('battery_old')){
                    $add_old=$this->add_batterydata($input['battery_old'],'3',$order_id);
                }
                if($request->filled('battery_new')){
                    $add_new=$this->add_batterydata($input['battery_new'],'4',$order_id);
                }
                // 订单操作时间
                DB::commit();
                //dump($lister['serial_number']);
                //dd($lister['order_num']);
                if($request->input('ser_type') == '1'){
                    //$ids,$ips,$function_name,$type,$content,$order_num
                    $this->addAppLog($input['admin_id'],$input['dediips'],"派工单(".$input['phoneType'].")","售后反馈，",$lister['order_num']."订单(".$lister['serial_number']."),申请质保完成",$lister['sys_num']);
                }else{
                    $this->AddPersonLog($input['admin_id'],$input['dediips'],"派工单(".$input['phoneType'].")","售后反馈，",$lister['order_num']."订单(".$lister['serial_number']."),申请质保完成",$lister['sys_num']);
                }

                $input['lable'] = $input['lable']??'';


                $input['finish_time'] = $input['finish_time']??'';

                 if($input['type'] == '1'){
                 	//$this->Message($input['admin_id'],$lister['sys_num'],'【售后】'.$input['message'],"售后日常反馈(App-android)",'0');
                 	$this->Message($input['admin_id'],$lister['sys_num'],'【售后】'.$input['lable'].' '.$input['message'].' (预约时间：'.$input['finish_time'].')',"售后日常反馈(App-android)",'0');
                 }else{
                 	$this->Message($input['admin_id'],$lister['sys_num'],'【售后】'.$input['lable'].' '.$input['message'].' (预约时间：'.$input['finish_time'].')',"售后审核完成(App-android)",'0');
                 }




                if($request->input('ser_type') == '1'){
                    $this->operating_time($lister['serial_number'],'申请质保完成时间',date("Y-m-d h:i:s"),$company_name['admin_acc']);
                }else{
                    $this->operating_time($lister['serial_number'],'申请质保完成时间',date("Y-m-d h:i:s"),$inst['install_name'].'('.$inst['check_code'].')');
                }
                //$install_name['install_name'].'('.$install_name['check_code'].')'
                //echo '{"data":null,"desecption":"succes","state":1}';exit;//成功
                return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
            }else{
                DB::rollback();
                return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
            }
        }else{
        	return response()->json(['data'=>null,'desecption'=>'状态不正确','state'=>2]);exit;
        }
    }




    /**
     * 售后展示
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年5月27日上午9:53:15
     */
    public function Json_SalesShow(Request $request){
        if(!$request->filled('admin_id') || !$request->filled('order_id')|| !$request->filled('serial_number')){
            return response()->json(['data'=>null,'desecption'=>'访问参数错误','state'=>4]);
        }
        $input = $request->only('admin_id','order_id','serial_number');

        $order_id = $input['order_id'];

       $sys_num = DB::table('order_after')->where('id',$input['order_id'])->value('sys_num');



   //  print_r($res);


     //备注


         // DB::connection()->enableQueryLog();
        if($request->input('ser_type')=='1'){

        	$arr = DB::table('feedsales')->select('install_time','feedback_pic','admin_id','install_remark')->where(['gl_id'=>$input['order_id']])->orderBy('id','DESC')->get()->toArray();//,'admin_id'=>$input['admin_id']



        	$list = DB::table('note')->whereRaw("`orders_id`='".$sys_num."' AND `public_state`=2 AND (note_group!=2 or note_adid='".$input['admin_id']."') ORDER BY id DESC")->get();



        }else {
        	$admin_id = DB::table('install_person')->where('id', $input['admin_id'])->value('admin_id');

        	$arr = DB::table('feedsales')->select('install_time','feedback_pic','admin_id','install_remark')->where(['gl_id'=>$input['order_id'],'admin_id'=>$admin_id])->orderBy('id','DESC')->get()->toArray();





        	$list = DB::table('note')->whereRaw("`orders_id`='" . $sys_num . "' AND `public_state`=2 AND (note_group!=2 or note_adid='" . $admin_id . "') ORDER BY id DESC")->get();
        }
        // print_r(DB::getQueryLog());



        foreach( $arr as $k => $v ){
        	$res[$k]['note_time'] = $v['install_time'];
        	$res[$k]['feedback_pic'] = $this->picurl($v['feedback_pic']);
        	$res[$k]['feed_type'] = 2;
            $res[$k]['admin_id'] = $v['admin_id'];
            $res[$k]['install_remark'] = $v['install_remark'];
        	$res[$k]['author'] = '';
        	$res[$k]['type'] = '';
        	$res[$k]['deals'] = '';

        }


        $list =$list->toArray();
        if($list){
        	foreach($list as $k=>$v){
        		if($v['note_group']=='0'){
        			$admin_group=DB::table('admin')->where('admin_name',$v['note_name'])->value('admin_group');
        			if(empty($admin_group)){
        				$admin_group=DB::table('admin')->where('admin_acc',$v['note_name'])->value('admin_group');
        			}
        		}else{
        			$admin_group=$v['note_group'];
        		}
        		if($v['note_content']=="售后处理完毕，已申请售后完成"){
        			$json[$k]['author']='系统备注';
        			$json[$k]['deals']="1";
        			$json[$k]['type']=2;
        		}else{
        			if($admin_group==2){
        				if($request->input('ser_type')=='1'){
        					if($v['note_installid']=='0'){
        						$json[$k]['author']='我';
        						$json[$k]['type']=1;
        					}else{
        						$json[$k]['author']='技师';
        						$json[$k]['type']=2;
        					}
        				}else{
        					if($v['note_installid']==$input['admin_id']){
        						$json[$k]['author']='我';
        						$json[$k]['type']=1;
        					}else{
        						$json[$k]['author']='代理';
        						$json[$k]['type']=2;
        					}
        				}
        			}else{
        				$json[$k]['author']='速电客服';
        				$json[$k]['type']=2;
        			}
        			$json[$k]['deals']="2";
        		}

        		//$time=str_replace("-","/",$v['note_time']);//时间
        		//$json[$k]['create_time'] = substr($time,0,-3);//时间

        		$json[$k]['note_time'] = $v['note_time'];
        		$json[$k]['content'] = $v['note_content'];//备注内容

        		$json[$k]['feed_type'] = 1;


        	}


        }

      //  print_r($json);

        if(!empty($res)&&!empty($json)){
        	$pic=[];
        	foreach($res as $k=>$v){
        		$pic[$v['note_time']][]=$v;
        	}
        	//echo 1;
//         	$feedarr = array_merge($json,$res);

//         	$note_time = array_column($feedarr,'note_time');

//         	array_multisort($note_time,SORT_DESC,$feedarr);
        	$feedarr=[];
        	foreach($json as $k=>$v){
        		$feedarr[$k]=$v;
        		$feedarr[$k]['img_list']=$pic[$v['note_time']]??[];
        		if(isset($pic[$v['note_time']])){
        			unset($pic[$v['note_time']]);
        		}
        	}
        	if(!empty($pic)){
        		//dump($pic);
        		$feedarrs=[];
        		$centent['img_list']=[];
        		$centent['note_time']='';
        		$centent['type']=1;
        		$centent['feed_type']=2;
        		$num=0;
        		foreach($pic as $k=>$v){
                    $centent['content'] = $v[0]['install_remark'];
                    if($v[0]['admin_id'] == $input['admin_id']) {
                        $centent['author'] = "我";
                    }else{
                        $centent['author'] = "代理";
                    }
        			//dump($v);
        			$feedarrs[$num]=$centent;
        			$feedarrs[$num]['note_time']= $k;
        			$feedarrs[$num]['img_list']=array_column($v, 'feedback_pic');
                    $num++;
        		}
        		$feedarr = array_merge($feedarrs,$feedarr);
        		$note_time = array_column($feedarr,'note_time');
        		array_multisort($note_time,SORT_DESC,$feedarr);
        	}

        }elseif(empty($res)&&!empty($json)){
        	//echo 2;
//         	$feedarr= $json;
        	$feedarr=[];

        	foreach($json as $k=>$v){
        		$feedarr[$k]=$v;
        		$feedarr[$k]['img_list']=[];
        	}

        }elseif(!empty($res)&&empty($json)){
        	//echo 3;
//         	$feedarr= $res;
        	$pic=[];

//            $centents['author']="我";
            $centents['img_list']=[];
            $centents['note_time']='';
            $centents['type']=1;
//        	$centent['content']='';
            $centents['feed_type']=2;
        	$centent=[];
        	foreach($res as $k=>$v){
        		$pic[$v['note_time']][]=$v['feedback_pic'];
                $v['content'] = $v['install_remark'];
                if($v['admin_id'] == $input['admin_id']) {
                    $v['author'] = "我";
                }else{
                    $v['author'] = "代理";
                }
                $v = array_merge($v,$centents);
        		$centent[$v['note_time']]=$v;
        	}
        	$feedarr=[];

        	$num=0;
        	foreach($pic as $k=>$v){
        		$feedarr[$num]=$centent[$k];
        		$feedarr[$num]['content']='';
        		$feedarr[$num]['img_list']=$v;
        	}
        }



        if(!empty($feedarr)){
            return response()->json(['data'=>$this->intToStr($feedarr),'desecption'=>'成功','state'=>1]);
        }else{
            return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);
        }
    }





    /**
     * @name 催单反馈
     * @param sin_id 催单信息id
     * @param sin_bid 标签id
     * @param sin_bcentent 标签内容
     * @param sin_centent 反馈内容
     * @param admin_id 服务商id
     * @param sin_serial 派工单号
     * @return json
     * @author he <2019.2.26>
     */
    public function Json_urge_feedback(Request $request) {
        if ($request->isMethod('post')) {
            $input = $request->only('sin_id','sin_bid','sin_bcentent','sin_centent','admin_id','sin_serial');
            if($input['sin_bid'] == ""){
                return response()->json(['data'=>null,'desecption'=>'未选择反馈标签','state'=>4]);;exit;
            }
            $poss['sin_bid']=$input['sin_bid'];
            if($input['sin_bcentent']){
                $input['sin_bcentent']="；".$input['sin_bcentent'];
            }
            $poss['sin_centent']=$input['sin_centent'].$input['sin_bcentent'];
            $poss['sin_state']='2';

            $sys_num = DB::table('ser_infor')->where(['sin_serial'=>$input['sin_serial'],'sin_id'=>$input['sin_id']])->value('sin_sysnum');

            $this->Message($input['admin_id'],$sys_num,$poss['sin_centent'],"催单反馈(App-android)",'0');
            $res = DB::table('ser_infor')->where(['sin_id'=>$input['sin_id'],'sin_serial'=>$input['sin_serial']])->update($poss);
            if($res){
                return response()->json(['data'=>null,'desecption'=>'催单反馈成功','state'=>1]);exit;
            }else{
                return response()->json(['data'=>null,'desecption'=>'催单反馈失败','state'=>2]);exit;
            }

        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);;exit;
        }
    }

    /**
     * @name 变更催单查看状态
     * @param sin_id 标签id
     * @param sin_serial 派工单号
     * @return json
     * @author he <2019.2.26>
     */
    public function Json_isRead(Request $request) {
        if($request->isMethod('post')){
            $input = $request->only('sin_id','sin_serial');
            if(empty($input['sin_id']) || empty($input['sin_serial'])){
                return response()->json(['data'=>null,'desecption'=>'参数格式错误','state'=>4]);;exit;
            }else{
                $poss['isRead']='2';
                $res = DB::table('ser_infor')->where(['sin_id'=>$input['sin_id'],'sin_serial'=>$input['sin_serial']])->update($poss);
                if($res){
                    return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);;exit;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);;exit;
                }
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);;exit;
        }
    }

    /**
     * @name
     * @param
     * @return json
     * @author he <2019.2.26>
     */
     public function Json_mpleInfo(Request $request){
         if($request->isMethod('post')){
             $input = $request->only('id');
             $returnData = OrderList::where('id',$input['id'])->select('serial_number','goods_name','customer_id')->distinct()->get()->toArray();
             $returnColle = User::where('id',$returnData[0]['customer_id'])->select('shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress')->get();
             foreach($returnData as $k=>$v){
                 foreach($returnColle as $kk=>$vv){
                     $json[$k]['serial_number']=$v['serial_number'];
                     $json[$k]['goods_name']=$v['goods_name'];
                     $json[$k]['name']=$vv['shr_name'];
                     $json[$k]['mobile_phone']=$vv['shr_phone'];
                     if($vv['shr_xian']=="市、县级市"){
                         UNSET($vv['shr_xian']);
                     }
                     $json[$k]['address']=$vv['shr_sheng'].$vv['shr_shi'].$vv['shr_xian'].$vv['shr_adress'];
                 }
             }
             return response()->json(['data'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);exit;
         }else{
             return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);exit;
         }
     }

    /**
     * @name 营业时间获取
     * @param admin_id 服务中心id
     * @return json
     * @author he <2019.2.26>
     */
    public function Json_bustime(Request $request) {
        if($request->isMethod('post')){
            $input = $request->only('admin_id');
            if($input['admin_id']){
                //$ad_urgent=$admin->where("id='".$_POST['ser_id']."'")->getField("ad_urgent");
                //$time=$ser_time->where("ser_id='".$_POST['ser_id']."'")->find();
                //$time1=$ser_time->where("ser_id=0")->find();
                $ad_urgent = Admin::where('id',$input['admin_id'])->select('ad_urgent')->first()->toArray();
                $time = DB::table('ser_time')->where('ser_id',$input['admin_id'])->first();
                $time1 = DB::table('ser_time')->where('ser_id','0')->first();
                if($time){

                }else{
                    $time=$time1;
                }
                $res=explode(',',ltrim(rtrim($ad_urgent['ad_urgent'],","),','));
                if(in_array(10,$res)){
                    $json['ad_urgent']=1;
                }else{
                    $json['ad_urgent']=2;
                }if(in_array(20,$res)){
                    $json['ad_urgentd']=1;
                }else{
                    $json['ad_urgentd']=2;
                }
                $json['start_times'] = substr($time1['start_time'],0,5);
                $json['end_times'] = substr($time1['end_time'],0,5);

                $json['start_time'] = substr($time['start_time'],0,5);
                $json['end_time'] = substr($time['end_time'],0,5);
                return response()->json(['data'=>$this->intToStr($json),'desecption'=>'获取成功','state'=>1]);;exit;
            }else{
                return response()->json(['data'=>null,'desecption'=>'获取失败','state'=>2]);;exit;
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);exit;
        }
    }

    /**
     * @name 转单操作
     * @param id 订单id
     * @param install_id 安装人员id
     * @param
     * @return json
     * @author he <2019.2.27>
     */
    public function Json_transferr_Oper(Request $request) {
        $input = $request->only('id','install_id','ser_type','admin_id','dediips');
        //$i = DB::table('order_list')->where('id','48919')->first();
        //return $i;exit;

        $list = DB::table('order_list')->where('id',$input['id'])->first();
        $is_lidao = Admin::where('id',$list['ser_id'])->first();
        $checkOrder = DB::table('install_line')->where('line_serm',$list['serial_number'])->value('line_status');//查询是否可转单
        //dd($checkOrder);

        if($checkOrder == 0){
            return response()->json(['data'=>null,'desecption'=>'请联系所属技师终止订单','state'=>4]);exit;
        }
        if($list['install_id'] == $input['install_id']){
            return response()->json(['data'=>null,'desecption'=>'不可转单为同一安装人员','state'=>5]);exit;
        }
        if($list['locklist_type']==2){
            return response()->json(['data'=>null,'desecption'=>'该订单已锁定，不可转单','state'=>6]);exit;
        }else{
            if($input['ser_type'] == '1'){
                $install_infor = InstallPerson::where(['id'=>$input['install_id'],'admin_id'=>$input['admin_id']])->first();
                if(!$install_infor){
                    return response()->json(['data'=>null,'desecption'=>'该技师不是当前子级技师','state'=>7]);exit;
                }
            }else{
                $install_infor = InstallPerson::where('id',$input['install_id'])->first();
                $install_infor['install_pid'] = $install_infor['install_pid'] ? $install_infor['install_pid'].','.$input['admin_id'] : '';
                $arr3 = explode(',',$install_infor['install_pid']);
                if(in_array($input['admin_id'],$arr3) || $input['install_id']==$input['admin_id']){

                }else{
                    return response()->json(['data'=>null,'desecption'=>'该技师不是当前子级技师','state'=>7]);exit;
                }
            }

            DB::beginTransaction(); //开启事物
            $poss['install_id']=$input['install_id'];
            $poss['intall_person']=$install_infor['install_name'];
            $poss['intall_phone']=$install_infor['install_phone'];
            $poss['line_status']='1';
            $posa['installperson']=$input['install_id'];
            $posa['intall_person']=$install_infor['install_name'];
            $posa['intall_phone']=$install_infor['install_phone'];

            $res = DB::table('order_list')->where('id',$input['id'])->update($poss);
            $res1 = DB::table('settlement_list')->where('list_id',$list['serial_number'])->update($posa);
            if($res && $res1){
                DB::commit();
                $this-> Json_sendflow ( $list['serial_number'],$install_infor['admin_id'],$input['install_id'],$input['admin_id'],$list['order_num'],$list['sys_num']);
                DB::table('install_line')->where('line_serm',$list['serial_number'])->update(['line_status'=>0,'line_state'=>1]);
                if($input['ser_type'] == '1'){
                    //日志
                    $this->addAppLog($input['admin_id'],$input['dediips'],"安装人员(".$input['phoneType'].")",'转单',$list['serial_number'],$list['sys_num']);
                }else{
                    // 日志
                    $this->AddPersonLog($input['admin_id'],$input['dediips'],"安装人员(".$input['phoneType'].")",'转单',$list['serial_number'],$list['sys_num']);
                }
                return response()->json(['data'=>null,'desecption'=>'转单成功','state'=>1]);;exit;
                /*******************需修改***************************/
                $binds = InstallPerson::where('id',$input['install_id'])->value('bind');
                if($binds==2){
                    if($is_lidao=='2'){
                        //include_once('PushLidaoAction.class.php');
                        //$Pushs= new PushLidaoAction();
                        //$Pushs->res_push($list['sys_num'],$install_infor['check_code'],'新订单',2);
                        //$this->success('接单成功！');exit;
                    }

                    //include_once('PushAction.class.php');
                    //$Push= new PushAction();
                    //$Push->res_push($list['sys_num'],$install_infor['check_code'],'新订单',2);
                }
                exit;
                /*********************需修改**********************/
            }else{
                DB::rollback();
                return response()->json(['data'=>null,'desecption'=>'转单失败','state'=>2]);exit;
            }

        }
    }

    /**
     * @name 售后转单操作（服务商）
     * @param id 售后单id
     * @param install_id 安装人员id
     * @param
     * @return json
     * @author he <2019.2.27>
     */
    public function Json_transferr_after(Request $request) {
        $input = $request->only('id','install_id','ser_type','admin_id','dediips');

        $list = DB::table('order_after')->where('id',$input['id'])->first();
        $is_lidao = Admin::where('id',$list['ser_id'])->first();
        if($list['install_id'] != $request->input('admin_id') && $request->input('ser_type') != '1'){
            return response()->json(['data'=>null,'desecption'=>'无操作权限，请联系所属技师操作','state'=>8]);exit;
        }
        //$checkOrder = DB::table('install_line')->where('line_serm',$list['serial_number'])->value('line_status');//查询是否可转单
        if($list['status'] =='30'){
            return response()->json(['data'=>null,'desecption'=>'该售后单已待审核，不可转单','state'=>3]);exit;
        }elseif($list['status'] =='40'){
            return response()->json(['data'=>null,'desecption'=>'该售后单已完成，不可转单','state'=>4]);exit;
        }elseif($list['status'] =='50'){
            return response()->json(['data'=>null,'desecption'=>'该售后单已撤销，不可转单','state'=>5]);exit;
        }
        if($input['ser_type'] == '1'){
            $install_infor = InstallPerson::where(['id'=>$input['install_id'],'admin_id'=>$input['admin_id']])->first();
            if(!$install_infor){
                return response()->json(['data'=>null,'desecption'=>'该技师不是当前子级技师','state'=>7]);exit;
            }
        }else{
            $install_infor = InstallPerson::where('id',$input['install_id'])->first();
            $install_infor['install_pid'] = $install_infor['install_pid'] ? $install_infor['install_pid'].','.$input['admin_id'] : '';
            $arr3 = explode(',',$install_infor['install_pid']);
            if(in_array($input['admin_id'],$arr3)){

            }else{
                return response()->json(['data'=>null,'desecption'=>'该技师不是当前子级技师','state'=>7]);exit;
            }
        }
        DB::beginTransaction(); //开启事物
        $poss['install_id']=$input['install_id'];
        //DB::connection()->enableQueryLog();
        $res = DB::table('order_after')->where('id',$input['id'])->update($poss);

        //print_r(DB::getQueryLog());
        if($res){
            DB::commit();
            $this-> Json_sendflow ( $list['after_num'],$install_infor['admin_id'],$input['install_id'],$input['admin_id'],$list['order_num'],$list['sys_num']);
            if($request->input('ser_type')==1){
                $this->addAppLog($input['admin_id'],$input['dediips'],"安装人员(".$input['phoneType'].")",'售后转单',$list['serial_number'],$list['sys_num']);
            }else{
                $this->AddPersonLog($input['admin_id'],$input['dediips'],"安装人员(".$input['phoneType'].")",'售后转单',$list['serial_number'],$list['sys_num']);
            }

            return response()->json(['data'=>null,'desecption'=>'售后转单成功','state'=>1]);;exit;
        }else{
            DB::rollback();
            return response()->json(['data'=>null,'desecption'=>'售后转单失败','state'=>2]);;exit;
        }


    }

    /**
     * @name 服务中心设置的时间
     * @param start_time ：开始营业时间
     * @param end_time ：结束营业时间
     * @param admin_id ：服务中心id
     * @param urger  1小时极速服务开通
     * @param nighthelp 夜间救援
     * @return json
     * @author he <2019.2.26>
     */
    public function Json_acceptime(Request $request) {
        if($request->isMethod('post')){
            //$time=$ser_time->where("ser_id=0")->find();
            $input =$request->only('start_time','end_time','admin_id','urger','nighthelp');
            $time = DB::table('ser_time')->where('ser_id','0')->first();
            if($input['start_time']>=$time['start_time'] || $input['end_time']>=$time['end_time']){
                return response()->json(['data'=>null,'desecption'=>'设置营业时间开始时间不得大于'.substr($time['start_time'],0,5).',结束时间大于'.substr($time['end_time'],0,5).'','state'=>3]);;exit;
            }else {
                $poss['start_time'] = $input['start_time'];
                $poss['end_time'] = $input['end_time'];
                if($input['urger'] == '10'){
                    $one[0] ='10';
                }else{
                    $one[0] ='';
                }
                if($input['nighthelp'] == '10'){
                    $one[1] = '20';
                }else{
                    $one[1] = '';
                }
                $type['ad_urgent'] =','.implode(',',$one).',';

               // echo $type['ad_urgent'];

                $pd = DB::table('ser_time')->where('ser_id', $input['admin_id'])->first();
                if ($pd) {
                    $pd = DB::table('ser_time')->where('ser_id',$input['admin_id'])->update($poss);
                    $pf =DB::table('admin')->where('id',$input['admin_id'])->update($type);
                } else {
                    $poss['ser_id'] = $input['admin_id'];
                   $pd = DB::table('ser_time')->insert($poss);
                   $pf = DB::table('admin')->where('id',$input['admin_id'])->update($type);
                }
                if($pd || $pf){
                    return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
                }
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);exit;
        }
    }

    //绑定别名
    public function Json_setBind(Request $request){
        if($request->isMethod('post')){
            $input = $request->only('ser_type','admin_id');
            //return response()->json(['data'=>$input,'desecption'=>'绑定成功','state'=>1]);exit;

            if($input['ser_type'] == '1'){
                $binds =AdminInfor::where('admin_id',$input['admin_id'])->value('bind');
                if($binds == 1){
                    $data['bind'] = 2;
                    $rest = AdminInfor::where('admin_id',$input['admin_id'])->update($data);
                    if($rest){
                        return response()->json(['data'=>null,'desecption'=>'绑定成功','state'=>1]);exit;
                    }else{
                        return response()->json(['data'=>null,'desecption'=>'绑定失败','state'=>2]);exit;
                    }
                }elseif ($binds == 2){
                    return response()->json(['data'=>null,'desecption'=>'绑定成功','state'=>1]);exit;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'绑定失败','state'=>2]);exit;
                }
            }else{
                //$install=$install_person->where("`id`='".$_POST['user_id']."'")->find();
                //$binds=$install['bind'];
                //$is_lidao=M('admin')->where("id='".$install['admin_id']."'")->getField('is_lidao');
                $install = InstallPerson::where('id',$input['admin_id'])->first()->toArray();
                $binds=$install['bind'];
                $is_lidao = Admin::where('id',$install['admin_id'])->value('is_lidao');
                if($binds==1){
                    $data['bind']=2;
                    $rest = InstallPerson::where('id',$input['admin_id'])->update($data);
                    if($rest){
                        return response()->json(['data'=>null,'desecption'=>'绑定成功','state'=>1]);exit;
                    }else{
                        return response()->json(['data'=>null,'desecption'=>'绑定失败','state'=>2]);exit;
                    }
                }elseif ($binds == 2){
                    return response()->json(['data'=>null,'desecption'=>'绑定成功','state'=>1]);exit;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'绑定失败','state'=>2]);exit;
                }
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);exit;
        }
    }

    /**
     * @name 预约安装时间
     * @param order_id    订单id
     * @param delay_time  预约时间
     * @param dediips     ip
     * @return json
     * @author he <2019.2.27>
     */
    public function Json_orderdelay(Request $request){
        //dd('1');
        //$this->addptrz("android-app","订单预约");//记录
        $input = $request->only('ser_type','order_id','delay_time','dediips','admin_id','phoneType');
        $time=date("Y-m-d");
        $day=floor((strtotime($input['delay_time'])-strtotime($time))/86400);
        $list = DB::table('order_list')->where('id',$input['order_id'])->select('sys_num','locklist_type','order_num','serial_number','ser_id','stauas','order_goods_id','p_id','create_time','install_id')->first();
       /*  if($list){
	        return response()->json(['data'=>null,'desecption'=>'订单信息错误','state'=>3]);exit;
        } */
        //dd($list);
        // 日志$ids,$ips,$function_name,$type,$content,$order_num
        if($input['ser_type'] == 1){
            $this->addAppLog($input['admin_id'],$input['dediips'],'派工单('.$input['phoneType'].')','预约安装'.$input['delay_time'],"订单(".$list['serial_number'].")",$list['sys_num']);
        }elseif($input['ser_type'] == 2){
            $this->AddPersonLog($input['admin_id'],$input['dediips'],'派工单('.$input['phoneType'].')','预约安装'.$input['delay_time'],"订单(".$list['serial_number'].")",$list['sys_num']);
        }

        //dd($list);
        if($list['stauas']=='10' || $list['stauas']=='20'){
            echo '{"data":null,"desecption":"请先接取订单！！！","state":1001}';exit;
        }

        if($list['locklist_type']=='2'){
            return response()->json(['data'=>null,'desecption'=>'该订单已锁定，无法预约','state'=>5]);exit;
        }
        if($day>0){
            DB::table('time_history')->where('tih_number',$list['serial_number'])->delete();
        }
        $data['day_time']=$input['delay_time'];
        $exist = DB::table('orders')->where(['sys_num'=>$list['sys_num'],'day_time'=>$input['delay_time']])->value('day_time');
        if($exist){
            $resultOrder=1;
            $resultOrderList=1;
        }else{
            $resultOrder = DB::table('orders')->where('sys_num',$list['sys_num'])->update($data);
            $resultOrderList = DB::table('order_list')->where('id',$input['order_id'])->update($data);
        }

        $company_name = DB::table('admin')->where('id',$list['ser_id'])->select('admin_acc','company_name','reward')->first();

        $yyaz_time = DB::table('order_time')->where(['serial_number'=>$list['serial_number'],'is_type'=>'安装预约时间'])->orderBy('id','DESC')->value('create_time');
        $yytime=date("Y-m-d H:i:s");
        if(!$yyaz_time){
            $this->operating_time($list['serial_number'],'安装预约时间',$yytime,$company_name['admin_acc']);
        }
        $set_id = DB::table('settlement_list')->where('list_id',$list['serial_number'])->value('id');
        $res = DB::table('settlement_money')->where(['sem_slid'=>$set_id,'sem_type'=>'17'])->first();
        $rulesout=$this::rulesout();
        if(!in_array($list['p_id'],$rulesout)) {
            if (!$res) {
                //$payout_time=$order_time->where("serial_number='".$list['serial_number']."' and is_type='接单时间'")->order('id DESC')->getField('create_time');//获取奖罚起始时间
                //$money_type=$setmoney_type->where("sety_id=17")->getField("sety_id,sety_price");//->select();
                $payout_time = DB::table('order_time')->where(['serial_number' => $list['serial_number'], 'is_type' => '接单时间'])->orderBy('id', 'DESC')->value('create_time');
                $money_type = DB::table('setmoney_type')->where('sety_id', '17')->select('sety_id', 'sety_price')->first();
                //dd($money_type);
                $zero1 = time();//strtotime (date("Y-m-d H:i:s"));
                $zero2 = strtotime($payout_time);
                $guonian = ($zero1 - $zero2) / 60; //60s*60min*24h
                if ($guonian <= 17 && $company_name['reward'] == '1') {
                    $money['sem_slid'] = $set_id;
                    $money['sem_synum'] = $list['sys_num'];
                    $money['sem_creacter'] = $company_name['admin_acc'];
                    $money['sem_price'] = $money_type['sety_price'];
                    $money['sem_type'] = 17;
                    //$settlement_money->add($money);
                    //$all_price['all_price']=$settlement_money->where("sem_slid='".$dou."'")->SUM('sem_price');
                    //$settlement_list->where("id='".$dou."'")->save($all_price);
                    DB::table('settlement_money')->insert($money);
                    $all_price['all_price'] = DB::table('settlement_money')->where('sem_slid', $set_id)->sum('sem_price');
                    DB::table('settlement_list')->where('id', $set_id)->update($all_price);
                }
            }
        }
        if($resultOrder && $resultOrderList){
            if($list['p_id'] == '463'){
                $insArr = InstallPersonService::getInstallPersonById($list['install_id']);
                $boshi['op_type'] = 12;
                $boshi['orderWebCod'] = $list['order_num'];
                $boshi['check_code'] = $insArr['check_code'];
                $order_lists['serial_number'] = $list['serial_number'];
                $order_lists['create_time'] = $list['create_time'];
                $order_lists['ser_id'] = $list['ser_id'];
                $boshi['order_list'][] = $order_lists;
                $boshi['method'] = 'sysBsWorkOrderStatue';
                $boshi['contactTime'] = $_POST['delay_time'];
                $sys_jd = $this->request_post('https://web.sudianwang.com/api/v1/BsApi/orderApi?method=sysBsWorkOrderStatue', json_encode($boshi), array('Content-Type: application/json'));
                $sys_jd = json_decode($sys_jd,true);
                if($sys_jd['response']['code'] != 1){
                    return response()->json(['data'=>null,'desecption'=>'预约失败','state'=>2]);exit;
                }
            }
            if($list['p_id']=='151'){
                $pingan['sign']='8d7f2da4dbea44c25f24ba578fc7d817';
                $pingan['api_name']='sysPState';
                $pingan['order_num']=$list['order_num'];
                $pingan['state']='04';
                $pian=$this->https_post('https://web.sudianwang.com/api/v1/WebInter/orderApi', $pingan);
            }
            // 日志
            $this->addAppLog($input['admin_id'],$input['dediips'],'派工单('.$input['phoneType'].')','预约安装',"订单(".$list['serial_number'].")",$list['sys_num']);
            return response()->json(['data'=>null,'desecption'=>'预约成功','state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>'预约失败','state'=>2]);exit;
        }
    }


    /**
     * @name 记录
     * @author he <2019.2.27>
     */
    public function addptrz($name,$centent){
        $rz['operating']=$name;
        $rz['centent']=$centent;
        DB::table('ptrz')->insert($rz);

    }

    // 订单操作时间
    function operating_time($num,$type,$time,$admin_acc){
        $data['serial_number']=$num;
        $data['is_type']=$type;
        $data['create_time']=$time;
        $data['create_name']=$admin_acc;

        $result = DB::table('order_time')->insert($data);
        if($result){
            return 1;exit;
        }else{
            return 2;exit;
        }
    }


    /**
     * @name 在线状态
     * @param type
     * @param state
     * @param admin_id  服务商id
     * @return json
     * @author he <2019.2.27>
     */
    public function Json_installstate(Request $request) {
       // return 11;exit;
        $input = $request->only('type','state','admin_id');
        if($request->input('type') == '1'){
            if($request->input('state') == '1' || $request->input('state') == '2'){
                $poss['install_state'] = $input['state'];
                $res = DB::table('install_person')->where('id',$input['admin_id'])->update($poss);
                if($res){
                    return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
                }
            }else{
                return response()->json(['data'=>null,'desecption'=>'参数错误','state'=>3]);exit;
            }

        }elseif($request->input('type') == '2'){
            $res = DB::table('install_person')->where('id',$input['admin_id'])->value('install_state');
            if($res){
                return response()->json(['data'=>$res,'desecption'=>'成功','state'=>1]);exit;
            }else{
                return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
            }
        }
    }

    /**
     * @name 评分列表(技师)
     * @param limit 页数
     * @param admin_id  技师id
     * @return json
     * @author he <2019.2.27>
     */
    public function Json_score_list(Request $request){
        $input = $request->only('admin_id','limit');
        $install_info =InstallPerson::where('id',$input['admin_id'])->first();
        if($install_info){
            //$install_info=$install_info->toArray();
            if($install_info['install_is_type']<>1){
                return response()->json(['data'=>null,'desecption'=>'该账号已停用','state'=>3]);exit;
            }
            $time=date('Y-m-d');
            $time2=date("Y-m-d",strtotime('-90 day'));
            if($request->input('limit')>1){
                //$limit=(($input['limit']-1)*15).",15";
                $offset =($input['limit']-1)*15;
            }else{
                //$limit="0,15";
                $offset = 0;
            }

           // DB::connection()->enableQueryLog();#开启执行日志
           $list = DB::table('install_evaluation')->where(['ineva_coke'=>$install_info['check_code']])->where('ineva_time','>',$time2)->where('ineva_time','<',$time.'23:59:59')->offset($offset)->limit('15')->get()->toArray();
            //print_r(DB::getQueryLog());
            if($list){
                foreach($list as $k=>$v){
                    $json['ineva'][$k]['ineva_time']=substr($v['ineva_time'],0,10);
                    $json['ineva'][$k]['ineva_centent']=$v['ineva_centent'];
                }
                $ineva_score = DB::table('install_evaluation')->where(['ineva_coke'=>$install_info->check_code])->where('ineva_time','>',$time2)->where('ineva_time','<',$time.'23:59:59')->avg('ineva_score');
                $json['ineva_score']=sprintf("%.1f",$ineva_score);//评分

                $json['evaluation_num'] = DB::table('install_evaluation')->where(['ineva_coke'=>$install_info['check_code']])->where('ineva_time','>',$time2)->where('ineva_time','<',$time.'23:59:59')->count();
                $json['ineva_score']=sprintf("%.1f",$ineva_score);
                return response()->json(['data'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);exit;
            }else{
                return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);exit;
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'查询不到技师','state'=>4]);exit;
        }
    }


    /**
     * @name 评分详情(技师)
     * @param limit 页数
     * @param admin_id  技师id
     * @return json
     * @author he <2019.2.27>
     */
    public function Json_score_detail(Request $request) {
        $input = $request->only('admin_id');
        $install_info = InstallPerson::where('id',$input['admin_id'])->first();
        if($install_info){
            if($install_info->install_is_type<>1){
                return response()->json(['data'=>null,'desecption'=>'账号不可登录','state'=>3]);exit;
            }
            $time=date('Y-m-d');
            $time2=date("Y-m-d",strtotime('-90 day'));

            $num = DB::select("select count(1),inety_type from gone_install_evaltype where inety_coke='".$install_info['check_code']."' and inety_time>'".$time2."' and inety_time<'".$time." 23:59:59' group by inety_type");
            if($num){
                $a1=0;$a2=0;$a3=0;$a4=0;$a5=0;$a6=0;$a7=0;$a8=0;$a9=0;
                foreach( $num as $k => $v ){
                    if($v['inety_type']==1){
                        $a1=$v['count(1)'];
                    }if($v['inety_type']==2){
                        $a2=$v['count(1)'];
                    }if($v['inety_type']==3){
                        $a3=$v['count(1)'];
                    }if($v['inety_type']==4){
                        $a4=$v['count(1)'];
                    }if($v['inety_type']==5){
                        $a5=$v['count(1)'];
                    }if($v['inety_type']==6){
                        $a6=$v['count(1)'];
                    }if($v['inety_type']==7){
                        $a7=$v['count(1)'];
                    }if($v['inety_type']==8){
                        $a8=$v['count(1)'];
                    }if($v['inety_type']==9){
                        $a9=$v['count(1)'];
                    }
                }
                $json['inety_type']=array("全程无忧".$a1,"安装即时".$a2,"安装规范".$a3,"非常专业".$a4,"态度极佳".$a5,"有质保卡".$a6,"不准时服务".$a7,"安装不规范".$a8,"服务态度差".$a9);
                if($input['limit']>1){
                    //$limit=(($input['limit']-1)*15).",15";
                    $offset =$input['limit']*15;
                }else{
                    //$limit="0,15";
                    $offset =0;
                }

               $list = DB::table('install_evaluation')->where('ineva_coke',$install_info->check_code)->where('ineva_time','>',$time2)->where('ineva_time','<',$time.'23:59:59')->select('ineva_time','ineva_centent')->offset($offset)->limit('15')->get()->toArray();
                if($list){
                    foreach($list as $k=>$v){
                        $json['ineva'][$k]['ineva_time']=substr($v['ineva_time'],0,10);
                        $json['ineva'][$k]['ineva_centent']=$v['ineva_centent'];
                    }
                }else{
                    $json['ineva']="";
                }
                return response()->json(['data'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);exit;
            }else{
                return response()->json(['data'=>null,'desecption'=>'查询不到信息','state'=>2]);exit;
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'查询不到技师','state'=>5]);exit;
        }
    }

    /**拒单标签获取
     * @param Request $request
     * @param
     * @return json
     */
    public function Json_refusal_order(Request $request){
        $list = DB::table('setmoney_type')->whereRaw("FIND_IN_SET ('2',lt_group)")->where('lt_parent_id','25')->select('sety_id','sety_name')->get()->toArray();
        if($list){
            return response()->json(['data'=>$this->intToStr($list),'desecption'=>'成功','state'=>1]);exit;
        }else{
            return response()->json(['data'=>$list,'desecption'=>'获取失败','state'=>2]);exit;
        }
    }
    /**@name 账户金额
     * @param admin_id 技师编号
     * @param
     * @return json
     */
    public function Json_money_list(Request $request){
        if($request->isMethod('post')){

            $input= $request->only('admin_id');
            $install_person=M("install_person");//`sdo2o_bluezp`.
            $instal_info=DB::table('install_person')->where('id',$input['admin_id'])->first();
            if($instal_info){
                if($instal_info['install_is_type']<>1){
                    echo '{"data":null,"desecption":"fail","state":3}';exit;//账号不可登录
                }
                $install_account=M("install_account");
                $inacc_price=$install_account->where("inacc_coke='".$instal_info['check_code']."'")->getField("inacc_price");
                if(!$inacc_price){
                    $inacc_price="0.00";
                }
                $json['inacc_price']=$inacc_price;//账号余额
                // 成功
                //echo '{"data":'.$inacc_price.',"desecption":"success","state":1}';exit;
            }else{
                //echo '{"data":null,"desecption":"fail","state":2}';exit;//查询不到技师号
            }
        }else{
            //echo '{"data":null,"desecption":"fail","state":4}';exit;//访问方式错误
        }
    }

    /**
     * @name 获取省
     * @return json
     * @author he <2019.2.27>
     */
    public function Json_search_sheng(Request $request) {
        $res = DB::table('region')->where('reg_level','1')->select('reg_num','reg_name','reg_id')->get();
        return response()->json(['data'=>$this->intToStr($res),'desecption'=>'获取成功','state'=>1]);
    }

    /**
     * @name 获取市
     * @return json
     * @author he <2019.2.27>
     */
    public function Json_search_shi(Request $request) {
        $input = $request->only('ser_type','admin_id','reg_num');
        if($input['ser_type'] == 1){
            $reg_id = DB::table('region')->where('reg_num',$input['reg_num'])->value('reg_id');

            if($reg_id){
                $arc_reids = DB::table('arcover')->where(['arc_serid'=>$input['admin_id'],'arc_shenid'=>$reg_id,'arc_shid'=>'0'])->value('arc_reids');

                $arc_reids=trim($arc_reids,',');
                $arc_reids=explode(',',$arc_reids);
            }else{
                $arc_reids = [];
            }
            $res = DB::table('region')->where('reg_blnum',$input['reg_num'])->select('reg_num','reg_name','reg_id')->get();

            $json=[];
            $num=0;
            foreach( $res as $k=> $v ){
                if(in_array($v['reg_id'],$arc_reids)){
                }else{
                    $json[$num]['reg_num']=$v['reg_num'];
                    $json[$num]['reg_name']=$v['reg_name'];
                    $json[$num]['reg_id']=$v['reg_id'];
                    $num=$num+1;
                }
            }
        }else{
            $reg_id = DB::table('region')->where('reg_num',$input['reg_num'])->value('reg_id');
            if($reg_id){

                $arc_reids = DB::table('install_arcover')->where(['arc_serid'=>$input['admin_id'],'arc_shenid'=>$reg_id,'arc_shid'=>'0'])->value('arc_reids');

                $arc_reids=trim($arc_reids,',');
                $arc_reids=explode(',',$arc_reids);
            }else{
                $arc_reids = [];
            }
            $res = DB::table('region')->where('reg_blnum',$input['reg_num'])->select('reg_num','reg_name','reg_id')->get();
            $json=[];
            $num=0;
            foreach( $res as $k=> $v ){
                if(in_array($v['reg_id'],$arc_reids)){
                }else{
                    $json[$num]['reg_num']=$v['reg_num'];
                    $json[$num]['reg_name']=$v['reg_name'];
                    $json[$num]['reg_id']=$v['reg_id'];
                    $num=$num+1;
                }
            }
        }
        return response()->json(['data'=>$this->intToStr($json),'desecption'=>'获取成功','state'=>1]);
    }

    /**
     * @name 获取县
     * @param reg_num    编号
     * @param ser_type
     * @param admin_id   会员id
     * @param arc_shenid 省id
     * @param arc_shid   市id
     * @param arc_xianid 县id
     * @return json
     * @author he <2019.2.27>
     */
    public function Json_search_xian(Request $request) {
       /* DB::table('order_list')->where('serial_number','P20190327101924129')->delete();
        exit;*/
        //$a = DB::table('install_arcover')->where('arc_serid','618')->delete();
        //dd($a);
        //$b =DB::table('install_arcover')->where('arc_serid','728')->get()->toArray();
        //dd($b);
        $input = $request->only('reg_num','ser_type','install_type','admin_id','arc_shenid','arc_shid');
        if($input['reg_num']!=""){
            $res = DB::table('region')->where('reg_blnum',$input['reg_num'])->select('reg_num','reg_name','reg_id')->get()->toArray();

            foreach( $res as $k => $v ){
                $res[$k]['reg_type']="1"; //标识 1:未添加区域 2:县下的区域全选 3:县下已添加区域
            }

        }else{
           if($input['ser_type'] == '1'){
               $xianid = DB::table('arcover')->where(['arc_serid'=>$input['admin_id'],'arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>'0'])->value('arc_reids');
               $xianid=trim($xianid,",");
               $sxianid = explode(',',$xianid);
               $zhenids = DB::table('arcover')->whereRaw("arc_xianid in (".$xianid.")")->select('arc_xianid','arc_reids')->get()->toArray();

               $zhenum=[];
               $newxianid=[];
               if($zhenids){
                   foreach( $zhenids as $kz => $vz){
                       //dump($vz['arc_xianid']);
                       $newxianid[]=$vz['arc_xianid'];
                       $num[$kz]=count(explode(',',trim($vz['arc_reids'],',')));
                       $zhenum[$vz['arc_xianid']]=$num[$kz];
                   }
               }

               $xianid=$newxianid;

               $reg_num = DB::table('region')->where('reg_id',$input['arc_shid'])->value('reg_num');//查市的编号

               $res = DB::table('region')->where('reg_blnum',$reg_num)->select('reg_num','reg_name','reg_id')->get()->toArray();//查市下的 所有县
               $reg_blnum="";
               $ara=[];
               foreach( $res as $kr => $vr){
                   if(in_array($vr['reg_id'],$xianid)){
                       $ara[$vr['reg_num']]=$vr['reg_id'];
                       $reg_blnum.="'".$vr['reg_num']."',";
                   }
               }

               $reg_blnum=trim($reg_blnum,",");
               $sql="SELECT count(*) as num,reg_blnum FROM `gone_region` WHERE reg_blnum in (".$reg_blnum.") group by reg_blnum";
               $reg_blnums = DB::select($sql);
               $zhenums=[];
               foreach( $reg_blnums as $kb => $vb ){
                   $zhenums[$ara[$vb['reg_blnum']]]=$vb['num'];
               }

               $cha = array_merge(array_diff($sxianid,$xianid),array_diff($xianid,$sxianid));

               if($cha){
                   foreach ($cha as $k=>$v){
                       $reg_num = DB::table('region')->where('reg_id',$v)->value('reg_num');
                       $zen = DB::table('region')->where('reg_blnum',$reg_num)->first();
                       if($zen==null){
                           $ress[] = $v;
                       }
                   }
               }

               foreach( $res as $k => $v){
                   $flag=2;
                   if(in_array($v['reg_id'],$xianid)){
                       if(!empty($zhenum) && ($zhenum[$v['reg_id']]==$zhenums[$v['reg_id']])){
                           $res[$k]['reg_type']="2";
                       }else{
                           $res[$k]['reg_type']="3";  //1:未添加区域 2:县下的区域全选 3:县下已添加区域
                       }
                   }else{
                       $res[$k]['reg_type']="1";
                   }
                   if(isset($ress)){
                       foreach ($ress as $ks=>$vs){
                           if($vs == $v['reg_id']){
                               $res[$k]['reg_type'] = "2";
                           }
                       }
                   }
               }

           }else{
           	//技师
               $xianid = DB::table('install_arcover')->where(['arc_serid'=>$input['admin_id'],'arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>'0'])->value('arc_reids');
               //dd($xianid);
               $xianid=trim($xianid,",");
               $sxianid = explode(',',$xianid);

               $zhenids = DB::table('install_arcover')->whereRaw("arc_xianid in (".$xianid.")")->select('arc_xianid','arc_reids')->get()->toArray();

               $newxianid=[];
               $zhenum=[];
               if($zhenids){//
                   foreach( $zhenids as $kz => $vz){
                       //dump($vz['arc_xianid']);
                       $newxianid[]=$vz['arc_xianid'];
                       $num[$kz]=count(explode(',',trim($vz['arc_reids'],',')));
                       $zhenum[$vz['arc_xianid']]=$num[$kz];
                   }
               }//

               $xianid=$newxianid;
               $reg_num = DB::table('region')->where('reg_id',$input['arc_shid'])->value('reg_num');//查市的编号

               $res = DB::table('region')->where('reg_blnum',$reg_num)->select('reg_num','reg_name','reg_id')->get()->toArray();//查市下的 所有县
               $reg_blnum="";
               $ara=[];
               foreach( $res as $kr => $vr){
                   if(in_array($vr['reg_id'],$xianid)){
                       $ara[$vr['reg_num']]=$vr['reg_id'];
                       $reg_blnum.="'".$vr['reg_num']."',";
                   }
               }

               $reg_blnum=trim($reg_blnum,",");
               if($reg_blnum){
                   $sql="SELECT count(*) as num,reg_blnum FROM `gone_region` WHERE reg_blnum in (".$reg_blnum.") group by reg_blnum";
                   $reg_blnums = DB::select($sql);
               }


               $zhenums=[];
               if($reg_blnums){
                   foreach( $reg_blnums as $kb => $vb ){
                       $zhenums[$ara[$vb['reg_blnum']]]=$vb['num'];
                   }
               }else{
                   $reg_blnums=[];
               }

               $cha = array_merge(array_diff($sxianid,$xianid),array_diff($xianid,$sxianid));

               if($cha){
                   foreach ($cha as $k=>$v){
                       $reg_num = DB::table('region')->where('reg_id',$v)->value('reg_num');
                       $zen = DB::table('region')->where('reg_blnum',$reg_num)->first();
                       if($zen==null){
                           $ress[] = $v;
                       }
                   }
               }
               //dd($res);
               foreach( $res as $k => $v){
                   $flag=2;
                   if(in_array($v['reg_id'],$xianid)){
                       if(!empty($zhenum) && ($zhenum[$v['reg_id']]==$zhenums[$v['reg_id']])){
                           $res[$k]['reg_type']="2";
                       }else{
                           $res[$k]['reg_type']="3";
                       }
                   }else{
                       $res[$k]['reg_type']="1";
                   }
                   if(isset($ress)){
                       foreach ($ress as $ks=>$vs){
                           if($vs == $v['reg_id']){
                               $res[$k]['reg_type'] = "2";
                           }
                       }
                   }
               }
           }
        }
        foreach ($res as $ks=>$vs){
            $res[$ks]['list']=[];
        }
        return response()->json(['data'=>$this->intToStr($res),'desecption'=>'获取成功','state'=>1]);
    }


    /**
     * @name 获取地区
     * @param reg_num 编号
     * @param arc_shenid 省id
     * @param arc_shid   市id
     * @param xianid 县id
     * @param admin_id   会员id
     * @return json
     * @author he <2019.2.28>
     */
    public function Json_search_zhen(Request $request) {
        $input = $request->only('admin_id','reg_num','ser_type','arc_shenid','arc_shid','xianid');
       /* if($input['reg_num']!=""){
            $res = DB::table('region')->where('reg_blnum',$input['reg_num'])->select('reg_num','reg_name','reg_id')->get()->toArray();
            foreach( $res as $k => $v ){
                $res[$k]['reg_type']="2";
            }
        }else{*/
            if($input['ser_type'] == '1'){
                //$arcover =DB::table('arcover');
                $xianid = DB::table('arcover')->where(['arc_serid'=>$input['admin_id'],'arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>$input['xianid']])->value('arc_reids');
                //dd($xianid); //,4921,4922,
                if($xianid){
                    $xianid=trim($xianid,",");
                    $xianid=explode(',',$xianid);
                    $reg_num = DB::table('region')->where('reg_id',$input['xianid'])->value('reg_num'); //查 县的编号
                    //dd($reg_num);130431
                    $res = DB::table('region')->where('reg_blnum',$reg_num)->select('reg_num','reg_name','reg_id')->get()->toArray(); //查县下所有的镇
                    //dd($res);
                    foreach( $res as $k => $v){
                        $flag=2;
                        if(in_array($v['reg_id'],$xianid)){
                            $res[$k]['reg_type']="2"; //是否已选择该镇 1:未选择 2:选择
                        }else{
                            $res[$k]['reg_type']="1";
                        }
                    }
                    //dd($res);
                }else{
                    $reg_num = DB::table('region')->where('reg_id',$input['xianid'])->value('reg_num');//查找县的编号
                    //dd($reg_num); ‘130432’ 广平县
                    $res = DB::table('region')->where('reg_blnum',$reg_num)->select('reg_num','reg_name','reg_id')->get()->toArray();
                    foreach( $res as $k => $v ){
                        $res[$k]['reg_type']="1";
                    }
                    //dd($res); //查县下所有的镇
                }

            }else{
                //$arcover = DB::table('install_arcover');
                $xianid = DB::table('install_arcover')->where(['arc_serid'=>$input['admin_id'],'arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>$input['xianid']])->value('arc_reids');
                if($xianid){
                    $xianid=trim($xianid,",");
                    $xianid=explode(',',$xianid);
                    //$reg_num = DB::table('region')->where('reg_id',$input['xianid'])->value('reg_num'); //查 县的编号
                    $reg_num = DB::table('region')->where('reg_id',$input['xianid'])->value('reg_num');
                    $res = DB::table('region')->where('reg_blnum',$reg_num)->select('reg_num','reg_name','reg_id')->get()->toArray();
                    foreach( $res as $k => $v){
                        $flag=2;
                        if(in_array($v['reg_id'],$xianid)){
                            $res[$k]['reg_type']="2";
                        }else{
                            $res[$k]['reg_type']="1";
                        }
                    }

                }else{
                    $reg_num = DB::table('region')->where('reg_id',$input['xianid'])->value('reg_num');
                    $res = DB::table('region')->where('reg_blnum',$reg_num)->select('reg_num','reg_name','reg_id')->get()->toArray();
                    foreach( $res as $k => $v ){
                        $res[$k]['reg_type']="1";
                    }
                }
            }
        //}
        if(empty($res)){
        	return response()->json(['data'=>$this->intToStr($res),'desecption'=>'无下级区域','state'=>2]);

        }else{
        	return response()->json(['data'=>$this->intToStr($res),'desecption'=>'获取成功','state'=>1]);

        }

    }

    /**
     * @name 添加区域
     * @param ser_type 1:技师  2:服务商
     * @param reg_num 编号
     * @param arc_shenid 所属省id
     * @param arc_shid   所属市id
     * @param xianid     县级id
     * @param xianids     县级id组（逗号分隔）
     * @param zhenid     镇级id
     * @param zhenids    镇id组（逗号分隔）
     * @param admin_id   会员id
     * @param arc_type   是否全选 1:全选 2:不全选(批量操作时用)
     * @return json
     * @author he <2019.3.7>
     */
    public function Json_add_area(Request $request) {
        $input = $request->only('ser_type','reg_num','arc_shenid','arc_shid','xianid','xianids','zhenid','zhenids','admin_id','arc_type');
        //dd($input);
        if($input['ser_type'] == 1 ){ //服务商
            $shenid = DB::table('arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>'0','arc_xianid'=>'0','arc_serid'=>$input['admin_id']])->value('arc_reids');
            //dd($shenid);//'39'
            if($shenid){
                $shi=trim($shenid,',');
                $shi=explode(',',$shi);
                if(in_array($input['arc_shid'],$shi)){
                    $res=1;
                }else{
                    $poss['arc_reids']=$shenid.$input['arc_shid'].",";
                    $res =DB::table('arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>'0','arc_xianid'=>'0','arc_serid'=>$input['admin_id']])->update($poss);
                }
                //dd($res);
            }else{
                $poss['arc_reids']=",".$input['arc_shid'].",";
                $poss['arc_shenid']=$input['arc_shenid'];
                $poss['arc_shid']="0";
                $poss['arc_xianid']="0";
                $poss['arc_serid']=$input['admin_id'];
                $res=DB::table('arcover')->insert($poss);
                //dd($res);
            }
            if($res){
                if($input['arc_type']==1 && $input['xianid']==""){//全选
                    $reg_blnum = DB::table('region')->whereRaw("reg_id in (".$input['xianids'].")")->get()->toArray();
                    //dd($reg_blnum);exit;
                    DB::table('arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_serid'=>$input['admin_id']])->delete();
                    $posa['arc_reids']=",".$input['xianids'].",";
                    $posa['arc_shenid']=$input['arc_shenid'];
                    $posa['arc_shid']=$input['arc_shid'];
                    $posa['arc_xianid']="0";
                    $posa['arc_serid']=$input['admin_id'];
                    DB::table('arcover')->insert($posa);
                    //exit;
                    $reg_nums="";
                    foreach( $reg_blnum as $k => $v ){
                        $reg_nums.="'".$v['reg_num']."',";
                    }
                    $reg_nums=trim($reg_nums,',');

                    $reg_num = DB::table('region')->whereRaw("reg_blnum in (".$reg_nums.")")->select('reg_id','reg_blnum')->get()->toArray();//获取县级编号

                    //if($input['ser_type']=='1'){
                        $sql="INSERT INTO `gone_arcover`(`arc_serid`, `arc_shenid`, `arc_shid`,`arc_xianid`,`arc_reids`) VALUES ";
                    //}//else{
                    // $sql="INSERT INTO `gone_install_arcover`(`arc_serid`, `arc_shenid`, `arc_shid`,`arc_xianid`,`arc_reids`) VALUES ";
                    //}
                    foreach( $reg_blnum as $kbl => $vbl ){
                        $zhenids[$kbl]=",";
                        foreach( $reg_num as $kn => $vn ){
                            if($vn['reg_blnum']==$vbl['reg_num']){
                                $zhenids[$kbl].=$vn['reg_id'].",";
                            }
                        }
                        if($zhenids[$kbl]!=","){
                            $sql.="('".$input['admin_id']."','".$input['arc_shenid']."','".$input['arc_shid']."','".$vbl['reg_id']."','".$zhenids[$kbl]."'),";
                        }
                    }
                    $sql=rtrim($sql,',');
                    //dump('wq');

                    $ree = DB::insert($sql);
                    return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);
                }else{//不全选
                    $xianid = DB::table('arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>'0','arc_serid'=>$input['admin_id']])->value('arc_reids');
                    //dd($xianid);
                    if($xianid){
                        $xian=trim($xianid,',');
                        $xian=explode(',',$xian);
                        if(in_array($input['xianid'],$xian)){
                            $rea=1;
                        }else{
                            $post['arc_reids']=$xianid.$input['xianid'].",";
                            //dd($post['arc_reids']);
                            $rea = DB::table('arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>'0','arc_serid'=>$input['admin_id']])->update($post);

                        }
                    }else{
                        //exit;
                        $post['arc_reids']=",".$input['xianid'].",";
                        $post['arc_shenid']=$input['arc_shenid'];
                        $post['arc_shid']=$input['arc_shid'];
                        $post['arc_xianid']="0";
                        $post['arc_serid']=$input['admin_id'];
                        $rea = DB::table('arcover')->insert($post);
                    }
                    if($rea){
                        if($request->input('zhenid')!=""){
                            $zhenid=DB::table('arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>$input['xianid'],'arc_serid'=>$input['admin_id']])->value('arc_reids');
                            //dd($zhenid);
                            if($zhenid){
                                $posz['arc_reids']=$zhenid.$input['zhenid'].",";
                                $ren = DB::table('arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>$input['xianid'],'arc_serid'=>$input['admin_id']])->update($posz);

                            }else{
                                $posz['arc_reids']=",".$input['zhenid'].",";
                                $posz['arc_shenid']=$input['arc_shenid'];
                                $posz['arc_shid']=$input['arc_shid'];
                                $posz['arc_xianid']=$input['xianid'];
                                $posz['arc_serid']=$input['admin_id'];
                                $ren = DB::table('arcover')->insert($posz);
                                // exit;
                            }
                            if($ren){
                                return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
                            }else{
                                return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
                            }
                        }else{
                            $zhenid = DB::table('arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>$input['xianid'],'arc_serid'=>$input['admin_id']])->value('arc_reids');
                            //dd($zhenid);
                            if($input['arc_type']==1){
                                if($zhenid){
                                    $posz['arc_reids']=",".$input['zhenids'].",";
                                    //dd($posz['arc_reids']);
                                    $ren = DB::table('arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>$input['xianid'],'arc_serid'=>$input['admin_id']])->update($posz);
                                }else{
                                    $posz['arc_reids']=",".$input['zhenids'].",";
                                    $posz['arc_shenid']=$input['arc_shenid'];
                                    $posz['arc_shid']=$input['arc_shid'];
                                    $posz['arc_xianid']=$input['xianid'];
                                    $posz['arc_serid']=$input['admin_id'];
                                    $ren=DB::table('arcover')->insert($posz);
                                }
                                if($ren){
                                    return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
                                }else{
                                    return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
                                }
                            }else{
                                $reg_blnum = DB::table('region')->where('reg_id',$input['xianid'])->value('reg_num');
                                //dd($reg_blnum);
                                $reg_num = DB::table('region')->where('reg_blnum',$reg_blnum)->get()->toArray();
                                //dd($reg_num);
                                $zhenids=",";
                                foreach( $reg_num as $k => $v ){
                                    $zhenids.=$v['reg_id'].",";
                                }
                                //dd($zhenids);
                                if($zhenids==","){
                                    $ret=1;
                                }else{
                                    if($zhenid){
                                        $poss['arc_reids']=$zhenids;
                                        $ret = DB::table('arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>$input['xianid'],'arc_serid'=>$input['admin_id']])->update($poss);

                                    }else{
                                        $poss['arc_reids']=$zhenids;
                                        $poss['arc_shenid']=$input['arc_shenid'];
                                        $poss['arc_shid']=$input['arc_shid'];
                                        $poss['arc_xianid']=$input['xianid'];
                                        $poss['arc_serid']=$input['admin_id'];
                                        $ret = DB::table('arcover')->insert($poss);
                                    }
                                }
                                if($ret){
                                    return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
                                }else{
                                    return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
                                }
                            }
                        }
                    }else{
                        return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
                    }
                }
            }else{
                return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
            }

        }else{//技师
            $shenid = DB::table('install_arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>'0','arc_xianid'=>'0','arc_serid'=>$input['admin_id']])->value('arc_reids');
            //dd($shenid);//'39'
            if($shenid){
                $shi=trim($shenid,',');
                $shi=explode(',',$shi);
                if(in_array($input['arc_shid'],$shi)){
                    $res=1;
                }else{
                    $poss['arc_reids']=$shenid.$input['arc_shid'].",";
                    $res =DB::table('install_arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>'0','arc_xianid'=>'0','arc_serid'=>$input['admin_id']])->update($poss);
                }
                //dd($res);
            }else{
                $poss['arc_reids']=",".$input['arc_shid'].",";
                $poss['arc_shenid']=$input['arc_shenid'];
                $poss['arc_shid']="0";
                $poss['arc_xianid']="0";
                $poss['arc_serid']=$input['admin_id'];
                $res=DB::table('install_arcover')->insert($poss);
                //dd($res);
            }
            if($res){
                if($input['arc_type']==1 && $input['xianid']==""){//全选
                    $reg_blnum = DB::table('region')->whereRaw("reg_id in (".$input['xianids'].")")->get()->toArray();
                    //dd($reg_blnum);exit;
                    DB::table('install_arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_serid'=>$input['admin_id']])->delete();
                    $posa['arc_reids']=",".$input['xianids'].",";
                    $posa['arc_shenid']=$input['arc_shenid'];
                    $posa['arc_shid']=$input['arc_shid'];
                    $posa['arc_xianid']="0";
                    $posa['arc_serid']=$input['admin_id'];
                    DB::table('install_arcover')->insert($posa);
                    //exit;
                    $reg_nums="";
                    foreach( $reg_blnum as $k => $v ){
                        $reg_nums.="'".$v['reg_num']."',";
                    }
                    $reg_nums=trim($reg_nums,',');

                    $reg_num = DB::table('region')->whereRaw("reg_blnum in (".$reg_nums.")")->select('reg_id','reg_blnum')->get()->toArray();//获取县级编号

                    //if($input['ser_type']=='1'){
                    $sql="INSERT INTO `gone_install_arcover`(`arc_serid`, `arc_shenid`, `arc_shid`,`arc_xianid`,`arc_reids`) VALUES ";
                    //}//else{
                    // $sql="INSERT INTO `gone_install_arcover`(`arc_serid`, `arc_shenid`, `arc_shid`,`arc_xianid`,`arc_reids`) VALUES ";
                    //}
                    foreach( $reg_blnum as $kbl => $vbl ){
                        $zhenids[$kbl]=",";
                        foreach( $reg_num as $kn => $vn ){
                            if($vn['reg_blnum']==$vbl['reg_num']){
                                $zhenids[$kbl].=$vn['reg_id'].",";
                            }
                        }
                        if($zhenids[$kbl]!=","){
                            $sql.="('".$input['admin_id']."','".$input['arc_shenid']."','".$input['arc_shid']."','".$vbl['reg_id']."','".$zhenids[$kbl]."'),";
                        }
                    }
                    $sql=rtrim($sql,',');
                    //dump('wq');

                    $ree = DB::insert($sql);
                    return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);
                }else{//不全选
                    $xianid = DB::table('install_arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>'0','arc_serid'=>$input['admin_id']])->value('arc_reids');
                    //dd($xianid);
                    if($xianid){
                        $xian=trim($xianid,',');
                        $xian=explode(',',$xian);
                        if(in_array($input['xianid'],$xian)){
                            $rea=1;
                        }else{
                            $post['arc_reids']=$xianid.$input['xianid'].",";
                            //dd($post['arc_reids']);
                            $rea = DB::table('install_arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>'0','arc_serid'=>$input['admin_id']])->update($post);

                        }
                    }else{
                        //exit;
                        $post['arc_reids']=",".$input['xianid'].",";
                        $post['arc_shenid']=$input['arc_shenid'];
                        $post['arc_shid']=$input['arc_shid'];
                        $post['arc_xianid']="0";
                        $post['arc_serid']=$input['admin_id'];
                        $rea = DB::table('install_arcover')->insert($post);
                    }
                    if($rea){
                        if($request->input('zhenid')!=""){
                            $zhenid=DB::table('install_arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>$input['xianid'],'arc_serid'=>$input['admin_id']])->value('arc_reids');
                            //dd($zhenid);
                            if($zhenid){
                                $posz['arc_reids']=$zhenid.$input['zhenid'].",";
                                $ren = DB::table('install_arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>$input['xianid'],'arc_serid'=>$input['admin_id']])->update($posz);

                            }else{
                                $posz['arc_reids']=",".$input['zhenid'].",";
                                $posz['arc_shenid']=$input['arc_shenid'];
                                $posz['arc_shid']=$input['arc_shid'];
                                $posz['arc_xianid']=$input['xianid'];
                                $posz['arc_serid']=$input['admin_id'];
                                $ren = DB::table('install_arcover')->insert($posz);
                                // exit;
                            }
                            if($ren){
                                return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
                            }else{
                                return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
                            }
                        }else{
                            $zhenid = DB::table('install_arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>$input['xianid'],'arc_serid'=>$input['admin_id']])->value('arc_reids');
                            //dd($zhenid);
                            if($input['arc_type']==1){
                                if($zhenid){
                                    $posz['arc_reids']=",".$input['zhenids'].",";
                                    //dd($posz['arc_reids']);
                                    $ren = DB::table('install_arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>$input['xianid'],'arc_serid'=>$input['admin_id']])->update($posz);
                                }else{
                                    $posz['arc_reids']=",".$input['zhenids'].",";
                                    $posz['arc_shenid']=$input['arc_shenid'];
                                    $posz['arc_shid']=$input['arc_shid'];
                                    $posz['arc_xianid']=$input['xianid'];
                                    $posz['arc_serid']=$input['admin_id'];
                                    $ren=DB::table('install_arcover')->insert($posz);
                                }
                                if($ren){
                                    return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
                                }else{
                                    return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
                                }
                            }else{
                                $reg_blnum = DB::table('region')->where('reg_id',$input['xianid'])->value('reg_num');
                                //dd($reg_blnum);
                                $reg_num = DB::table('region')->where('reg_blnum',$reg_blnum)->get()->toArray();
                                //dd($reg_num);
                                $zhenids=",";
                                foreach( $reg_num as $k => $v ){
                                    $zhenids.=$v['reg_id'].",";
                                }
                                //dd($zhenids);
                                if($zhenids==","){
                                    $ret=1;
                                }else{
                                    if($zhenid){
                                        $poss['arc_reids']=$zhenids;
                                        $ret = DB::table('install_arcover')->where(['arc_shenid'=>$input['arc_shenid'],'arc_shid'=>$input['arc_shid'],'arc_xianid'=>$input['xianid'],'arc_serid'=>$input['admin_id']])->update($poss);

                                    }else{
                                        $poss['arc_reids']=$zhenids;
                                        $poss['arc_shenid']=$input['arc_shenid'];
                                        $poss['arc_shid']=$input['arc_shid'];
                                        $poss['arc_xianid']=$input['xianid'];
                                        $poss['arc_serid']=$input['admin_id'];
                                        $ret = DB::table('install_arcover')->insert($poss);
                                    }
                                }
                                if($ret){
                                    return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
                                }else{
                                    return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
                                }
                            }
                        }
                    }else{
                        return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
                    }
                }
            }else{
                return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
            }


        }


    }


    /**
     * @name 删除区域
     * @param reg_num 编号
     * @param arc_shenid 所属省id
     * @param arc_shid   所属市id
     * @param arc_xianid 所属县id
     * @param xianid     县级id
     * @param zhenid     镇级id
     * @param admin_id   会员id
     * @return json
     * @author he <2019.2.28>
     */
    public function Json_delet_area(Request $request) {
        $input = $request->only('ser_type','arc_shenid','arc_shid','xianid','zhenid','admin_id');
       /* if($input['ser_type'] == 1){
            $arcover = DB::table('arcover');
        }else{
            $arcover = DB::table('install_arcover');
        }*/
        //DB::table('arcover')->where('arc_serid','618')->delete();
        //exit;
        if($request->input('zhenid') != ""){
            //关闭镇级数据
            $zhenid=$this->eitare($input['arc_shenid'],$input['arc_shid'],$input['xianid'],$input['zhenid'],$input['admin_id'],$input['ser_type']);
            //dd($zhenid);
            if($zhenid==","){
                $xianid=$this->eitare($input['arc_shenid'],$input['arc_shid'],$input['xianid'],'0',$input['admin_id'],$input['ser_type']);
                if($xianid==","){
                    $shid=$this->eitare($input['arc_shenid'],$input['arc_shid'],'0','0',$input['admin_id'],$input['ser_type']);
                    if($shid==","){
                        $res=$this->eitare($input['arc_shenid'],'0','0','0',$input['admin_id'],$input['ser_type']);
                    }else{
                        $res=$this->saveare($input['arc_shenid'],"0","0",$input['admin_id'],$shid,$input['ser_type']);
                    }
                }else{
                    $res=$this->saveare($input['arc_shenid'],$input['arc_shid'],"0",$input['admin_id'],$xianid,$input['ser_type']);
                }
            }else{
                $res=$this->saveare($input['arc_shenid'],$input['arc_shid'],$input['xianid'],$input['admin_id'],$zhenid,$input['ser_type']);
                //dd($res);
            }
        }else{
            if($request->input('xianid')!=""){
                //关闭县级数据==关闭所有镇
                $xianid=$this->eitare($input['arc_shenid'],$input['arc_shid'],$input['xianid'],'0',$input['admin_id'],$input['ser_type']);
                if($xianid==","){
                    $shid=$this->eitare($input['arc_shenid'],$input['arc_shid'],'0','0',$input['admin_id'],$input['ser_type']);
                    if($shid==","){
                        $res=$this->eitare($input['arc_shenid'],'0','0','0',$input['admin_id'],$input['ser_type']);
                    }else{
                        $res=$this->saveare($input['arc_shenid'],"0","0",$input['admin_id'],$shid,$input['ser_type']);
                    }
                }else{
                    $res=$this->saveare($input['arc_shenid'],$input['arc_shid'],"0",$input['admin_id'],$xianid,$input['ser_type']);
                }
            }else{
                //删除市数据==关闭所有县
                $shid=$this->eitare($input['arc_shenid'],$input['arc_shid'],'0','0',$input['admin_id'],$input['ser_type']);
                if($shid==","){
                    $res=$this->eitare($input['arc_shenid'],'0','0','0',$input['admin_id'],$input['ser_type']);
                }else{
                    $res=$this->saveare($input['arc_shenid'],"0","0",$input['admin_id'],$shid,$input['ser_type']);
                }
            }
        }
        if($res){
            return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
        }
    }


    /**
     * @name 地域整理
     * @param $shenid 省id
     * @param $shid   市id
     * @param $xianid 县id
     * @param $zhenid 镇级id
     * @param $serid
     * @param $ser_type
     * @return json
     * @author he <2019.2.28>
     */
    public function eitare($shenid,$shid,$xianid,$zhenid,$serid,$ser_type){
        /*if($ser_type == 1){
            //$arcover=M("arcover");
            $arcover = DB::table('arcover');
        }else{
            //$arcover=M("install_arcover");
            $arcover = DB::table('install_arcover');
        }*/
        if($ser_type == '1'){
            if($zhenid!="0"){
                $zheng = DB::table('arcover')->where(['arc_shenid'=>$shenid,'arc_shid'=>$shid,'arc_xianid'=>$xianid,'arc_serid'=>$serid])->value('arc_reids');
                $ids=str_replace($zhenid.",","",$zheng);
                //dd($ids);exit;
            }else{
                if($xianid!="0"){
                    DB::table('arcover')->where(['arc_shenid'=>$shenid,'arc_shid'=>$shid,'arc_xianid'=>$xianid,'arc_serid'=>$serid])->delete();
                    $xian = DB::table('arcover')->where(['arc_shenid'=>$shenid,'arc_shid'=>$shid,'arc_xianid'=>'0','arc_serid'=>$serid])->value('arc_reids');
                    $ids=str_replace($xianid.",","",$xian);

                }else{
                    if($shid!="0"){
                        DB::table('arcover')->where(['arc_shenid'=>$shenid,'arc_shid'=>$shid,'arc_serid'=>$serid])->delete();
                        $shi = DB::table('arcover')->where(['arc_shenid'=>$shenid,'arc_shid'=>'0','arc_xianid'=>'0','arc_serid'=>$serid])->value('arc_reids');
                        $ids=str_replace($shid.",","",$shi);
                    }else{
                        $ids = DB::table('arcover')->where(['arc_shenid'=>$shenid,'arc_serid'=>$serid])->delete();
                    }
                }
            }
        }else{
            if($zhenid!="0"){
                $zheng = DB::table('install_arcover')->where(['arc_shenid'=>$shenid,'arc_shid'=>$shid,'arc_xianid'=>$xianid,'arc_serid'=>$serid])->value('arc_reids');
                $ids=str_replace($zhenid.",","",$zheng);
                //dd($ids);exit;
            }else{
                if($xianid!="0"){
                    DB::table('install_arcover')->where(['arc_shenid'=>$shenid,'arc_shid'=>$shid,'arc_xianid'=>$xianid,'arc_serid'=>$serid])->delete();
                    $xian = DB::table('install_arcover')->where(['arc_shenid'=>$shenid,'arc_shid'=>$shid,'arc_xianid'=>'0','arc_serid'=>$serid])->value('arc_reids');
                    $ids=str_replace($xianid.",","",$xian);

                }else{
                    if($shid!="0"){
                        DB::table('install_arcover')->where(['arc_shenid'=>$shenid,'arc_shid'=>$shid,'arc_serid'=>$serid])->delete();

                        $shi = DB::table('install_arcover')->where(['arc_shenid'=>$shenid,'arc_shid'=>'0','arc_xianid'=>'0','arc_serid'=>$serid])->value('arc_reids');

                        $ids=str_replace($shid.",","",$shi);

                    }else{
                        $ids = DB::table('install_arcover')->where(['arc_shenid'=>$shenid,'arc_serid'=>$serid])->delete();
                    }
                }
            }
        }

        return $ids;
    }


    /**
     * @name 保存地域编辑
     * @param $shenid 省id
     * @param $shid   市id
     * @param $xianid 县id
     * @param $serid
     * @param $arc_reids 覆盖区域id
     * @param $ser_type
     * @return json
     * @author he <2019.2.28>
     */
    public function saveare($shenid,$shid,$xianid,$serid,$arc_reids,$ser_type){
        if($ser_type == '1'){
            $poss['arc_reids']=$arc_reids;
            $res=DB::table('arcover')->where(['arc_shenid'=>$shenid,'arc_shid'=>$shid,'arc_xianid'=>$xianid,'arc_serid'=>$serid])->update($poss);
            return $res;
        }else{
            $poss['arc_reids']=$arc_reids;
            //DB::connection()->enableQueryLog();
            $res=DB::table('install_arcover')->where(['arc_shenid'=>$shenid,'arc_shid'=>$shid,'arc_xianid'=>$xianid,'arc_serid'=>$serid])->update($poss);
           // print_r(DB::getQueryLog());
            return $res;
        }

    }

    /**
     * @name 显示覆盖区域
     * @param ser_type
     * @param install_type
     * @param admin_id
     * @return json
     * @author he <2019.2.28>
     */
    public function Json_show_area(Request $request){
        //DB::table('install_arcover')->where('arc_serid','618')->delete();
        //exit;
        //$a = DB::table('install_arcover')->where('arc_serid','728')->where('arc_shenid','4')->get()->toArray();
        //dd($a);
        $input = $request->only('ser_type','admin_id');
        if($input['ser_type'] == 1){
            $arcover=DB::table("arcover");
        }else{
            $arcover=DB::table("install_arcover");
        }
        //$shi=$arcover->where("arc_serid='".$_POST['admin_id']."' and arc_shenid!='0' and arc_shid!='0' and arc_xianid='0'")->field('arc_shenid,arc_shid,arc_reids')->order('arc_shenid desc')->select();
        $shi = $arcover->where('arc_serid',$input['admin_id'])->where('arc_shenid','!=','0')->where('arc_shid','!=','0')->where('arc_xianid','0')->select('arc_shenid','arc_shid','arc_reids')->orderBy('arc_shenid','DESC')->get()->toArray();
        //dd($shi);
        //获取市列表
        if($shi){
            $xianids="";
            foreach( $shi as $k => $v ){
                $xianids.=rtrim($v['arc_reids'],",");
            }
            $shes=DB::table('region')->whereRaw("reg_level=1 or reg_level=2")->select('reg_id','reg_name')->get()->toArray();
            foreach( $shes as $ks => $vs ){
                $shess[$vs['reg_id']]=$vs['reg_name'];
            }
            $xianids=trim($xianids,",");
            $xian=DB::table('region')->whereRaw("reg_id in (".$xianids.")")->select('reg_id','reg_name')->get()->toArray();
            $xians=[];
            //dd($xian);
            foreach( $xian as $kx => $vx ){
                $xians[$vx['reg_id']]=$vx['reg_name'];
            }
            //dump($xians);
            foreach( $shi as $ki => $vi ){
                $shi[$ki]['reg_num'] = DB::table('region')->where('reg_id',$vi['arc_shid'])->value('reg_num');
                $shi[$ki]['sheng']=$shess[$vi['arc_shenid']];
                $shi[$ki]['shi']=$shess[$vi['arc_shid']];
                if($vi['arc_reids'] !=''){
                    $arc_reids[$ki]=trim($vi['arc_reids'],',');
                    $arc_reids[$ki]=explode(",",$arc_reids[$ki]);
                }

                //dump($arc_reids[$ki]);
                if(isset($arc_reids[$ki])){
                    foreach( $arc_reids[$ki] as $kxi => $vxi ){
                        if(isset($xians[$vxi])){
                            $shi[$ki]['xian'][$kxi]=$xians[$vxi];
                        }else{

                        }
                    }
                }
            }

            return response()->json(['data'=>$this->intToStr($shi),'desecption'=>'获取成功','state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);exit;
        }
    }

    /**
     * @name 新闻公告
     * @param limit 页码
     * @return json
     * @author he <2019.2.28>
     */
    public function Json_manageapp (Request $request){
        $input = $request->only('limit');
        if($input['limit']){
            if($request->input('type') == '1'){
                $offset = ($input['limit']-1)*3;
                $limit = 3;
            }else{
                $offset = ($input['limit']-1)*10;
                $limit = 10;
            }

        }else{
            $offset = 0;
        }
        $res = DB::table('manageapp')->where('app_type','2')->offset($offset)->limit($limit)->select('app_tittle','app_id','app_pic','app_time','app_describe')->orderBy('app_time','DESC')->get();
        if(!$res->isEmpty()){
            $res=$res->toArray();
            foreach ($res as $k=>$v){
            	$res[$k]['app_pic'] = 'http://img.sudianwang.com/SDKB/Uploads/APP_xinw/new_logo.png';//$this->picurl($v['app_pic']);
                $res[$k]['app_time'] = date('Y-m-d');
            }
            return response()->json(['data'=>$this->intToStr($res),'desecption'=>'获取成功','state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);exit;
        }

    }



    function sms_note($mobile,$content){
        $username = "sdkb";
        $pwd = "9m4uva2m";
        $password = md5($username."".md5($pwd));

        $url = "http://www1.jc-chn.cn/smsSend.do?";

        $param = http_build_query(
            array(
                'username'=>$username,
                'password'=>$password,
                'mobile'=>$mobile,
                // 'content'=>iconv("GB2312","UTF-8",$content)
                'content'=>$content
            )
        );

        $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,$param);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    //意见反馈
    /*
	opf_creact： 反馈人     opf_centent：反馈内容		opf_tittle：反馈标题		opf_serid:反馈人id
	*/
    public function Json_opinion_feedback(Request $request){
        $input = $request->only('opf_creact','opf_centent','opf_tittle');
        $input['opf_serid'] = $request->input('admin_id');
        $input['opf_creact'] = DB::table('admin')->where('id',$input['opf_serid'])->value('admin_acc');
        //dd($input);
        $res = DB::table('opinion_feedback')->insert($input);
        if($res){
            return response()->json(['data'=>null,'desecption'=>"反馈成功",'state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>"反馈失败",'state'=>2]);exit;
        }
    }

    //发送验证码
    public function Json_verification_code(Request $request){
        //dd('1');
        $input=$request->only('is_type','ser_type','phone','admin_id','code','phc_type');
        if($input['is_type'] == 1){
            if($input['ser_type'] == 1){
                //$phone=$admin_infor->where("phone='".$_POST['phone']."'")->find();
                $phone = DB::table('admin_infor')->where('phone',$input['phone'])->first();
            }else{
                $phone = DB::table('install_person')->where('install_phone',$input['phone'])->first();
                $phone['admin_id']=$phone['id'];
            }
            if($phone){
                $res = DB::table('phone_coke')->whereRaw("phc_phone='".$input['phone']."' AND phc_expirationtime>'".date("Y-m-d H:i:s")."' and phc_sertype='".$input['ser_type']."'")->first();
                if($res){
	                $code=(string)$res['phc_coke'];
                    return response()->json(['data'=>$code,'desecption'=>"验证码未过期",'state'=>4]);exit;
                }else{
                    $code=rand(100000,999999);
                    $code=(string)$code;
                    $content="您本次的验证码为".$code.",有效时间为十分钟,请勿告诉他人";//内容
                    //$sms=$this->sms_note($input['phone'],$content);
                    $sms =1;
                    if($sms>0){
                        $poss['phc_phone']=$input['phone'];
                        $poss['phc_coke']=$code;
                        $time=date("Y-m-d H:i:s");
                        $poss['phc_creacttime']=$time;//创建时间
                        $poss['phc_type']='1';//验证码类行
                        $poss['phc_expirationtime']=date('Y-m-d H:i:s', strtotime($time) + 60);;//过期时间
                        $poss['phc_sertype']=$input['ser_type'];//用户身份1门店2技师
                        //$phone_coke->add($poss);
                        DB::table('phone_coke')->insert($poss);
                        //echo '{"data":[{code:"'.$code.'",phone:"'.$_POST['phone'].'",admin_id:"'.$phone['admin_id'].'"}],"desecption":"succes","state":1}';exit;
                        $data=['code'=>$code,'phone'=>$input['phone']];

                        return response()->json(['data'=>$code,'desecption'=>"返回验证码成功",'state'=>1]);exit;
                    }else{
                        return response()->json(['data'=>null,'desecption'=>"返回验证码失败",'state'=>2]);exit;
                    }
                }
            }else{
                return response()->json(['data'=>null,'desecption'=>"没有该手机号",'state'=>6]);exit;
            }
        }elseif($input['is_type']==2){
            if($input['ser_type'] == 1){
                //$phone=$admin_infor->where("phone='".$_POST['phone']."'")->find();
                $phone = DB::table('admin_infor')->where('phone',$input['phone'])->first();
            }else{
                $phone = DB::table('install_person')->where('install_phone',$input['phone'])->first();
            }
            if(!$phone){
                $res = DB::table('phone_coke')->whereRaw("phc_phone='".$input['phone']."' AND phc_expirationtime>'".date("Y-m-d H:i:s")."' and phc_sertype='".$input['ser_type']."'")->first();
                if($res){
	                $code=(string)$res['phc_coke'];
                    return response()->json(['data'=>$code,'desecption'=>"验证码未过期",'state'=>4]);exit;
                }else{
                    $code=rand(100000,999999);
                    $code=(string)$code;
                    $content="您本次的验证码为".$code.",有效时间为十分钟,请勿告诉他人";//内容
                    //$sms=$this->sms_note($input['phone'],$content);
                    $sms =1;
                    if($sms>0){
                        $poss['phc_phone']=$input['phone'];
                        $poss['phc_coke']=$code;
                        $time=date("Y-m-d H:i:s");
                        $poss['phc_creacttime']=$time;//创建时间
                        $poss['phc_type']='1';//验证码类行
                        $poss['phc_expirationtime']=date('Y-m-d H:i:s', strtotime($time) + 60);;//过期时间
                        $poss['phc_sertype']=$input['ser_type'];//用户身份1门店2技师
                        //$phone_coke->add($poss);
                        DB::table('phone_coke')->insert($poss);
                        //echo '{"data":[{code:"'.$code.'",phone:"'.$_POST['phone'].'",admin_id:"'.$phone['admin_id'].'"}],"desecption":"succes","state":1}';exit;
                        $data=['code'=>$code,'phone'=>$input['phone']];

                        return response()->json(['data'=>$code,'desecption'=>"返回验证码成功",'state'=>1]);exit;
                    }else{
                        return response()->json(['data'=>null,'desecption'=>"返回验证码失败",'state'=>2]);exit;
                    }
                }
            }else{
                return response()->json(['data'=>null,'desecption'=>"手机号已存在",'state'=>6]);exit;
            }
        }elseif($input['is_type']==4){

            $phc_type = $input['phc_type'] ? $input['phc_type'] : '1';
           // DB::connection()->enableQueryLog();
            $res = DB::table('phone_coke')->whereRaw("phc_phone='".$input['phone']."' AND phc_type='".$phc_type."' AND phc_coke='".$input['code']."' and phc_sertype='".$input['ser_type']."'")->orderBY('phc_id','desc')->first();

            if(!isset($res)){
            	return response()->json(['data'=>null,'desecption'=>"不存在",'state'=>1]);exit;
            }

           // print_r(DB::getQueryLog());
            $exptime = $res['phc_expirationtime'];
            $nowtime = date("Y-m-d H:i:s");


            if($exptime<$nowtime){
            	return response()->json(['data'=>null,'desecption'=>"验证码失效",'state'=>2]);exit;
            }else{
            	return response()->json(['data'=>null,'desecption'=>"验证成功",'state'=>1]);exit;
            }

        }else{
	        return response()->json(['data'=>null,'desecption'=>"请求状态不存在",'state'=>2]);exit;
        }
    }


    /**
     * @name  技师端订单列表(施工中)
     * @param
     * @param limit 页数
     * @param admin_id
     * @return json
     * @author he <2019.3.13>
     */
    public function Linelist(Request $request){
        $input=$request->only('state','limit','admin_id','user_name','user_phone','start_time','end_time','admin_id');
        $where="";
        if(!empty($request->input('user_name')) && empty($request->input('user_phone'))){
            $where.=" AND `shr_name`='".$request->input('user_name')."'";

        }elseif(empty($request->input('user_name')) && !empty($request->input('user_phone'))){
            $where.=" AND `shr_phone`='".$request->input('user_phone')."'";

        }elseif(!empty($request->input('user_name')) && !empty($request->input('user_phone'))){
            $where.=" AND `shr_phone`='".$request->input('user_phone')."' AND `shr_name`='".$request->input('user_name')."'";
        }else{

        }

        if(!empty($request->input('start_time')) && !empty($request->input('end_time'))){
            $where.= " AND a.create_time >= '".$request->input('start_time')." 00:00:00' AND a.create_time <='".$request->input('end_time')." 23:59:59'";
        }elseif(!empty($request->input('start_time')) && empty($request->input('end_time'))){
            $where.=" AND a.create_time >= '".$request->input('start_time')." 00:00:00' AND a.create_time <='".date("Y-m-d")." 23:59:59'";
        }else{
            $where.=" AND (a.create_time > '2016-08-01 00:00:01') ";
        }

        //$page = $input['limit'];//分页
        $limit = (($input['limit'] - 1) * 10).',10';
        $sql = "SELECT id FROM gone_install_person WHERE FIND_IN_SET('".$input['admin_id']."',install_pid)";
        $ids =DB::select($sql);
        //dd($ids);
        foreach($ids as $key=>$val){
            $data[] = $val['id'];
        }
        if(isset($data)){
            $arr = implode(',',$data);
            if($arr[0]){
                $arr = $input['admin_id'].','.implode(',',$data);
            }else{
                $arr = $input['admin_id'];
            }
        }else{
            $arr = $input['admin_id'];
        }
        //DB::connection()->enableQueryLog();
        $sql1 = 'SELECT a.feeds_time,a.id,a.sys_num,a.serial_number,a.goods_name,a.create_time,a.orli_type,a.order_goods_id,line_status,a.install_id,a.stauas,a.locklist_type,b.shr_name,b.shr_phone,b.shr_sheng,b.shr_shi,b.shr_xian,b.shr_adress FROM gone_order_list as a left join gone_user as b on a.customer_id = b.id WHERE a.install_id in ('.$arr.') and a.stauas=30 '.$where.' order by a.create_time desc limit '.$limit;

        $list = DB::select($sql1);
        if($list){
            foreach ($list as $k=>$v){
                $state = DB::table('install_line')->where('line_serm',$v['serial_number'])->value('line_state');
                //$goods_name = DB::table('order_msg')->where('id',$v['order_goods_id'])->value('goods_name');
                $goods_name = DB::table('order_replace')->where('or_serialnum',$v['serial_number'])->where('deal_state','1')->orderBy('creact_time','DESC')->select('or_goodname','deal_state','deal_price','or_goodnum')->first();
                if ($goods_name){
                    $list[$k]['goods_name']=$goods_name['or_goodname'];
                    $list[$k]['deal_state']=$goods_name['deal_state']??0;
                    $list[$k]['deal_price']=$goods_name['deal_price']??0;
                    $list[$k]['goods_num']=$goods_name['or_goodnum']??0;
                }else{
                    $goods_name=DB::table('order_msg')->where('id',$v['order_goods_id'])->select('goods_name','goods_num')->first();
                    $list[$k]['goods_name']=$goods_name['goods_name']??'暂无';
                    $list[$k]['goods_num']=$goods_name['goods_num']??'0';
                    $list[$k]['deal_state']=0;
                }
                $install =DB::table('install_person')->where('id',$v['install_id'])->select('check_code','install_pic','install_name')->first();

                $list[$k]['line_state']=$state??'暂无';
                //$list[$k]['goods_name']=$goods_name??'暂无';
                $list[$k]['check_code']=$install['check_code']??'';
                $list[$k]['install_pic']=$install['install_pic']??'';
                $list[$k]['install_name']=$install['install_name']??'';
                $serm[]=$v['serial_number'];
                //$admin_id = DB::table('install_person')->where('id', $input['admin_id'])->value('admin_id');
                $note_num = DB::table('note')->whereRaw("`orders_id`='" . $v['sys_num'] . "' AND `public_state`=2 AND (note_group!=2 or note_installid='" . $input['admin_id'] . "')")->count();
                $list[$k]['note_num'] = $note_num??0;
            }
            //dd($serm);
            /* foreach ($list as $k=>$v){

                 $goods_name = DB::table('order_msg')->where('id',$v['order_goods_id'])->value('goods_name');
                 $list[$k]['goods_name']=$goods_name;
             }*/


            $timeList =DB::table('order_time')->whereIn('serial_number',$serm)->where('is_type','接单时间')->select('create_time','serial_number')->get()->toArray();

            if($timeList){
                foreach ($timeList as $ks=>$vs){
                    $timeArr[$vs['serial_number']]=$vs['create_time'];
                    $serial_number[]=$vs['serial_number'];
                }
                //dd($list);
                foreach ($list as $ks=>$vs){
                    //$json[$k]['shr_name']=$vs['user']['shr_name'];
                    //if($serial_number){
                    if(in_array($vs['serial_number'],$serial_number)) {
                        $list[$ks]['ricvetime'] =$timeArr[$vs['serial_number']];
                    }else{
                        $list[$ks]['ricvetime']=date('Y-m-d h:i:s');
                    }

                }
            }
            return response()->json(['data'=>$this->intToStr($list),'desecption'=>"成功",'state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>"暂无数据",'state'=>2]);exit;
        }

    }

    /**
     * @name  技师端订单列表(催单中)
     * @param state 状态 1：施工中；2：催单中；3：售后中；4已完成
     * @param limit 页数
     * @param admin_id
     * @return json
     * @author he <2019.3.21>
     */
    public function Linelist_two(Request $request){
        $input=$request->only('state','limit','admin_id','user_name','user_phone','start_time','end_time');
        $where="reminder=1 and stauas<34";
        if(!empty($request->input('user_name')) && empty($request->input('user_phone'))){
            $where.=" AND `shr_name`='".$request->input('user_name')."'";

        }elseif(empty($request->input('user_name')) && !empty($request->input('user_phone'))){
            $where.=" AND `shr_phone`='".$request->input('user_phone')."'";

        }elseif(!empty($request->input('user_name')) && !empty($request->input('user_phone'))){
            $where.=" AND `shr_phone`='".$request->input('user_phone')."' AND `shr_name`='".$request->input('user_name')."'";
        }else{

        }

        if(!empty($request->input('start_time')) && !empty($request->input('end_time'))){
            $where.= " AND gone_a.create_time >= '".$request->input('start_time')." 00:00:00' AND gone_a.create_time <='".$request->input('end_time')." 23:59:59'";
        }elseif(!empty($request->input('start_time')) && empty($request->input('end_time'))){
            $where.=" AND gone_a.create_time >= '".$request->input('start_time')." 00:00:00' AND gone_a.create_time <='".date("Y-m-d")." 23:59:59'";
        }else{
            $where.=" AND (gone_a.create_time > '2016-08-01 00:00:01') ";
        }
        if($request->input('limit')){
            $limit=($input['limit']-1)*10;
        }else{
            $limit = 0;
        }
        /*$page = $input['limit'];//分页
        $limit = (($page - 1) * 10).',10';
        $limit = ($page-1)*10;*/
        $sql = "SELECT id FROM gone_install_person WHERE FIND_IN_SET('".$input['admin_id']."',install_pid)";
        $ids =DB::select($sql);

        foreach($ids as $key=>$val){
            $data[] = $val['id'];
        }
        if(isset($data)){
            $arr = implode(',',$data);
            if($arr[0]){
                $arr = $input['admin_id'].','.implode(',',$data);
            }else{
                $arr = $input['admin_id'];
            }
        }else{
            $arr = $input['admin_id'];
        }
        $where.=" AND install_id in (".$arr.")";
        $list = DB::table('order_list as a')->leftJoin('user as b','a.customer_id','=','b.id')->whereRaw($where)->select('a.id','a.sys_num','a.serial_number','a.orli_type','a.customer_id','a.create_time','a.feeds_time','a.order_goods_id','a.line_status','a.install_id','a.locklist_type','b.shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress')->orderBy('a.create_time','DESC')->offset($limit)->limit('10')->get()->toArray();
        if($list){
            foreach ($list as $k=>$v){
                $serm[]=$v['serial_number'];
                //$goods_name = DB::table('order_msg')->where('id',$v['order_goods_id'])->value('goods_name');
                $state = DB::table('install_line')->where('line_serm',$v['serial_number'])->value('line_state');
                $list[$k]['line_state']=$state??'0';
                $goods_name = DB::table('order_replace')->where('or_serialnum',$v['serial_number'])->where('deal_state','1')->orderBy('creact_time','DESC')->select('or_goodname','deal_state','deal_price','or_goodnum')->first();
                if ($goods_name){
                    $list[$k]['goods_name']=$goods_name['or_goodname'];
                    $list[$k]['deal_state']=$goods_name['deal_state']??0;
                    $list[$k]['deal_price']=$goods_name['deal_price']??0;
                    $list[$k]['goods_num']=$goods_name['or_goodnum']??0;
                }else{
                    $goods_name=DB::table('order_msg')->where('id',$v['order_goods_id'])->select('goods_name','goods_num')->first();
                    $list[$k]['goods_name']=$goods_name['goods_name']??'暂无';
                    $list[$k]['goods_num']=$goods_name['goods_num']??'0';
                    $list[$k]['deal_state']=0;
                }
            }
            $timeList =DB::table('order_time')->whereIn('serial_number',$serm)->where('is_type','接单时间')->select('create_time','serial_number')->get()->toArray();

            if($timeList){
                foreach ($timeList as $ks=>$vs){
                    $timeArr[$vs['serial_number']]=$vs['create_time'];
                    $serial_number[]=$vs['serial_number'];
                }

                foreach ($list as $ks=>$vs){
                    //$json[$k]['shr_name']=$vs['user']['shr_name'];
                    //if($serial_number){
                    if(in_array($vs['serial_number'],$serial_number)) {
                        $list[$ks]['ricvetime'] =$timeArr[$vs['serial_number']];
                    }else{
                        $list[$ks]['ricvetime']='';
                    }
                    $install =DB::table('install_person')->where('id',$vs['install_id'])->select('check_code','install_pic','install_name')->first();
                    $list[$ks]['check_code']=$install['check_code']??'';
                    $list[$ks]['install_pic']=$this->getUrl().$install['install_pic']??'';
                    $list[$ks]['install_name']=$install['install_name']??'';
                    $admin_id = DB::table('install_person')->where('id', $input['admin_id'])->value('admin_id');
                    $note_num = DB::table('note')->whereRaw("`orders_id`='" . $v['sys_num'] . "' AND `public_state`=2 AND (note_group!=2 or note_adid='" . $admin_id . "')")->count();
                    $list[$ks]['note_num'] = $note_num??0;

                }
            }
            return response()->json(['data'=>$this->intToStr($list),'desecption'=>"成功",'state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>"暂无催单记录",'state'=>2]);exit;
        }

    }

    /**
     * @name 售后订单（售后列表）
     * @param type 1:服务商登录 2：技师登录
     * @param state  售后单状态 1:未处理 2:处理中 3:审核中 4:已完成
     * @param limit 页码
     * @return json
     * @author he <2019.3.5>
     */

    public function Linelist_four(Request $request){

        $input = $request->only('admin_id','state','limit');
        //$page = $input['limit'];//分页
        //$limit = (($page - 1) * 10).',10';
        $sql = "SELECT id FROM gone_install_person WHERE FIND_IN_SET('".$input['admin_id']."',install_pid)";
        $ids =DB::select($sql);
        //dd($ids);
        foreach($ids as $key=>$val){
            $data[] = $val['id'];
        }
        if(isset($data)){
            $arr = implode(',',$data);
            if($arr[0]){
                $arr = $input['admin_id'].','.implode(',',$data);
            }else{
                $arr = $input['admin_id'];
            }
        }else{
            $arr = $input['admin_id'];
        }
        $where="install_id in (".$arr.")";

        switch ( $input['state'] )
        {
            case 1:
                $where.=" and status=1";
                break;
            case 2:
                $where.=" and status=10";
                break;
            case 3:
                $where.=" and status=30";
                break;
            case 4:
                $where.=" and status=40";
                break;
        }

        if($input['limit']){
            $limit=($input['limit']-1)*10;
        }else{
            $limit=0;
        }
       // DB::connection()->enableQueryLog();
        $where .= " and store_type!=5";
        $list = DB::table('order_after')->whereRaw($where)->select('id','sys_num','after_num','serial_number','create_time','shr_name','shr_phone','shr_address','p_id','ser_id','status','shr_sheng','shr_shi','shr_xian','good_names','deal_sertime','deal_firstime','finish_time')->offset($limit)->limit('10')->get()->toArray();
        //print_r(DB::getQueryLog());
        if($list){
            foreach( $list as $ks => $vs ){
                $serial_number[]="'".$vs['serial_number']."'";
            }
            if(isset($serial_number)){

                $serial_number=implode(',',$serial_number);
                if($request->input('type') == 2){
                    $line_time =DB::table('install_line')->whereRaw("line_serm in (".$serial_number.")")->select('line_state','line_serm')->get()->toArray();//查询状态
                    if($line_time){
                        foreach ($line_time as $k=>$v){
                            $lineArr[$v['line_serm']]=$v['line_state'];
                            $linesen[]=$v['line_serm'];
                        }
                    }
                    foreach ($list as $k=>$v){
                        if(in_array($v['serial_number'],$linesen)){
                            $list[$k]['line_type']=$lineArr[$v['serial_number']];
                        }else{
                            $list[$k]['line_type']='';
                        }
                    }
                }

                $time = DB::table('order_time')->whereRaw("serial_number in (".$serial_number.") and (`is_type`='下单时间' or `is_type`='接单时间' or `is_type`='任务反馈时间')")->select('create_time','is_type','serial_number')->get()->toArray();

                if($time){
                    foreach( $time as $km => $vm ){
                        if($vm['is_type']=='下单时间'){
                            $xd_number[]=$vm['serial_number'];
                            $times[$vm['serial_number']]['xd_time']=$vm['create_time'];
                        }elseif($vm['is_type']=='接单时间'){
                            $jd_number[]=$vm['serial_number'];
                            $times[$vm['serial_number']]['jd_time']=$vm['create_time'];
                        }else{
                            $fk_number[]=$vm['serial_number'];
                            $times[$vm['serial_number']]['fk_time']=$vm['create_time']?$vm['create_time']:date("Y-m-d H:i:s");
                        }
                    }

                }

                $score = DB::table('install_evaluation')->whereRaw("ineva_serial in (".$serial_number.")")->select('ineva_score','ineva_serial')->get();

                foreach ($score as $k=>$v){
                    $fen[$v['ineva_serial']]=$v['ineva_score'];
                }
                //dd($fen);exit;
                foreach ($list as $k=>$v){
                    $json[$k]['id']=$v['id'];
                    $json[$k]['status'] = $v['status'];
                    $json[$k]['serial_number']=$v['serial_number']; //派工单号
                    $json[$k]['after_num']=$v['after_num'];//售后单号
                    $json[$k]['shr_name']=$v['shr_name'];//客户姓名
                    $json[$k]['good_name']=$v['good_names'];//客商品名称
                    $json[$k]['score']=$fen[$v['serial_number']]??'0'; //分数
                    $json[$k]['user_address']=trim($v['shr_sheng']).trim($v['shr_shi']).trim($v['shr_xian']).trim($v['shr_address']); //地址
                    $json[$k]['order_action']=$input['state']; //售后单状态码
                    $json[$k]['shr_phone']=$v['shr_phone'];
                    $json[$k]['create_time']=$v['create_time'];
                    $json[$k]['deal_firstime'] = $v['deal_firstime']??'';
                    $json[$k]['deal_sertime'] = $v['deal_sertime'];
                    $json[$k]['time20'] = date("Y-m-d H:i:s",strtotime($v['create_time'])+20*60);
                    $json[$k]['finish_time'] = $v['finish_time'];

                    $json[$k]['xd_time']=$times[$v['serial_number']]['xd_time']??"";
                    $json[$k]['jd_time']=$times[$v['serial_number']]['jd_time']??"";
                    $json[$k]['fk_time']=$times[$v['serial_number']]['fk_time']??"";
                    $admin_id = DB::table('install_person')->where('id', $input['admin_id'])->value('admin_id');
                    $note_num = DB::table('note')->whereRaw("`orders_id`='" . $v['sys_num'] . "' AND `public_state`=2 AND (note_group!=2 or note_adid='" . $admin_id . "')")->count();
                    $json[$k]['note_num'] = $note_num??0;

                }
                return response()->json(['data'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);exit;
            }
            return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);exit;

        }else{
            return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>3]);exit;
        }

    }

    /**
     * @name  技师端订单列表(已完成)
     * @param state 状态 1：施工中；2：催单中；3：售后中；4已完成
     * @param limit 页数
     * @param admin_id
     * @return json
     * @author he <2019.3.21>
     */
    public function Linelist_three(Request $request){
        $input=$request->only('state','limit','admin_id','user_name','user_phone','start_time','end_time');
        $where="reminder=2";
        if(!empty($request->input('user_name')) && empty($request->input('user_phone'))){
            $where.=" AND `shr_name`='".$request->input('user_name')."'";

        }elseif(empty($request->input('user_name')) && !empty($request->input('user_phone'))){
            $where.=" AND `shr_phone`='".$request->input('user_phone')."'";

        }elseif(!empty($request->input('user_name')) && !empty($request->input('user_phone'))){
            $where.=" AND `shr_phone`='".$request->input('user_phone')."' AND `shr_name`='".$request->input('user_name')."'";
        }else{

        }

        if(!empty($request->input('start_time')) && !empty($request->input('end_time'))){
            $where.= " AND create_time >= '".$request->input('start_time')." 00:00:00' AND create_time <='".$request->input('end_time')." 23:59:59'";
        }elseif(!empty($request->input('start_time')) && empty($request->input('end_time'))){
            $where.=" AND create_time >= '".$request->input('start_time')." 00:00:00' AND create_time <='".date("Y-m-d")." 23:59:59'";
        }else{
            $where.=" AND (create_time > '2016-08-01 00:00:01') ";
        }
        if(empty($request->input('limit'))){

        }
        $page = $input['limit'];//分页
        $limit = (($page - 1) * 10).',10';
        $sql = "SELECT id FROM gone_install_person WHERE FIND_IN_SET('".$input['admin_id']."',install_pid)";
        $ids =DB::select($sql);
        //dd($ids);
        foreach($ids as $key=>$val){
            $data[] = $val['id'];
        }
        if(isset($data)){
            $arr = implode(',',$data);
            if($arr[0]){
                $arr = $input['admin_id'].','.implode(',',$data);
            }else{
                $arr = $input['admin_id'];
            }
        }else{
            $arr = $input['admin_id'];
        }
        $where=" AND install_id in (".$arr.")";
        $ssql=" is_delete=1 AND line_status=1 AND stauas>30 AND stauas !=50 AND stauas!=55 AND invalid=1 AND install_id in (".$arr.")";
        $list =DB::table('order_list as a')->leftJoin('user as b','b.id','=','a.customer_id')->select('a.id','a.feeds_time','a.sys_num','a.stauas','a.serial_number','a.locklist_type','a.create_time','a.orli_type','a.feeds_time','a.day_time','a.install_id','a.order_goods_id','a.locklist_type','b.shr_name','b.shr_phone','b.shr_sheng','b.shr_shi','b.shr_xian','b.shr_adress','b.car_make','b.car_line','b.car_model','a.line_status')->whereRaw($ssql)->orderBy('a.id','DESC')->orderBy('a.create_time','DESC')->offset($limit)->limit('10')->get()->toArray();
        if($list){
            $serm = '';
            foreach ($list as $k=>$v){
                $serm .= "'".$v['serial_number']."',";
            }
            $serm=rtrim($serm,',');
            $timeList =DB::table('order_time')->whereRaw("serial_number in (".$serm.")")->where('is_type','接单时间')->select('create_time','serial_number')->get()->toArray();

            if($timeList){
                foreach ($timeList as $ks=>$vs){
                    $timeArr[$vs['serial_number']]=$vs['create_time'];
                    $serial_number[]=$vs['serial_number'];
                }
                foreach ($list as $ks=>$vs){
                    if(in_array($vs['serial_number'],$serial_number)) {
                        $list[$ks]['ricvetime'] =$timeArr[$vs['serial_number']];
                    }else{
                        $list[$ks]['ricvetime']='';
                    }
                }
            }


            foreach ($list as $kq=>$vq){
                $line_type = DB::table('install_line')->where('line_serm',$vq['serial_number'])->value('line_state');
                $goods_name = DB::table('order_replace')->where('or_serialnum',$vq['serial_number'])->where('deal_state','1')->orderBy('creact_time','DESC')->select('or_goodname','deal_state','deal_price','or_goodnum')->first();
                if ($goods_name){
                    $list[$kq]['goods_name']=$goods_name['or_goodname'];
                    $list[$kq]['deal_state']=$goods_name['deal_state']??0;
                    $list[$kq]['deal_price']=$goods_name['deal_price']??0;
                    $list[$kq]['goods_num']=$goods_name['or_goodnum']??0;
                }else{
                    $goods_name=DB::table('order_msg')->where('id',$vq['order_goods_id'])->select('goods_name','goods_num')->first();
                    $list[$kq]['goods_name']=$goods_name['goods_name']??'暂无';
                    $list[$kq]['goods_num']=$goods_name['goods_num']??'0';
                    $list[$kq]['deal_state']=0;
                }
                $list[$kq]['line_state']=$line_type??'暂无';

                //DB::connection()->enableQueryLog();
                $note_num = DB::table('note')->whereRaw("`orders_id`='" . $vq['sys_num'] . "' AND `public_state`=2 AND (note_group!=2 or note_installid='" . $input['admin_id'] . "')")->count();
                //print_r(DB::getQueryLog());

                $list[$kq]['note_num'] = $note_num??0;
				$install =DB::table('install_person')->where('id',$vq['install_id'])->select('check_code','install_pic','install_name')->first();
                $list[$kq]['check_code']=$install['check_code']??'';
                $list[$kq]['install_pic']=$this->getUrl().$install['install_pic']??'';
                $list[$kq]['install_name']=$install['install_name']??'';
            }

            $json=$list;
            return response()->json(['data'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);exit;
        }

    }

    /**
     * @name  技师端订单详情
     * @param serial_number 派工单号
     * @param admin_id
     * @return json
     * @author he <2019.3.13>
     */
    public function Lineinfo(Request $request){
        $input = $request->only('serial_number','admin_id');
        $chkOrder = DB::table('order_list')->where('serial_number',$input['serial_number'])->select('id','serial_number','sys_num','ser_id','order_num','customer_id','p_id','sys_num','install_id','locklist_type','day_time','stauas','line_status')->first();
        $infos = DB::table('install_line')->where('line_serm',$input['serial_number'])->first();
        if($chkOrder['stauas']=='30'){
            if(!$infos){
                $lines['line_serm'] = $input['serial_number'];
                $lines['line_sysnum'] = $chkOrder['sys_num'];
                $lines['line_number'] = $chkOrder['order_num'];
                $lines['line_state'] = 1;
                $lines['line_lasttime'] = date('Y-m-d H:i:s');
                DB::table('install_line')->insert($lines);
            }
        }

        $info = $chkOrder;
        if($info){
	        $score=DB::table('order_score')->where('orsc_sernum',$info['serial_number'])->select('orsc_grade','orsc_type')->get()->toArray();

            $scores['fen1'] = $score[0]['orsc_grade']??'0';
            $scores['fen2'] = $score[1]['orsc_grade']??'0';
            $scores['fen3'] = '5';
            $ineva_score = ($scores['fen1']+$scores['fen2']+$scores['fen3'])/3;
            $info['ineva_score'] =$ineva_score??'1';
            $json['ineva_score']=sprintf("%.1f",$info['ineva_score']);//评分
            //评分
            $info['scores'] =$scores;
            $info['line_state'] = $infos['line_state'];
            $info['line_status'] = $info['line_status'];
            $info['line_start'] = $infos['line_start'];
            $info['line_arrive'] = $infos['line_arrive'];
            $info['line_task'] = $infos['line_task'];
            $info['line_end'] = $infos['line_end'];
            $info['line_lasttime'] = $infos['line_lasttime'];
            $info['line_status']=(string)$info['line_status'];
            //$timeList = M('order_time')->where(array('serial_number'=>$info['serial_number']))->select();
            $timeList = DB::table('order_time')->where('serial_number',$info['serial_number'])->get()->toArray();
            foreach($timeList as $key=>$val){
                $timedata[] = $val['is_type'].":_".$val['create_time'];
            }
            $info['times'] = implode('!',$timedata);
            //客户信息
            //$user = M('user')->where(array('id'=>$info['customer_id']))->field('shr_name,shr_phone,shr_sheng,shr_shi,shr_xian,shr_adress')->find();
            $user = DB::table('user')->where('id',$info['customer_id'])->select('shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress')->first();
            $info['shr_name'] = $user['shr_name'];
            $info['shr_phone'] = $user['shr_phone'];
            $info['shr_sheng'] = $user['shr_sheng'];
            $info['shr_shi'] = $user['shr_shi'];
            $info['shr_xian'] = $user['shr_xian'];
            $info['shr_adress'] = $user['shr_adress'];
            if($info['stauas'] > 30){
                $info['line_state'] = '5';
                $info['line_lasttime'] = '';
            }


            $jingwei = $this->jingwei($info['shr_sheng'],$info['shr_sheng'].$info['shr_shi'].$info['shr_xian'].$info['shr_adress']);
            $info['jingwei'] = $jingwei;



            //平台名称
            $info['p_oname'] = DB::table('pt')->where('id',$info['p_id'])->value('p_oname');
            //商品名称
            $order_msg=DB::table('order_msg')->where('sys_num',$info['sys_num'])->select('goods_name','goods_num')->first();
            $info['goods_name'] = $order_msg['goods_name'];
			$info['goods_num'] = $order_msg['goods_num'];
		 	$info['service_name']='换电瓶'; //服务项目
            $plate = DB::table('carplate_info')->where(array('or_number'=>$info['serial_number']))->select('or_number','can_plate','vehicleID','bar_code')->first();

            //关联车型表
            //$zt_sid = M('zt_bml')->where(array('zt_vehicle'=>$plate['vehicleID']))->getField('zt_sid');
            $zt_sid = DB::table('zt_bml')->where(array('zt_vehicle'=>$plate['vehicleID']))->value('zt_sid');
            //查出车型
            //$xinghao = M('pj_carmatnew')->where(array('pjc_id'=>$zt_sid))->find();
            $xinghao = DB::table('pj_carmatnew')->where(array('pjc_id'=>$zt_sid))->first();
            $info['or_number'] = $plate['or_number'];
            $info['can_plate'] = $plate['can_plate'];
            $info['bar_code'] = $plate['bar_code'];
            if($xinghao){
                $info['carinfo'] = $xinghao['car_series'].$xinghao['car_year'].$xinghao['car_model'].$xinghao['car_models'];//车辆信息
            }else{
                $info['carinfo'] ='未知';
            }
            if($info['install_id'] == $input['admin_id']){
                $info['checks'] = '1';
            }else{
                $info['checks'] = '2';
            }
            unset($info['customer_id']);
            unset($info['p_id']);
            //unset($info['sys_num']);



            $parentname=DB::table('order_sendflow')->where(['os_installid'=>$input['admin_id'],'os_serial'=>$info['serial_number']])->orderBy('os_id','DESC')->value('os_parenid');
            if($parentname){
                $oneinfor = DB::table('install_person')->where('id',$input['admin_id'])->value('install_pid');
                if($oneinfor=='0'){
                    $info['parentname'] = DB::table('admin')->where('id',$parentname)->value('company_name');
                }else{
                    $info['parentname'] = DB::table('admin')->where('id',$parentname)->value('admin_name');//install_name
                }
            }else{
                $info['parentname'] = DB::table('admin')->where('id',$chkOrder['ser_id'])->value('company_name');
            }

            $childrenname=DB::table('order_sendflow')->whereRaw("os_parenid='".$input['admin_id']."' and os_serial='".$info['serial_number']."'")->orderBy('os_id','DESC')->value('os_installid');
            if($childrenname){
                $childrenname=DB::table('install_person')->where('id',$childrenname)->value('install_name');
                $info['childrenname']=$childrenname;
            }else{
                $info['childrenname']='';
            }
            $timess = $info['times'];
            unset($info['times']);
            $info['p_name'] = $info['p_oname'] ? $info['p_oname'] : '速电救援';
            unset($info['p_oname']);
            $arr = explode('!',$timess);
            $info['jd_time'] = '';
            $info['create_time'] = '';
            $info['cftime'] = '';
            $info['ddtime'] = '';
            $info['zytime'] = '';
            $info['feeds_time'] = '';
            foreach($arr as $key=>$val){
                $arr2 = explode(':_',$val);
                switch($arr2[0]){
                    case '派单时间':
                        $info['create_time'] = $arr2[1];
                        break;
                    case '接单时间':
                        $info['jd_time'] = $arr2[1];
                        break;
                    case '出发时间':
                        $info['cftime'] = $arr2[1];
                        break;
                    case '抵达时间':
                        $info['ddtime'] = $arr2[1];
                        break;
                    case '作业时间':
                        $info['zytime'] = $arr2[1];
                        break;
                    case '任务反馈时间':
                        $info['feeds_time'] = $arr2[1];
                        break;
                }
            }

            if($info['stauas']<'34' && $info['feeds_time']!=''){
                DB::table('order_time')->where(array('serial_number'=>$info['serial_number'],'is_type'=>'任务反馈时间'))->delete();
                $info['feeds_time']='';
            }
            if($info['zytime']==''){
                $info['zytime']=$info['feeds_time'];
            }

            $note_num = DB::table('note')->whereRaw("`orders_id`='".$info['sys_num']."' AND `public_state`=2 AND (note_group!=2 or note_installid='".$input['admin_id']."')")->count();
            if($note_num){
                $info['note_num'] = $note_num;
            }else{
                $info['note_num'] = 0;
            }



            return response()->json(['data'=>$this->intToStr($info),'desecption'=>"成功",'state'=>1]);exit;
        }else{
            return response()->json(['data'=>$info,'desecption'=>"获取失败",'state'=>2]);exit;
        }
    }

    //地图轨迹
    public function maptrail(Request $request){
        $input = $request->only('line','eq_type','provinces','city','admin_id');
        $arr = explode(',',$input['line']);
        $data['longitude'] = $arr[1];
        $data['latitude'] = $arr[0];
        $data['last_time']=date("Y-m-d H:i:s");
        $data['eq_type']=$input['eq_type'];
        $data['provinces']=$input['provinces'];
        $data['city']=$input['city'];
        $save = DB::table('install_person')->where('id',$input['admin_id'])->update($data);
        if($save || $save == '0'){
            return response()->json(['data'=>null,'desecption'=>"成功",'state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>"成功",'state'=>2]);exit;
        }

    }


    //终止订单 or 恢复订单
    public function Exitorder(Request $request){

        $input = $request->only('serm','flag','admin_id','dediips','phoneType');

        $install_id = DB::table('order_list')->where('serial_number',$input['serm'])->value('install_id');
        //dd($install_id);
        if($install_id != $input['admin_id']){
            return response()->json(['data'=>null,'desecption'=>"无权操作，联系订单所属技师操作",'state'=>7]);exit;
        }
        $chks = DB::table('install_line')->where('line_serm',$input['serm'])->first();

        DB::beginTransaction();
        if($input['flag'] == 2){
            if($chks['line_status'] == 0){
                return response()->json(['data'=>null,'desecption'=>"订单未被终止",'state'=>3]);exit;
            }
            $title = '恢复订单';
            $line_state = DB::table('order_list')->where('serial_number',$input['serm'])->update(['line_status'=>1]);

            $chk = DB::table('install_line')->where('line_serm',$input['serm'])->update(['line_status'=>0,'line_lasttime'=>date('Y-m-d H:i:s')]);
        }else{

            if($chks['line_state'] == 5){
                return response()->json(['data'=>null,'desecption'=>"订单不可终止",'state'=>4]);exit; //订单不可终止
            }
            if($chks['line_status'] == 1){
                return response()->json(['data'=>null,'desecption'=>"订单已被终止",'state'=>5]);exit;
            }

            $title = '终止订单';
            $line_state = DB::table('order_list')->where('serial_number',$input['serm'])->update(['line_status'=>2]);
            $chk = DB::table('install_line')->where(['line_serm'=>$input['serm']])->update(['line_status'=>1,'line_lasttime'=>date('Y-m-d H:i:s')]);
        }

        if($chk && $line_state){
            DB::commit();
            $number =$chks['line_sysnum'];
            if($request->input('ser_type') == 1){
                // 日志
                $this->addAppLog($input['admin_id'],$input['dediips'],'派工单('.$input['phoneType'].')',$title,"订单(".$input['serm'].")",$number);
            }else{
                // 日志
                $this->AddPersonLog($input['admin_id'],$input['dediips'],'派工单('.$input['phoneType'].')',$title,"订单(".$input['serm'].")",$number);
            }

            return response()->json(['data'=>null,'desecption'=>"操作成功",'state'=>1]);exit;
        }else{
            DB::rollback();
            return response()->json(['data'=>null,'desecption'=>"操作失败",'state'=>2]);exit;
        }
    }

    //技师日志
    function AddPersonLog($ids,$ips,$function_name,$type,$content,$order_num){
        $admin_acc = DB::table('install_person')->where('id',$ids)->value('install_name');
        $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;
    }

    /*
	 * 技师个人中心
	 * @param admin_id
	 * @param
	 * @param
     * @return json
	 */
    public function Install_personal(Request $request){
        //$info = M('install_person')->where(array('id'=>$_POST['admin_id']))->find();
        $input = $request->only('admin_id');
        $info = DB::table('install_person')->where('id',$input['admin_id'])->first();
        if($info){
            $data['id'] = $info['id'] ? $info['id'] : '0';
            $data['install_year'] = $info['install_year'] ? $info['install_year'] : '';
            $data['install_type'] = $info['install_type'] ? $info['install_type'] : '0';
            if($info['install_pic']){
                $data['install_pic'] = $this->picurl($info['install_pic']);
            }else{
                $data['install_pic'] = '';
            }
            //$data['install_pic'] = $info['install_pic'] ? $this->getUrl().$info['install_pic'] : '';
            $data['check_code'] = $info['check_code'] ? $info['check_code'] : '';
            $data['install_name'] = $info['install_name'] ? $info['install_name'] : '';
            $data['install_phone'] = $info['install_phone'] ? $info['install_phone'] : '';
            $data['install_carid'] = $info['install_carid'] ? $info['install_carid'] : '';
            return response()->json(['data'=>$this->intToStr($data),'desecption'=>'成功','state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
        }
    }

    /**@name 技师个人中心修改
	 * @param admin_id
	 * @param userPass
     * @param userPass1
     * @param userPass2
     * @param install_name
     * @param install_phone
     * @param code
     * @param userPic
     * @param install_carid
     * @param install_year
     * @param dediips
     * @return json
     * @author he <2019-03-14>
	 */

    public function install_EditInfo(Request $request){
        $input = $request->all();//'admin_id','userPass','userPass1','install_name','install_phone','code','userPic','install_carid','dediips'
        if(!$request->input('admin_id')){
            return response()->json(['data'=>null,'desecption'=>'参数错误','state'=>5]);exit;
        }
        $checkPass = DB::table('install_person')->where(array('id'=>$input['admin_id']))->first();
        if($request->input('userPass')){
            if($input['userPass'] <> $input['userPass1']){
                // 两次密码不一致
                return response()->json(['data'=>null,'desecption'=>'两次输入密码不一致','state'=>3]);exit;
            }
            if(md5($input['userPass2']) <>$checkPass['install_password']){
                // 原密码错误
                return response()->json(['data'=>null,'desecption'=>'原密码错误','state'=>4]);exit;
            }
            $data['install_password']=md5($input['userPass']);
            $data['install_password1'] = $input['userPass'];
        }

        if($request->input('install_name')){
            $data['install_name'] = $input['install_name'];
        }
        if($request->input('install_phone')){
            $pp = DB::table('phone_coke')->whereRaw("phc_coke='".$input['code']."' and phc_phone='".$input['install_phone']."' and phc_type='1' and phc_expirationtime>'".date('Y-m-d H:i:s')."' and phc_sertype='".$input['ser_type']."'")->first();
            if(!$pp){
                return response()->json(['data'=>null,'desecption'=>'验证码已失效','state'=>7]);exit;
            }
            $data['install_phone'] = $input['install_phone'];
        }
        if($request->input('install_year')){
            $data['install_year'] = $input['install_year'];
        }
        $personInfo=DB::table('install_person')->where('id',$input['admin_id'])->first();
        //头像

        $file = $request->input('userPic');
        if($file){
            /*if (preg_match('/(?<=\/)[^\/]+(?=\;)/',$file,$pregR)) $streamFileType ='.' .$pregR[0];
            $streamFileRand = time().str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
            $dir='./Uploads/install/'.date('Ym').'/';
            $upPath='./Uploads/install/'.date('Ym').'/';
            if(!is_dir($dir)){
                mkdir ($dir);
            }
            $streamFilename = $upPath."/".$streamFileRand .$streamFileType;
            //处理base64文本，用正则把第一个base64,之前的部分砍掉
            preg_match('/(?<=base64,)[\S|\s]+/',$file,$streamForW);
            if (file_put_contents($streamFilename,base64_decode($streamForW[0]))===false){
                return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
            }else{
                $aa=ltrim($personInfo['install_pic'],'/');
                if(file_exists($aa)){
                    unlink($aa);
                }
                $streamFilename=trim($streamFilename,".");
                $data['install_pic']='/.'.$streamFilename;
                $ress=$this->getUrl().'/'.$streamFilename;
            }*/

        	$data['install_pic'] = $file;

          /*   $upPath='./Uploads/install';
            $param['path'] = $upPath;
            $param['file'] = $file;
            $param['type'] = 1;
            $param['deletpath'] = $personInfo['install_pic']?? '';
            $curl_data = $this->curl_basepic(2,$param);
            if($curl_data!='error'){
                $streamFilename = $curl_data;
                $data['install_pic'] = $streamFilename;
                $streamFilename = trim($streamFilename,'.');
                $ress = $this->picurl($streamFilename);
            }else{
                return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
            } */
        }

        if($request->input('install_carid')){
            $data['install_carid'] = $input['install_carid'];
        }
        $check = DB::table('install_person')->where('id',$input['admin_id'])->update($data);
        if($check){
            // 日志
            $this->AddPersonLog($input['admin_id'],$input['dediips'],"安装人员(App)",'修改资料',$personInfo['install_name'],'');
            return response()->json(['data'=>'','desecption'=>'修改成功','state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>'修改失败','state'=>2]);exit;
        }

    }



    /**@name 上传音频
     * @param admin_id 服务商id
     * @param length   音频长度
     * @param order_id 订单id
     * @param myFile   音频文件
     * @return json
     * @author he <2019-03-14>
     */
    public function Uploadaudio(Request $request){
        if($request->isMethod('post')){
            $input = $request->only('admin_id','length','order_id','myFile');
            $inst = DB::table('install_person')->where('id',$input['admin_id'])->first();
            $company_name = DB::table('admin')->where('id',$inst['admin_id'])->select('admin_acc','company_name')->first();
            //return response()->json(['data'=>'1']);exit;
            $data['type']=1;//类型
            $data['gl_id']= $input['order_id'];//关联派工单id
            $data['install_name']=$inst['install_name'];//安装人员姓名
            $data['install_phone']=$inst['install_phone'];//安装人员电话
            $data['install_time']=date("Y-m-d H:i:s");//安装时间
            $data['admin_id']=$inst['admin_id'];//所属服务中心id
            $data['company_name']=$company_name['company_name'];//服务中心名称
            $data['feedback_status']='2';//
            $data['sys_num']= "rwfk".$input['order_id'];//派工单id
            $data['is_type']=2;
            $data['sound_length']=$input['length'];

            $stream = $request->input('myFile');
            if($stream){
                /*if (preg_match('/(?<=\/)[^\/]+(?=\;)/',$stream,$pregR)) $streamFileType ='.' .$pregR[0];
                $streamFileRand = time().str_pad(rand(0,999),3,'0',STR_PAD_LEFT);
                $dir='./Uploads/feedsound/'.date('Ym');
                $upPath='./Uploads/feedsound/'.date('Ym');
                if(!is_dir($dir)){
                    mkdir ($dir);
                }
                $streamFilename = $upPath."/".$streamFileRand .$streamFileType;
                //处理base64文本，用正则把第一个base64,之前的部分砍掉
                preg_match('/(?<=base64,)[\S|\s]+/',$stream,$streamForW);
                if (file_put_contents($streamFilename,base64_decode($streamForW[0]))===false){
                    return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>2]);exit;
                }else{
                    $streamFilename=trim($streamFilename,".");
                    $data['feedback_sound'] = '/.'.$streamFilename;
                }

                $add = DB::table('feedsound')->insert($data);
                if($add){
                    return response()->json(['data'=>null,'desecption'=>'上传成功','state'=>1]);exit;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>2]);exit;
                }*/
                $upPath='./FeekUploads/feedsound/'.date('Ym');
                $param['path'] = $upPath;
                $param['file'] = $stream;//$this->ceshi_pic();
                $param['type'] = 1;
                $curl_data = $this->curl_basepic(1,$param);
                if($curl_data!='error'){
                    $streamFilename = $curl_data;
                    $data['feedback_sound'] = $streamFilename;
                    $add = DB::table('feedsound')->insert($data);
                    if($add){
                        return response()->json(['data'=>null,'desecption'=>'上传成功','state'=>1]);exit;
                    }else{
                        return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>2]);exit;
                    }
                }else{
                    return response()->json(['data'=>null,'desecption'=>'上传失败','state'=>3]);exit;
                }

            }else{
                return response()->json(['data'=>null,'desecption'=>'请上传音频文件','state'=>4]);exit;
            }

        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>3]);exit;
        }

    }

    /**
	 * @name 坐标记录操作
	 * @param line {string} 坐标位置
	 * @param state {int} 按钮点击状态
	 * @param serm {string} 派工单号
     * @return json
     * @ahthor he <2019-03-15>
	 */
    public function linerecord(Request $request){
        $input = $request->only('ser_type','order_id','admin_id','serm','state','line','dress','dediips','bar_code','car_plate','battery_old','battery_new','order_age');

        $file1 =$request->input('myFile1');
        $file2 =$request->input('myFile2');
        $file3 =$request->input('myFile3');
        $file4 =$request->input('myFile4');
        $file5 =$request->input('myFile5');
        $lise = DB::table('order_list')->where('id',$input['order_id'])->first();

        if($lise['install_id'] <> $input['admin_id']){
            return response()->json(['data'=>null,'desecption'=>'不是自己的订单，无法操作','state'=>13]);exit;//不是自己的订单
        }
        $order_id=DB::table('order_list')->where('serial_number',$input['serm'])->value('id');
        $input['order_id'] = $order_id;
        $install_name = DB::table('install_person')->where('id',$input['admin_id'])->first();
        //$info = $dbname->where(array('line_serm'=>$serm))->find();
        $info = DB::table('install_line')->where(['line_serm'=>$input['serm']])->first();
        //DB::table()->where('serial_number')->value('line_status');

        if($info['line_status'] == 1){
            return response()->json(['data'=>null,'desecption'=>"该订单已终止，无法操作",'state'=>10]);exit;
        }
        $state = $input['state'];
        if($state == 5){
            $inputs=$input;
            $chk = $this->install_upload($inputs,$file1,$file2,$file3,$file4,$file5);
            if($chk <> 1){
                if($chk == 6){
                    $message='不是自己的订单，无法操作';
                }elseif($chk==4){
                    $message='请求参数错误';
                }elseif($chk==5){
                    $message='该订单已锁定';
                }elseif($chk==7){
                    $message='该订单状态错误';
                }elseif($chk==8){
                    $message='该订单已反馈';
                }elseif($chk==11){
                    $message='图片格式无效';
                }elseif($chk==3){
                    $message='图片上传失败';
                }elseif($chk==2){
                    $message='反馈失败';
                }
                return response()->json(['data'=>null,'desecption'=>$message,'state'=>$chk]);exit;
            }
        }else{
            $chk = 1;
        }
        $line = $input['line'];

        $times = date('Y-m-d H:i:s',time());
        $data['line_lasttime'] = $times;
        $data['line_state'] = $state;
        $chkOrder = DB::table('order_list')->where(['serial_number'=>$input['serm']])->first();
        if($chkOrder && !$info){
            $lines['line_serm'] = $input['serm'];
            $lines['line_sysnum'] = $chkOrder['sys_num'];
            $lines['line_number'] = $chkOrder['order_num'];
            $lines['line_state'] = $state;
            $lines['line_lasttime'] = date('Y-m-d H:i:s');
            $dbid = DB::table('install_line')->insertGetId($lines);
            $info = DB::table('install_line')->where('id',$dbid)->first();
        }
        if($info){
            $data['line_dynamic'] = $line;
            switch($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;
            }

            DB::beginTransaction();
            $check = DB::table('install_line')->where('line_serm',$input['serm'])->update($data);

        }else{
            //echo '{"data":null,"desecption":"fail","state":7}';exit;
        }

        if($check && $chk == 1){
            //操作时间
            $this->operating_time($input['serm'],$title,date("Y-m-d H-i-s"),$install_name['install_name'].'('.$install_name['check_code'].')');

            //if($state == 5){
            //	$order = M('orders');
            //	$order->startTrans(); //开启事物回滚
            //	$order_list->startTrans(); //开启事物回滚
            //	$a1 = $order->where(array('sys_num'=>$info['line_sysnum']))->save(array('order_status'=>'40'));
            //	$a2 = $order_list->where(array('serial_number'=>$info['line_serm']))->save(array('stauas'=>'40'));
            //	if($a1 && $a2){
            //		$dbname->commit();
            //		$order->commit();
            //		$order_list->commit();

            //	}else{
            //		$dbname->rollback();
            //		$order->rollback();
            //		$order_list->rollback();
            //		echo '{"data":null,"desecption":"fail","state":8}';exit;
            //	}
            //}else{
            //$dbname->commit();
            DB::commit();
            //}
            if($input['ser_type'] == 1){
                // 日志A
                $this->addAppLog($input['admin_id'],$input['dediips'],'派工单('.$input['phoneType'].')',$title,"订单(".$input['serm'].")",$info['line_sysnum']);
            }else{
                // 日志
                $this->AddPersonLog($input['admin_id'],$input['dediips'],'派工单('.$input['phoneType'].')',$title,"订单(".$input['serm'].")",$info['line_sysnum']);
            }
            return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);
        }else{
            //$dbname->rollback();
            DB::rollback();
            return response()->json(['data'=>null,'desecption'=>'失败','state'=>9]);

        }
    }

    //任务反馈
    public function install_upload($inputs,$file1,$file2,$file3,$file4,$file5){


            if(empty($inputs['admin_id']) && empty($inputs['order_id'])){
                return 4;exit;
            }

            //$lister=$order_list->where("`id`='".$order_id."'")->find();
            $lister = DB::table('order_list')->where('id',$inputs['order_id'])->first();
            if($lister['locklist_type']=='2'){
                return 5;exit;
            }

            if($lister['install_id'] <> $inputs['admin_id']){
                return 6;exit; //不是自己的订单
            }

            if($lister['stauas']<>30){
                return 7;exit;
            }
            $sys_num="rwfk".$inputs['order_id'];//派工单id
            //$res=$feedback->where("sys_num=".$sys_num)->find();
            $res = DB::table('feedback')->where('sys_num',$sys_num)->first();


            if($file1){
                // 追溯
				$psos['qualification_pr']=$file1;
				// 反馈
				$arr_c['feedback_pic']=$file1;
				$image_file2=$file1;
            }
            if($file2){
               // 追溯
				//$psos['qualification_nooutage']=$file2;
				// 反馈
				$arr_d['feedback_pic']=$file2;
				$image_file1=$file2;
            }
            if($file3){
                // 追溯
					$psos['installation_pictures']=$file3;
				// 反馈
				$arr_b['feedback_pic']=$file3;
            }
            if($file4){
                // 追溯
				//$psos['qualification_warranty']=$file4;
				// 反馈
				$arr_e['feedback_pic']=$file4;
            }
            if($file5){
                // 追溯
				$psos['qualification']=$file5;
				// 反馈
				$arr_a['feedback_pic']=$file5;
            }
           $personsss = DB::table('install_person')->where('id',$inputs['admin_id'])->value('admin_id');
            $company_name = DB::table('admin')->where('id',$personsss)->select('admin_acc','company_name','reward')->first();
            $inst = DB::table('install_person')->where('id',$inputs['admin_id'])->first();

            //车牌号
            $arr_a['type']=1;//类型
            $arr_a['gl_id']=$inputs['order_id'];//关联派工单id
            $arr_a['install_name']=$inst['install_name'];//安装人员姓名
            $arr_a['install_phone']=$inst['install_phone'];//安装人员电话
            $arr_a['install_time']=date("Y-m-d H:i:s");//安装时间
            $arr_a['admin_id']=$personsss;//所属服务中心id
            $arr_a['company_name']=$company_name['company_name'];//服务中心名称
            $arr_a['feedback_status']='2';//
            $arr_a['sys_num']="rwfk".$inputs['order_id'];//派工单id
            $arr_a['is_type']=2;
            $arr_a['install_remark']='1';
            DB::table('feedback')->insert($arr_a);
            //不断电安装
            $arr_b['type']=2;//类型
            $arr_b['gl_id']=$inputs['order_id'];//关联派工单id
            $arr_b['install_name']=$inst['install_name'];//安装人员姓名
            $arr_b['install_phone']=$inst['install_phone'];//安装人员电话
            $arr_b['install_time']=date("Y-m-d H:i:s");//安装时间
            $arr_b['admin_id']=$personsss;//所属服务中心id
            $arr_b['company_name']=$company_name['company_name'];//服务中心名称
            $arr_b['feedback_status']='2';//
            $arr_b['sys_num']="rwfk".$inputs['order_id'];//派工单id
            $arr_b['is_type']=2;
            $arr_b['install_remark']='1';
            DB::table('feedback')->insert($arr_b);
            //生产日期
            $arr_c['type']=3;//类型
            $arr_c['gl_id']=$inputs['order_id'];//关联派工单id
            $arr_c['install_name']=$inst['install_name'];//安装人员姓名
            $arr_c['install_phone']=$inst['install_phone'];//安装人员电话
            $arr_c['install_time']=date("Y-m-d H:i:s");//安装时间
            $arr_c['admin_id']=$personsss;//所属服务中心id
            $arr_c['company_name']=$company_name['company_name'];//服务中心名称
            $arr_c['feedback_status']='2';//
            $arr_c['sys_num']="rwfk".$inputs['order_id'];//派工单id
            $arr_c['is_type']=2;
            $arr_c['install_remark']='1';
            DB::table('feedback')->insert($arr_c);

            //安装完成
            $arr_d['type']=7;//类型
            $arr_d['gl_id']=$inputs['order_id'];//关联派工单id
            $arr_d['install_name']=$inst['install_name'];//安装人员姓名
            $arr_d['install_phone']=$inst['install_phone'];//安装人员电话
            $arr_d['install_time']=date("Y-m-d H:i:s");//安装时间
            $arr_d['admin_id']=$personsss;//所属服务中心id
            $arr_d['company_name']=$company_name['company_name'];//服务中心名称
            $arr_d['feedback_status']='2';//
            $arr_d['sys_num']="rwfk".$inputs['order_id'];//派工单id
            $arr_d['is_type']=2;
            $arr_d['install_remark']='1';
            DB::table('feedback')->insert($arr_d);

            //质保卡
            $arr_e['type']=5;//类型
            $arr_e['gl_id']=$inputs['order_id'];//关联派工单id
            $arr_e['install_name']=$inst['install_name'];//安装人员姓名
            $arr_e['install_phone']=$inst['install_phone'];//安装人员电话
            $arr_e['install_time']=date("Y-m-d H:i:s");//安装时间
            $arr_e['admin_id']=$personsss;//所属服务中心id
            $arr_e['company_name']=$company_name['company_name'];//服务中心名称
            $arr_e['feedback_status']='2';//
            $arr_e['sys_num']="rwfk".$inputs['order_id'];//派工单id
            $arr_e['is_type']=2;
            $arr_e['install_remark']='1';
            DB::table('feedback')->insert($arr_e);

           /* //签收确认单
            $arr_f['type']=6;//类型
            $arr_f['gl_id']=$input['order_id'];//关联派工单id
            $arr_f['install_name']=$inst['install_name'];//安装人员姓名
            $arr_f['install_phone']=$inst['install_phone'];//安装人员电话
            $arr_f['install_time']=date("Y-m-d H:i:s");//安装时间
            $arr_f['admin_id']=$personsss;//所属服务中心id
            $arr_f['company_name']=$company_name['company_name'];//服务中心名称
            $arr_f['feedback_status']='2';//
            $arr_f['sys_num']="rwfk".$input['order_id'];//派工单id
            $arr_f['is_type']=2;
            DB::table('feedback')->insert($arr_f);*/

            $time=date("Y-m-d H:i:s");
            $post['stauas']=34;//待完成
            $post['feeds_time']=$time;//商家提交安装单时间
            //$reir=$order_list->where("`id`='".$order_id."'")->save($post);
            $reir = DB::table('order_list')->where('id',$inputs['order_id'])->update($post);
            //dump($inputs['admin_id']);
            //dd($reir);
            if(!$inputs['car_plate']){
            	$inputs['car_plate'] = '暂无';
            }

            $info=DB::table('carplate_info')->where(['can_plate'=>$inputs['car_plate'], 'or_number'=>$lister['serial_number']])->first();
            //$plate['can_plate']=$_POST['can_plate'];
            if($info){
            	$this->carPlate($inputs['car_plate'],$lister['serial_number'],$info['can_id'],$inputs['bar_code']);
            }else{
            	$this->carPlate($inputs['car_plate'],$lister['serial_number'],"null",$inputs['bar_code']);
            	//$carplate_info->add($plate);
            }

            //$ids,$ips,$function_name,$type,$content,$order_num
            $this->AddPersonLog($inputs['admin_id'],$inputs['dediips'],"派工单(App-android)","任务反馈，",$lister['order_num']."订单(".$lister['serial_number']."),已安装",$lister['order_num']);
            $this->operating_time($lister['serial_number'],'任务反馈时间',$time,$company_name['admin_acc']);

            if($reir){
                if($inputs['battery_old']){
                    $add_old=$this->add_batterydata($inputs['battery_old'],'1',$inputs['order_id']);
                }
                if($inputs['battery_new']){
                    $add_new=$this->add_batterydata($inputs['battery_new'],'2',$inputs['order_id']);
                }
                $psos['goods_time']=date("Y-m-d");
                //$management->where("trace_code='".$lister['serial_number']."'")->save($psos);
                DB::table('management')->where('trace_code',$lister['serial_number'])->update($psos);

                $OrderCount = DB::table('order_list')->whereRaw("sys_num='".$lister['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',$lister['sys_num'])->update($orderArr);
                }else{
                    $a1 = 1;
                }

                if($lister['orli_type']==1) {
                    $dou = DB::table('settlement_list')->where('list_id', $lister['serial_number'])->value('id');

                    ////开始计算奖惩金额以及评分
                    //$payout_time=$order_time->where("serial_number='".$lister['serial_number']."' and is_type='接单时间'")->order('id DESC')->getField('create_time');//获取奖罚起始时间
                    //$yy_time=$order_time->where("serial_number='".$lister['serial_number']."' and is_type='安装预约时间'")->order('id DESC')->getField('create_time');//获取奖罚起始时间
                    ////派单时间
                    //$pd_time=$order_time->where("serial_number='".$lister['serial_number']."' and is_type='派单时间'")->order('id DESC')->getField('create_time');//获取奖罚起始时间

                    //$times=$order_time->where("serial_number='".$lister['serial_number']."' and (is_type='接单时间' or is_type='安装预约时间' or is_type='派单时间')")->order("id DESC")->group('is_type')->getField("is_type,create_time");
                    // $times = DB::table('order_time')->whereRaw("serial_number='".$lister['serial_number']."' and (is_type='接单时间' or is_type='安装预约时间' or is_type='派单时间')")->orderBy('id','DESC')->groupBy('is_type')->select('is_type','create_time')->get()->toArray();
                    $sql = "select `is_type`, `create_time` from `gone_order_time` where serial_number='" . $lister['serial_number'] . "' and (is_type='接单时间' or is_type='安装预约时间' or is_type='派单时间') group by `is_type` order by `id` desc";
                    $times = DB::select($sql);
                    foreach ($times as $k => $v) {
                        $timess[$v['is_type']] = $v['create_time'];
                    }
                    $payout_time = $timess['接单时间'] ?? "";
                    $yy_time = $timess['安装预约时间'] ?? "";
                    $pd_time = $timess['派单时间'] ?? "";
                    $zero4 = strtotime($pd_time);
                    $zero2 = strtotime($payout_time);  //过年时间，不能写2014-1-21 24:00:00  这样不对
                    if ($yy_time) {
                        $zero3 = strtotime($yy_time);  //过年时间，不能写2014-1-21 24:00:00  这样不对
                        $yyaz = ($zero3 - $zero2) / 60; //60s*60min*24h
                        if ($yyaz > 17) {
                            $flag = 1;
                        } else {
                            $flag = 2;
                        }
                    } else {
                        $flag = 1;
                    }
                    $rulesout = self::rulesout();
                    if (!in_array($lister['p_id'], $rulesout)) {
                        //$money_type=$setmoney_type->where("sety_id=7 or sety_id=18")->getField("sety_id,sety_price");//->select()
                        $money_types = DB::table('setmoney_type')->whereRaw("sety_id=7 or sety_id=18")->get()->toArray();
                        foreach ($money_types as $k => $v) {
                            $money_type[$v['sety_id']] = $v['sety_price'];
                        }
                        if ($flag == '1' && $company_name['reward'] == '1') {
                            $money['sem_slid'] = $dou;
                            $money['sem_synum'] = $lister['sys_num'];
                            $money['sem_creacter'] = $company_name['admin_acc'];
                            $money['sem_price'] = $money_type[18];
                            $money['sem_type'] = 18;
                            //$settlement_money->add($money);
                            DB::table('settlement_money')->insert($money);
                            //$all_price['all_price']=$settlement_money->where("sem_slid='".$dou."'")->SUM('sem_price');
                            $all_price['all_price'] = DB::table('settlement_money')->where('sem_slid', $dou)->sum('sem_price');
                            //$settlement_list->where("id='".$dou."'")->save($all_price);
                            DB::table('settlement_list')->where('id', $dou)->update($all_price);
                        }
                        //$res=$settlement_money->where("sem_slid='".$dou."' and sem_type=15")->getField("sem_type");

                        if (!$res) {
                            $zero1 = time();//strtotime (date("Y-m-d H:i:s")); //当前时间  ,注意H 是24小时 h是12小时
                            $guonian = ($zero1 - $zero4) / 60; //60s*60min*24h
                            if ($company_name['reward'] == '1') {
                                $Install_money = str_replace('，', ',', $money_type[7]);
                                $Install_money = explode(',', $Install_money);

                                $money['sem_slid'] = $dou;
                                $money['sem_synum'] = $lister['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', $dou)->sum('sem_price');
                                    DB::table('settlement_list')->where('id', $dou)->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', $dou)->sum('sem_price');
                                    DB::table('settlement_list')->where('id', $dou)->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', $dou)->sum('sem_price');
                                    DB::table('settlement_list')->where('id', $dou)->update($all_price);
                                }
                            }
                        }
                    }
                    //2016-3-28
                }
                $lemeArr['list_service_type']='34';//待完成
                $lemeArr['setfeeds_time']=$time;//待完成
                $a2 = DB::table('settlement_list')->where('list_id',$lister['serial_number'])->update($lemeArr);
                if($inputs['order_age']){
                    $admin_id=$inputs['admin_id'];
                    $info = DB::table('install_person')->where(array('id'=>$inputs['admin_id']))->first();
                    $this->Message($inputs['admin_id'],$lister['sys_num'],$inputs['order_age'],"派工单(App_android)",$inputs['admin_id']);
                }
                //$order_visit=M("order_visit");
                $visit['ov_show']='3';
                $cisis=DB::table('order_visit')->where('ov_serial',$lister['serial_number'])->update($visit);
                if($a1 && $a2 && $reir){
                    DB::commit();
                    return 1;
                    //$ordestatu=M()->execute("update gone_order_status set st_three=st_three+1,st_two=st_two-1 where st_serid='".$lister['ser_id']."'");
                }else{
                    DB::rollback();
                    return 2;exit;
                }
            }
        //}else{
        //    return 3;exit;
        //}
    }

    //添加监测数据
    public function add_batterydata ($data,$type,$id){
        //$batterydata=M("batterydata");
        if($type=='1' || $type=='2'){
            $list = DB::table('order_list')->where('id',$id)->select('serial_number','ser_id','order_num')->first();

            $poss['bty_serm']=$list['serial_number'];
            $poss['bty_ordernum']=$list['order_num'];
            $poss['bty_serid']=$list['ser_id'];
            if($type=='2'){
                $poss['bty_num']='1';
            }
        }else{
            $list = DB::table('order_after')->where('id',$id)->select('serial_number','deal_serid','order_num','after_num')->first();
            $poss['bty_serm']=$list['serial_number'];
            $poss['bty_ordernum']=$list['order_num'];
            $poss['bty_shnum']=$list['after_num'];
            $poss['bty_serid']=$list['deal_serid'];

            $num = DB::table('batterydata')->where(['bty_serm'=>$list['serial_number'],'bty_ordernum'=>$list['order_num']])->select('bty_num','bty_snum')->orderBy('bty_id','DESC')->first();
            if($type=='3'){
                $poss['bty_num']=$num['bty_num'];
                $poss['bty_snum']=$num['bty_snum']+1;
            }if($type=='4'){
                $poss['bty_num']=$num['bty_num']+1;
                $poss['bty_snum']='0';
            }
        }
        $poss['bty_type']=$type;
        $data=json_decode($data,true);
        $poss['bty_mcca']=$data['mcca'];
        $poss['bty_mah']=$data['mah'];
        $poss['bty_Standard']=$data['type'];
        $poss['bty_time']=date("Y-m-d H:i:s");
        $poss['bty_data']=json_encode($data['data']);
        //$res=$batterydata->add($poss);
        $res =DB::table('batterydata')->insert($poss);
        return $res;
    }



    //匹配车型 car_plate {string} 车牌号
    public function addcarinfo(Request $request){

        if($request->input('car_plate') =='' || $request->input('sem')){
            //echo '{"data":null,"desecption":"fail","state":3}';exit;
            return response()->json(['data'=>null,'desecption'=>'参数错误','state'=>1]);
        }
        $input = $request->only('car_plate','sem');
        $add=$this->carPlate($input['car_plate'],$input['sem']);
        if($add=='1'){
            return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);
        }else{
            return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);
        }
    }
    //车牌号识别
    function carPlate($car_plate,$serial_number,$can_id,$bar_code){
        $url='https://1.sudianwang.com/index.php/Carrescue/search_placeext?car_plate='.$car_plate;//生产环境
        $output = file_get_contents($url); ;//运行curl

        $obj=json_decode($output,true);
        //$obj['code'] = 200;
        if($obj['data']['state']=='1'){
            $data = $obj['data']['data']['vehicleList'];
            $order_infor['can_plate']=$car_plate;
            $order_infor['vehicleFgwCode']=$data[0]['vehicleFgwCode'];
            $order_infor['vehicleFgwName']=$data[0]['vehicleFgwName'];
            $order_infor['parentVehName']=$data[0]['parentVehName'];
            $order_infor['brandCode']=$data[0]['brandCode'];
            $order_infor['brandName']=$data[0]['brandName'];
            $order_infor['engineDesc']=$data[0]['engineDesc'];
            $order_infor['familyName']=$data[0]['familyName'];
            $order_infor['gearboxType']=$data[0]['gearboxType'];
            $order_infor['remark']=$data[0]['remark'];
            $order_infor['newCarPrice']=$data[0]['newCarPrice'];
            $order_infor['purchasePriceTax']=$data[0]['purchasePriceTax'];
            $order_infor['importFlag']=$data[0]['importFlag'];
            $order_infor['purchasePrice']=$data[0]['purchasePrice'];
            $order_infor['seat']=$data[0]['seat'];
            $order_infor['standardName']=$data[0]['standardName'];
            $order_infor['or_number']=$serial_number;
            $order_infor['vehicleID']=$data[0]['vehicleID'];
            $order_infor['type']="Android";
            $order_infor['car_id']=DB::table('zt_bml')->where(array('zt_vehicle'=>$data[0]['vehicleID']))->value('zt_sid');
            $order_infor['time']= date('Y-m-d H:i:s');

        }else{
            $order_infor['can_plate']=$car_plate;
            $order_infor['or_number']=$serial_number;
            $order_infor['time']= date('Y-m-d H:i:s');
        }
        $order_infor['bar_code']= $bar_code;
        $order_infor['type']='android';
        if($can_id=='null'){
            $add = DB::table('carplate_info')->insert($order_infor);
        }else{
            unset($order_infor['or_number']);
            $add = DB::table('carplate_info')->where('can_id',$can_id)->update($order_infor);
        }
        if($add){
            return 1;
            //echo '{"data":null,"desecption":"succes","state":1}';exit;
        }else{
            return 2;
            //echo '{"data":null,"desecption":"fail","state":2}';exit;
        }
    }

    /**
     * @name 获取备注
     * @param id
     * @state
     * @limit ser_type
     * @return json
     * */
    public function Json_Gain_Message(Request $request){
        //dd('1');
        if(empty($request->input('serial_number')) || empty($request->input('limit'))){
            return response()->json(['data'=>null,'desecption'=>'访问参数错误','state'=>4]);
        }
        $input = $request->only('serial_number','admin_id','limit');
       	$sys_num = DB::table('order_list')->where('serial_number',$input['serial_number'])->value('sys_num');
        if($request->input('limit')){
            $limit=($input['limit']-1)*10;
            $limits=" LIMIT ".$limit.",10";
        }
       // DB::connection()->enableQueryLog();
        if($request->input('ser_type')=='1'){
           $list = DB::table('note')->whereRaw("`orders_id`='".$sys_num."' AND `public_state`=2 AND (note_group!=2 or note_adid='".$input['admin_id']."') ORDER BY id DESC".$limits)->get();
        }else {
           // $admin_id = DB::table('install_person')->where('id', $input['admin_id'])->value('admin_id');

            $list = DB::table('note')->whereRaw("`orders_id`='" . $sys_num . "' AND `public_state`=2 AND (note_group!=2 or note_installid='" . $input['admin_id'] . "') ORDER BY id DESC" . $limits)->get();
        }
       // print_r(DB::getQueryLog());

        $list =$list->toArray();
        if($list){
            foreach($list as $k=>$v){
                if($v['note_group']=='0'){
                    $admin_group=DB::table('admin')->where('admin_name',$v['note_name'])->value('admin_group');
                    if(empty($admin_group)){
                        $admin_group=DB::table('admin')->where('admin_acc',$v['note_name'])->value('admin_group');
                    }
                }else{
                    $admin_group=$v['note_group'];
                }
                if($v['note_content']=="售后处理完毕，已申请售后完成"){
                    $json[$k]['author']='系统备注';
                    $json[$k]['deals']="1";
                    $json[$k]['type']=2;
                }else{
                    if($admin_group==2){
                        if($request->input('ser_type')=='1'){
                            if($v['note_installid']=='0'){
                                $json[$k]['author']='我';
                                $json[$k]['type']=1;
                            }else{
                                $json[$k]['author']='技师';
                                $json[$k]['type']=2;
                            }
                        }else{
                            if($v['note_installid']==$input['admin_id']){
                                $json[$k]['author']='我';
                                $json[$k]['type']=1;
                            }else{
                                $json[$k]['author']='代理';
                                $json[$k]['type']=2;
                            }
                        }
                    }else{
                        $json[$k]['author']='速电客服';
                        $json[$k]['type']=2;
                    }
                    $json[$k]['deals']="2";
                }

                $time=str_replace("-","/",$v['note_time']);//时间
                $json[$k]['create_time']=substr($time,0,-3);//时间
                $json[$k]['content']=$v['note_content'];//备注内容

                $install_id = DB::table('order_list')->where('sys_num',$sys_num)->value('install_id');

                if($install_id){
                    $pic = DB::table('install_person')->where('id',$install_id)->value('install_pic');
                }
                if(isset($pic)){
                    //explode('/.',$pic)[1];
                    $json[$k]['pic'] =$this->picurl($pic);
                }else{
                    $json[$k]['pic'] ="";
                }
            }
            if(isset($json)){
                return response()->json(['data'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);
            }

        }else{
            return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);
        }

    }

    /**
     * @name 接单 拒单
     * @param id
     * @state admin_id
     * @param content
     * @param sin_bcentent
     * @param dediips
     * @param
     * @return json
     * */
    public function Json_order_oper(Request $request){
        $input = $request->only('id','admin_id','type','install_id','send_num','dediips','phoneType');
        if(!$request->input('admin_id')){
            return response()->json(['data'=>null,'desecption'=>'参数错误','state'=>17]);exit;
        }
        $orderListArr = DB::table('order_list')->where('id',$request->input('id'))->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','goods_price','create_time')->first();
        //dd($orderListArr);
        $is_lidao = DB::table('admin')->where('id',$orderListArr['ser_id'])->value('is_lidao');
        //dd($is_lidao);
        // 不等于未接单
        if($orderListArr['locklist_type']==2){
            return response()->json(['data'=>null,'desecption'=>'该订单已锁定，不可操作','state'=>4]);exit;
        }
        if($request->input('type') == 2){
            if($orderListArr['stauas']!=10 && $orderListArr['stauas']!=20 && $orderListArr['stauas']!=30){
                return response()->json(['data'=>null,'desecption'=>'该状态不可拒单','state'=>3]);exit;
                exit;
            }
        }else{
            if($orderListArr['stauas']!=10 && $orderListArr['stauas']!=20){
                //echo '{"data":null,"desecption":"fail","state":5}';
                //exit;
                return response()->json(['data'=>null,'desecption'=>'该状态不可接单','state'=>5]);exit;
            }
        }

        $admins = DB::table('admin')->where('id',$input['admin_id'])->first();
        $admin_acc=$admins['admin_acc'];
        //dd($admins);
        // 拒单
        if($request->input('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;
                }
            }


            //$this->addptrz("android-app","服务商拒单");
            // 添加备注
            if($orderListArr['stauas']==10 || $orderListArr['stauas']==20){
                $centent = '接单前拒单；';
            }else{
                $centent = '接单后拒单；';
            }
            $centent .= $request->input('content')."；".$request->input('sin_bcentent');
            $this->Message($input['admin_id'],$orderListArr['sys_num'],"拒单，".$centent."(".$orderListArr['serial_number'].")","派工单(App-android)",'0');

            $is_html='拒单，';

            DB::beginTransaction();
            $input['sin_bid']=rtrim($request->input('sin_bid'),',');
            $labarr = explode(',',$input['sin_bid']);
            //dd($labarr);
            foreach($labarr as $key=>$val){
                //$labstate = $setmoney_type->where(array('sety_id'=>$val))->find();
                $labstate = DB::table('setmoney_type')->where('sety_id',$val)->first();
                if(strstr((string)$labstate['sety_price'],'-')){
                    $price = substr($labstate['sety_price'],1);
                }else{
                    $price = $labstate['sety_price'];
                }

                $adddata['afs_statues'] = $labstate['sety_type']??'1';
                $adddata['afs_order'] = $orderListArr['order_num'];
                $adddata['afs_serial'] = $input['send_num'];
                $adddata['afs_sales'] = 1;
                $adddata['afs_paid'] = $labstate['lt_parent_id']??'0';
                if($val){
                    $adddata['afs_type'] = $val;
                }else{
                    $adddata['afs_type'] = 0;
                }

                $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'] = "";
                DB::table('aftersale')->insert($adddata);

            }
            $resultOrderList = DB::table('order_list')->where('id',$input['id'])->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){
               // $ordestatu=M()->execute("update gone_order_status set st_one=st_one-1 where st_serid='".$orderListArr['ser_id']."'");
                //$order_list->commit();
                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',$input['admin_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->addAppLog($input['admin_id'],$input['dediips'],'派工单('.$input['phoneType'].')',$is_html,"订单(".$orderListArr['serial_number'].")",$orderListArr['sys_num']);

                return response()->json(['data'=>null,'desecption'=>'拒单成功','state'=>1]);exit;

            }else{
                DB::rollback();
                return response()->json(['data'=>null,'desecption'=>'拒单失败','state'=>2]);exit;
            }
            exit;
            // 接单
        }elseif($request->input('type')==1){
            $returncount = DB::table('order_list')->where('sys_num',$orderListArr['sys_num'])->whereRaw('(`stauas`=10 or `stauas`=20)')->count();

            //$this->addptrz("android-app","服务商接单");

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

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

            $MsgArr = DB::table('order_msg')->where('id',$orderListArr['order_goods_id'])->select('goods_id','goods_name','goods_brand')->first();
            //dd($MsgArr);
            $instArr = DB::table('install_person')->where('id',$input['install_id'])->select('install_name','install_phone','check_code','bind')->first();
            //dd($instArr);
            //if(!$supply_price){
            $pt_id=array('111','112','136');
            $pttype = PlatformService::getPtIdByPtType();
            if(in_array($orderListArr['p_id'],$pt_id)){
                $supply_price=$orderListArr['goods_price'];
            }else{
                if(in_array($orderListArr['p_id'], $pttype)){
                    $supply_price = GhXPrice::whereRaw("`goods_id`='" . $MsgArr['goods_id'] . "' and `ser_id`='" . $orderListArr['ser_id'] . "'")->orderBy('id', 'DESC')->value('supply_price');
                }else {
                    $supply_price = GhPrice::whereRaw("`goods_id`='" . $MsgArr['goods_id'] . "' and `ser_id`='" . $orderListArr['ser_id'] . "'")->orderBy('id', 'DESC')->value('supply_price');
                }
                if(in_array($orderListArr['p_id'],$pttype)){
                    $supply_price = GhXPrice::whereRaw("`goods_id`='" . $MsgArr['goods_id'] . "' and `ser_id`=0")->orderBy('id', 'DESC')->value('supply_price');
                }else{
                    $supply_price = GhPrice::whereRaw("`goods_id`='" . $MsgArr['goods_id'] . "' and `ser_id`=0")->orderBy('id', 'DESC')->value('supply_price');
                }
                if(!$supply_price){
                    $supply_price='0.00';
                }
            }
            //dump($supply_price);

            //}

            $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']=$input['install_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'];

            // 锁定状态
            $submit_stauas = DB::table('submit_please')->where(['submit_sys_num'=>$orderListArr['sys_num'],'msg_id'=>$orderListArr['order_goods_id']])->value('submit_stauas');
            //dd($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']=$input['install_id'];//安装人id
        $post['intall_person']=$instArr['install_name'];//安装人姓名
        $post['intall_phone']=$instArr['install_phone'];//安装人电话
        //dump($post);
        // $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('id',$input['id'])->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';
            $visit['company_id'] = $stauasa['company_id'];
            //dd($visit);
            $cisis = DB::table('order_visit')->insert($visit);

        }
        if($restSettlementList) {
            $money['sem_slid'] = $restSettlementList;
            $money['sem_synum'] = $orderListArr['sys_num'];
            $money['sem_price'] = $supply_price;
            $money['sem_creacter'] = $admin_acc . "(APP)";
            $money['sem_type'] = 1;
            $rulesout = self::rulesout();
            if(!in_array($orderListArr['p_id'],$rulesout)) {
                $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);
                //print_r(DB::getQueryLog());
                $tim = $orderListArr['create_time'];
                $sup_price = DB::table('support')->whereRaw("sup_serid like '%," . $input['admin_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 . "(APP)";
                        $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 . "(APP)";
            $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."(APP)";
            $scoreq['orsc_type'] = 2;
            DB::table('order_score')->insert($scoreq);
            if(!in_array($orderListArr['p_id'],$rulesout)) {
                #计算奖惩金额
                $moneyjc['sem_slid'] = $restSettlementList;
                $moneyjc['sem_creacter'] = $admin_acc . "(APP)";
                $moneyjc['sem_synum'] = $orderListArr['sys_num'];

                $moneyqj['sem_slid'] = $restSettlementList;
                $moneyqj['sem_creacter'] = $admin_acc . "(APP)";
                $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);
                        //}
                    }
                }
                //putong
                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 {
                    //night
                    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;
                    }
                    //60min
                    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;
                    }
                    //40min
                    if ($orderListArr['orli_type'] == 15) {
                        $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;
                    }
                    //90min
                    if ($orderListArr['orli_type'] == 25) {
                        $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;
                    }
                    //120min
                    if ($orderListArr['orli_type'] == 30) {
                        $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(!in_array($orderListArr['p_id'],$rulesout)) {
                    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_time($orderListArr['serial_number'], '接单时间', date("Y-m-d H:i:s"), $admin_acc);
            //$this->add_thistory($orderListArr['serial_number'], 'tih_acceptime', date("Y-m-d H:i:s"), '', 2);//添加历史时间
        }
        $shr_phone=DB::table('user')->where('id',$orderListArr['customer_id'])->value('shr_phone');//手机号

        if($restOrderList && $restSettlementList && $lins && $cisis) {
            if($orderListArr['p_id']=='151' && $orderListArr['order_num']!='ND21101612786857B'){
                $pingan['sign']='8d7f2da4dbea44c25f24ba578fc7d817';
                $pingan['api_name']='sysPState';
                $pingan['order_num']=$orderListArr['order_num'];
                $pingan['state']='03';
                $pian=$this->https_post('https://web.sudianwang.com/api/v1/WebInter/orderApi', $pingan);
                //dump($pian);
                $pian=json_decode($pian,true);
                if(isset($pian['code'])){
                    if($pian['code']=='0'){
                    }else{
                        DB::rollback();
                        return response()->json(['data' => null, 'desecption' => '接单失败', 'state' => 2]);
                        exit;
                    }
                }else{
                    DB::rollback();
                    return response()->json(['data' => null, 'desecption' => '接单失败', 'state' => 2]);
                    exit;
                }
            }
            if($orderListArr['p_id'] == '463'){
                $boshi['op_type'] = 11;
                $boshi['orderWebCod'] = $orderListArr['order_num'];
                $boshi['check_code'] = $instArr['check_code'];
                $order_lists['serial_number'] = $orderListArr['serial_number'];
                $order_lists['create_time'] = $orderListArr['create_time'];
                $order_lists['ser_id'] = $orderListArr['ser_id'];
                $boshi['order_list'][] = $order_lists;
                $boshi['method'] = 'sysBsWorkOrderStatue';
                $sys_jd = $this->request_post('https://web.sudianwang.com/api/v1/BsApi/orderApi?method=sysBsWorkOrderStatue', json_encode($boshi), array('Content-Type: application/json'));
                $sys_jd = json_decode($sys_jd,true);
                if($sys_jd['response']['code'] != 1){
                    DB::rollback();
                    // 失败
                    return response()->json(['data' => null, 'desecption' => '接单失败', 'state' => 2]);
                    exit;
                }
            }
            //$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);
            }
            if ($orderListArr['p_id'] != "70" && $orderListArr['p_id'] != "86" && $orderListArr['p_id'] != "111" && $orderListArr['p_id'] != "112") {
                //include_once('SendsmsAction.class.php');
                //$activitysms=M("activitysms");
                //$content = DB::table('activitysms')->where('act_type','2')->value("act_centent");
                //$content="您购买的汽车电瓶已派单,稍后安装技师与您预约安装时间,该电瓶为以旧换新价,旧电瓶技师收回。电话:4000-77-3321";//内容
                //$interface= new SendsmsAction();
                //$sms = $this->sms_note($shr_phone, $content);
            }
            $this->probability('1', $input['admin_id'], $stauas);//计算接单率
            // 日志
            $this->addAppLog($input['admin_id'], $input['dediips'], '派工单('.$input['phoneType'].')', $is_html, "订单(" . $orderListArr['serial_number'] . ")", $orderListArr['sys_num']);
            if ($instArr['bind'] == '2') {
                if ($is_lidao == '2') {
                   /* include_once('PushLidaoAction.class.php');
                    $Pushs = new PushLidaoAction();
                    $Pushs->res_push($orderListArr['sys_num'], $instArr['check_code'], '新订单', 2);*/
                    //$this->success('接单成功！');exit;
                }

               /* include_once('PushAction.class.php');
                $Push = new PushAction();
                $Push->res_push($orderListArr['sys_num'], $instArr['check_code'], '新订单', 2);*/
            }

            return response()->json(['data' => null, 'desecption' => '接单成功', 'state' => 1]);
            $binds = DB::table('install_person')->where('id', $input['install_id'])->value("bind");
            if ($binds == 2) {
               /* include_once('PushAction.class.php');
                $Push = new PushAction();
                $Push->res_push($orderListArr['sys_num'], $instArr['check_code'], '新订单', 2);*/
            }
            exit;
        }else{
            DB::rollback();
            // 失败
            return response()->json(['data' => null, 'desecption' => '接单失败', 'state' => 2]);
            exit;
        }
    }


    /**
     * @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);
        }
    }

    //获取技师路径接口
    public function Json_install_line(Request $request){
        //if($_POST['version']==""){
        //	$_POST['version']="1.03";
        //	$_POST['line_serm']='P20171011032039376';
        //	$_POST['admin_id']=585;
        //}

        if($request->isMethod('post')){
            $input = $request->only('line_serm','admin_id');
            $rss=DB::table('order_list')->where(['serial_number'=>$input['line_serm'],'ser_id'=>$input['admin_id']])->first();
            if($rss){
                $res=DB::table('install_line')->where('line_serm',$input['line_serm'])->first();
                if($res){
                    return response()->json(['data'=>$res,'desecption'=>'成功','state'=>1]);exit;
                }else{
                    return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
                }
            }else{
                return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>3]);exit;
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'非法请求','state'=>5]);exit;
        }

    }

    //获取地址反馈标签 暂不用
    public function Json_dress_acquiring(Request $request){
        if($request->isMethod('post')){

            $list = DB::table('setmoney_type')->whereRaw("lt_parent_id=85  and FIND_IN_SET('2',lt_group)")->get();
            if($list){
                $list = $list->toArray();
                foreach($list as $key=>$val){
                    $datas[$key]['key'] = $val['sety_id'];
                    $datas[$key]['value'] = $val['sety_name'];
                }
                //echo $this->JsonMore($datas,2);exit;
                return response()->json(['data'=>$datas,'desecption'=>"成功",'state'=>1]);exit;
            }else{
                //echo '{"data":null,"desecption":"fail","state":1}';exit;
                return response()->json(['data'=>null,'desecption'=>"失败",'state'=>2]);exit;
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>"非法请求",'state'=>5]);exit;
        }
    }


    /**催单反馈
     * @param Request $request
     * @param sin_bid
     * @param sin_content
     * @param content
     * @param
     * @return mixed
     */
    public function Json_dress_feedback (Request $request){
        if($request->isMethod('post')){
            $poss['sin_bid']=$request->input('sin_bid');
            $poss['sin_centent']=$request->input('content')."；".$request->input('sin_bcentent');
            $poss['sin_state']='2';
            $res=DB::table('ser_infor')->where('sin_id',$request->input('sin_id')."'")->update($poss);
            if($res){
                return response()->josn(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
            }else{
                return response()->josn(['data'=>null,'desecption'=>'添加失败','state'=>2]);exit;
            }
        }else{
            return response()->josn(['data'=>null,'desecption'=>'非法请求','state'=>3]);exit;
        }
    }

    /**添加电池型号接口
     * @param Request $request
     * @param sin_bid
     * @param sin_content
     * @param content
     * @param
     * @return mixed
     */
    public function Json_add_version (Request $request){
        //$inventory=M("inventory");
        if($request->input('admin_id')=="" || $request->input('brand_name')=="" || $request->input('goodid')=="" || !$request->has('num')){
            return response()->json(['data'=>null,'desecption'=>'请求参数错误','state'=>3]);exit;
        }
        $input = $request->only('admin_id','brand_name','goodid','num','dediips');

        $inv_num=DB::table('inventory')->where(['inv_serid'=>$input['admin_id'],'inv_brand'=>$input['brand_name'],'inv_goodid'=>$input['goodid']])->value('inv_goodid','inv_num');
        //dd($inv_num);
        if($inv_num){
            if($inv_num['inv_goodid']==$input['num']){
                $res=1;
            }else{
                $poss['inv_num']=$input['num'];
                //"inv_serid='".$_POST['admin_id']."' and inv_brand='".$_POST['brand_name']."' and inv_goodid='".$_POST['goodid']."'"
                $res=DB::table('inventory')->where(['inv_serid'=>$input['admin_id'],'inv_brand'=>$input['brand_name'],'inv_goodid'=>$input['goodid']])->update($poss);

            }
        }else{
            $poss['inv_goodid']=$input['goodid'];
            $poss['inv_serid']=$input['admin_id'];
            $poss['inv_brand']=$input['brand_name'];
            $poss['inv_num']=$input['num'];
            //dd($poss);
            $res=DB::table('inventory')->insert($poss);
        }
        if($res){
            $this->addAppLog($input['admin_id'],$input['dediips'],'库存管理('.$input['phoneType'].')','编辑库存',"","");
            return response()->json(['data'=>null,'desecption'=>'操作成功','state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>'操作失败','state'=>2]);exit;
        }
    }

    //添加时间戳
    public function add_thistory ($number,$timetype,$time,$ser_id,$type){
        //$time_history=M("time_history");
        if($type==1){
            $poss[$timetype]=strtotime($time);
            $poss['tih_serid']=$ser_id;
            $poss['tih_number']=$number;
            DB::table('time_history')->insert($poss);
        }else{
            $poss[$timetype]=strtotime($time);
            $res=DB::table('time_history')->where('tih_number',$number)->value('tih_id');
            if($res){
                DB::table('time_history')->where('tih_number',$number)->update($poss);
            }
            //$time_history->where("tih_number='".$number."'")->save($poss);
        }
    }


    /**
     * 获取品牌
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年5月31日下午3:14:06
     */
    public function Json_get_brands(){

    	$arr = array('瓦尔塔','风帆','汤浅','理士','德尔福','骆驼','统一','博世');

    	return response()->json(['data'=>$this->intToStr($arr),'desecption'=>'获取成功','state'=>1]);exit;
    }



    /**商品型号选择
     * @param Request $request
     * @param admin_id
     * @brand_name
     * @return json
     */
    public function Json_good_version (Request $request){
        //$a =DB::table('inventory')->where('inv_goodid','84')->where('inv_serid','618')->delete();
        $a =DB::table('pj_goods')->where('brand_name','瓦尔塔')->count();
        //dump($a);
        //exit;
        if(!$request->input('brand_name') && !$request->input('admin_id')){
            return response()->json(['data'=>null,'desecption'=>'参数错误','state'=>3]);exit;
        }
        $input = $request->only('brand_name','admin_id');
        $version=DB::table('pj_goods')->where(['sort_directory'=>'蓄电池', 'brand_name'=>$input['brand_name']])->select('pg_id','pg_series','version')->get()->toArray();
        //dump($version);
        $goodid=DB::table('inventory')->where(['inv_serid'=>$input['admin_id'],])->select('inv_goodid','inv_num')->get()->toArray();
        //
        //'inv_brand'=>$input['brand_name']
        //dump($version);

        $json=array();
        $goodids=array();
        if($goodid){
            foreach( $goodid as $kg => $vg ){
                $goodids[$vg['inv_goodid']]=$vg['inv_num'];
                $ids[]=$vg['inv_goodid'];
            }

            //dump($goodids);
            //$goodid=trim($goodid,',');
            //$goodid=explode(',',$goodid);
            foreach( $version as $k => $v ){
                if($v['pg_series']==""){
                    $json[$k]['version']=$v['version'];
                }else{
                    $json[$k]['version']=$v['pg_series']."-".$v['version'];
                }
                if(in_array($v['pg_id'],$ids)){
                    $json[$k]['num']=$goodids[$v['pg_id']];
                    $json[$k]['type']='2';
                }else{
                    $json[$k]['num']='0';
                    $json[$k]['type']='1';
                }
               /* if($goodids[$v['pg_id']]>'0'){
                    //in_array($v['pg_id'], $goodid)
                    $json[$k]['num']=$goodids[$v['pg_id']];
                    $json[$k]['type']='2';
                }else{
                    $json[$k]['num']='0';
                    $json[$k]['type']='1';
                }*/
                $json[$k]['id']=$v['pg_id'];
            }
        }else{
            foreach( $version as $k => $v ){
                if($v['pg_series']==""){
                    $json[$k]['version']=$v['version'];
                }else{
                    $json[$k]['version']=$v['pg_series']."-".$v['version'];
                }
                $json[$k]['type']='1';
                $json[$k]['num']='0';
                $json[$k]['id']=$v['pg_id'];
            }
        }
        return response()->json(['data'=>$this->intToStr($json),'desecption'=>'成功','state'=>1]);exit;
    }


    /**服务中心确认账单金额
     * @param Request $request
     * @param admin_id
     * @param wat_num
     * @param dediips
     * @param apply_note
     * @return json
     */
    public function Json_business_review(Request $request){


        /*if(!$request->has(['admin_id','wat_num','dediips','apply_note'])){
            return response()->json(['data'=>null,'desecption'=>'访问参数错误','state'=>3]);exit;
        }*/
        if (!$request->has('admin_id') || !$request->has('wat_num') || !$request->has('dediips') || !$request->has('apply_note')){
            return response()->json(['data'=>null,'desecption'=>'访问参数错误','state'=>3]);exit;
        }
        $input = $request->only('admin_id','wat_num','dediips','apply_note','phoneType');
        $admin_infor = DB::table('admin')->where('id',$input['admin_id'])->first();
        $admin = DB::table('admin')->where('id',$input['admin_id'])->select('admin_acc','admin_group')->first();
        $apply_for_money=DB::table('statements_list')->where('stl_wat',$input['wat_num'])->select('stl_money','stl_ticket')->first();
        $stl_type['stl_type']=2;
        $wat_num=DB::table('settlement_list')->where('wat_num',$input['wat_num'])->get()->toArray();
        $post['apply_note']=$input["apply_note"];
        $post['settlement_ids']=$wat_num[0]['wat_num'];
        $post['crector']=$admin['admin_acc'];
        $post['group_type']=$admin['admin_group'];
        $post['public']=2;
        $post['note_model']="订单金额确认";
        //财务结算信息
        $arr['wat_num'] = $input['wat_num'];//结算单号
        $arr['ser_id'] = $input['admin_id'];//服务中心id
        $arr['company_name'] = $admin_infor['company_name'];//服务商
        $arr['apply_for_name'] = $admin_infor['admin_acc'];//申请人
        $arr['apply_for_money'] = $apply_for_money['stl_money']-$apply_for_money['stl_ticket'];//结算金额
        $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){
            //$ordestatu=M()->execute("update gone_order_status set st_five=st_five-1 where st_serid='".$_POST['admin_id']."'");
            DB::commit();//成功则提交
            DB::table('statements_list')->where('stl_wat',$input['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,',');
            //$sys_num=ltrim($sys_num,',');
            $AccArr["account_status"]=20;
            DB::table('order_list')->whereRaw("serial_number in (".$list_id.")")->update($AccArr);
            $add_note=DB::table('apply_note')->insert($post);
            $content=$wat_num[0]['wat_num']."结算号";
            $this->addAppLog($input['admin_id'],$input['dediips'],'派工单('.$input['phoneType'].')','审核结算单',"订单(".$input['wat_num'].")",$input['wat_num']);
            //echo '{"data":null,"desecption":"succes","state":1}';exit;
            return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
        }else{
            DB::rollback();//不成功，则回滚
            return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
        }
        //}
    }


    /**
     * @name 关闭最新推送消息
     * @param Request $request
     * @param admin_id
     * @param app_id
     * @return json
     *
     */
    public function Json_push_hide(Request $request){
        $input = $request->only('admin_id','app_id');
        $poss['map_serid']=$input['admin_id'];
        $poss['map_appid']=$input['app_id'];
        $res=DB::table('manageapp_show')->insert($poss);
        if($res){
            return response()->json(['data'=>null,'desecption'=>'成功','state'=>1]);exit;
        }else{
            return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
        }
    }
    public function Chuanshu(Request $request){
        $res =DB::table('order_list')->where('order_num','L20151026095325391')->first();
        dd($res);
    }

    public function jingwei($city,$address){//获取经纬度
        //http://restapi.amap.com/v3/geocode/geo?key=bf7919b601432722e4353ba6358e9c10&address=河北省石家庄市无极限七汲镇东小镇村&city=河北省&output='json'
        $url = "http://restapi.amap.com/v3/geocode/geo?key=bf7919b601432722e4353ba6358e9c10&address='".$address."'&city='".$city."'&output='json'";
        //$result = file_get_contents($url);
        $result = $this->http_get($url);
        $arr = json_decode($result,true);
        //dd($arr['geocodes'][0]['location']);
        if($arr['status'] == '1'){
            return $arr['geocodes'][0]['location'];
        }else{
            return '';
        }
    }

    function http_get($url, $ssl = FALSE)
    {
        $curl = curl_init(); // 启动一个CURL会话
        curl_setopt($curl, CURLOPT_URL, $url); // 要访问的地址
        if($ssl)
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0); // 对认证证书来源的检查
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 1); // 从证书中检查SSL加密算法是否存在
            curl_setopt($curl, CURLOPT_SSLVERSION, 3);
        }
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($curl, CURLOPT_TIMEOUT, 30); // 设置超时限制防止死循环
        curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); // 获取的信息以文件流的形式返回
        $tmpInfo = curl_exec($curl); // 执行操作
        if (curl_errno($curl)) {
            var_dump(curl_error($curl));
            return FALSE;
        }
        curl_close($curl); // 关闭CURL会话
        return $tmpInfo; // 返回数据
    }





    //图片获取车牌号
    public function pictoplace (Request $request){
        $url='http://sudianwang.com/OcrWeb/servlet/OcrServlet';//生产环境
        if($request->has('filedata')){
            $filedata = $request->input('filedata');
            $ParArray = array("filedata" => $filedata,"pid" => "6");
            //$ParArray = json_encode($ParArray);
            $resp = $this->https_post($url,$ParArray);
            return $resp;
            //return response()->json();
            //$obj=json_decode($resp,true);
        }else{
            return response()->json(['data'=>null,'desecption'=>'参数错误','state'=>2]);
        }

    }

    public function feeedGoods (Request $request){
        if ($request->has('id')){ //48987
            $id = $request->input('id');
            $order_id = DB::table('order_list')->where('id',$id)->value('order_goods_id');
            $msgArr = DB::table('order_msg')->where('id',$order_id)->select('goods_id','goods_brand')->first();
            $list = DB::table('pj_goods')->where('pg_id','!=',$msgArr['goods_id'])->where('brand_name',$msgArr['goods_brand'])->select('pg_id','brand_name','pg_series','version')->get();

            if (!$list->isEmpty()){
                $list = $list->toArray();
                foreach ($list as $k=>$v){
                    $json[$k]['goodid'] = $v['pg_id'];
                    if ($v['pg_series'] == ''){
                        $json[$k]['goodname'] = $v['brand_name'].'-'.$v['version'];
                    }else{
                        $json[$k]['goodname'] = $v['brand_name'].'-'.$v['pg_series'].'-'.$v['version'];
                    }
                }
                return response()->json(['data'=>$json,'desecption'=>'成功','state'=>1]);exit;
            }else{
                return response()->json(['data'=>null,'desecption'=>'暂无可换商品','state'=>2]);exit;
            }
        }
    }
    //修改商品
    public function exchangeGoods (Request $request){
        if ($request->has('id') && $request->has('goodid') && $request->has('goodname') && $request->has('admin_id') && $request->has('ser_type')){
            $input = $request->only('id','goodid','goodname','admin_id','ser_type');
            if ($input['ser_type'] == '1'){//服务商
                $arr['creact_id'] = $input['admin_id'];
                $arr['admin_id'] = $input['admin_id'];
                $arr['creact_type'] = '1';
                $admin_acc = DB::table('admin')->where('id',$input['admin_id'])->value('admin_acc');
                $arr['creact_name'] = $admin_acc;
            }else{
                $arr['creact_id'] = $input['admin_id'];
                $install = DB::table('install_person')->where('id',$input['admin_id'])->select('admin_id','install_name')->first();
                $arr['admin_id'] = $install['admin_id'];
                $arr['creact_name'] = $install['install_name'];
                $arr['creact_type'] = '2';
            }
            $listArr = OrderList::where('id',$input['id'])->select('order_num','serial_number')->first();
            //DB::connection()->enableQueryLog();
            $faker = DB::table('order_replace')->where('deal_state',1)->where('or_serialnum',$listArr->serial_number)->orderBy('creact_time','DESC')->limit('1')->first();
            //print_r(DB::getQueryLog());
            if ($faker){
                return response()->json(['data'=>null,'desecption'=>'你已经提交申请，无需重复提交','state'=>4]);exit;
            }
            $arr['or_num'] = $listArr->order_num;
            $arr['or_serialnum'] = $listArr->serial_number;
            $arr['or_goodid'] = $input['goodid'];
            $arr['or_goodname'] = $input['goodname'];
            $arr['creact_time'] = date('Y-m-d H:i:s');
            $insRes = DB::table('order_replace')->insert($arr);
            if ($insRes){
                return response()->json(['data'=>null,'desecption'=>'编辑成功','state'=>1]);exit;
            }else{
                return response()->json(['data'=>null,'desecption'=>'编辑失败','state'=>2]);exit;
            }
        }else{
            return response()->json(['data'=>null,'desecption'=>'参数错误','state'=>3]);exit;
        }
    }
	 //检验预约码
	public function Json_appoint ( Request $request )
	{

		$input = $request->only('id');
		if(!empty($input['id'])){
			$order_list=DB::table("order_list")->where("id",$input['id'])->select('order_goods_id')->first();
			if($order_list){
				$msg=DB::table("order_msg")->where("id",$order_list['order_goods_id'])->select('appoint_code','code_state','send_sms')->first();
				if($msg['appoint_code']!='' && $msg['code_state']=='1' && $msg['send_sms']=='2'){
					return response()->json(['data'=>$msg['appoint_code'],'desecption'=>'succes','state'=>1]);exit;
				}else{
					return response()->json(['data'=>null,'desecption'=>'fail','state'=>2]);exit;
				}
			}else{
				return response()->json(['data'=>null,'desecption'=>'数据异常','state'=>1001]);exit;
			}
		}else{
			return response()->json(['data'=>null,'desecption'=>'缺少参数','state'=>1001]);exit;
		}
	}
	//校验预约码
	public function Json_jy_appoint( Request $request )
	{

		$input = $request->only('id','code');
		if(!empty($input['id']) && !empty($input['code'])){
			$order_list=DB::table("order_list")->where("id",$input['id'])->select('order_goods_id')->first();
			if($order_list){
				$msg=DB::table("order_msg")->where("id",$order_list['order_goods_id'])->select('appoint_code','code_state','send_sms')->first();
				if($input['code']==$msg['appoint_code']){
					$poss['code_state']=2;
					$res=DB::table("order_msg")->where("id",$order_list['order_goods_id'])->update($poss);
					if($res){
						return response()->json(['data'=>null,'desecption'=>'校验成功','state'=>1]);exit;
					}else{
						return response()->json(['data'=>null,'desecption'=>'校验失败sys','state'=>2]);exit;
					}
				}else{
					return response()->json(['data'=>null,'desecption'=>'校验失败','state'=>2]);exit;
				}
			}else{
				return response()->json(['data'=>null,'desecption'=>'数据异常','state'=>1001]);exit;
			}
		}else{
			return response()->json(['data'=>null,'desecption'=>'缺少参数','state'=>1001]);exit;
		}
		//echo '{"data":null,"desecption":"参数异常","state":1001}';exit;
		//echo '{"data":null,"desecption":"校验失败","state":2}';exit;
		//echo '{"data":null,"desecption":"校验成功","state":1}';exit;
	}


	/**
	 * 退款管理列表
	 * @param type 1:未处理 2：已处理
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 * @author du 2021年6月3日下午3:30:22
	 */
	public function Json_refund_list( Request $request ){
		if(!$request->filled('type')){
			return response()->json(['data'=>null,'desecption'=>'缺少参数','state'=>3]);exit;
		}

		if($request->input('ser_type')!=1){
			return response()->json(['data'=>null,'desecption'=>'只有服务商可查看','state'=>3]);exit;
		}

		$admin_id = $request->input('admin_id');


		if($request->input('limit')>1){
			$offset =($request->input('limit')-1)*10;
		}else{
			$offset = 0;
		}


		$type = intval($request->input('type'));
		if($type==1){
			$list = DB::table('refund')
			->where('ser_id',$admin_id)
			->where('state',0)
			->offset($offset)
			->limit('10')
			->get()
			->toarray();//50:未处理；其它都为处理中
		}else{
			$list = DB::table('refund')
			->where('ser_id',$admin_id)
			->where('state','!=',0)
			->offset($offset)
			->limit('10')
			->get()
			->toarray();
		}


		if(!empty($list)){

			//$installids = array_column($list,'install_id');
			//dump($installids);
			//$installpics = DB::table('install_person')->whereIn('id',$installids)->pluck('install_pic','id');

			$nowtime = date("Y-m-d H:i:s");

			$statearr = array('0'=>'未处理','1'=>'跟进中','2'=>'电话回访中','3'=>'已回访','4'=>'已完成','5'=>'已驳回','50'=>'待确认');
			foreach ($list as $k =>$v){

				$list[$k]['refund_num'] = "T".$v['order_num'].$v['id'];
				/* if(isset($installpics[$v['install_id']])){
					$list[$k]['install_pic'] = $installpics[$v['install_id']];
				}else{
					$list[$k]['install_pic'] = '';
				} */
			//	$list[$k]['state_name'] = $statearr[$v['state']];

				if($v['state']>0){

					if($v['state']==5){
						$list[$k]['state_name'] = '已驳回';
					}else{
						$list[$k]['state_name'] = '已通过';
					}
					//电话变*
					$list[$k]['shr_phone'] = substr_replace($v['shr_phone'],'****',3,4);

				}else{
					$list[$k]['state_name'] = '未处理';
					$list[$k]['shr_phone'] = $v['shr_phone'];
				}


				//$imes48 = date("Y-m-d H:i:s",strtotime($v['created_at'])+48*3600);
				//echo $imes48;
				$list[$k]['times24'] = date("Y-m-d H:i:s",strtotime($v['created_at'])+2*3600);//处理时间

				$list[$k]['times'] = $this->time_diff($v['created_at'],$nowtime);//计时
			}

			return response()->json(['data'=>$this->intToStr($list),'desecption'=>'获取成功','state'=>1]);exit;
		}else{
			return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);exit;
		}


	}

	/**
	 * 退单管理详情
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 * @author du 2021年6月22日下午3:06:00
	 */
	public function Json_refund_detail(Request $request){
		if(!$request->filled('id')){
			return response()->json(['data'=>null,'desecption'=>'缺少参数','state'=>3]);exit;
		}

		if($request->input('ser_type')!=1){
			return response()->json(['data'=>null,'desecption'=>'只有服务商可查看','state'=>3]);exit;
		}

		$id = intval($request->input('id'));

		$info =  DB::table('refund')->where('id',$id)->select('id','order_num','ser_id','shr_name','shr_phone','shr_sheng','shr_shi','shr_xian','shr_adress','state','created_at','updated_at')->first();



		if(empty($info)){

			return response()->json(['data'=>null,'desecption'=>'此ID不存在','state'=>3]);exit;
		}

		$info['refund_num'] = 'T'.$info['order_num'].$id;

		if($info['state']>0){
		$info['shr_phone'] = substr_replace($info['shr_phone'],'****',3,4);
		}

		$orderlist = DB::table('order_list')
					->where('order_num',$info['order_num'])
					->select('serial_number','install_id','intall_person','goods_name','stauas','order_goods_id')
					->get()
					->toArray();

		$order_goods_ids = array_column($orderlist,'order_goods_id');

		$goods = DB::table('order_msg')->whereIn('id',$order_goods_ids)->pluck('goods_name','id');

		$status_name = array('10'=>'未接单','30'=>'安装中','34'=>'待审核','40'=>'已完成','50'=>'已退单');

		foreach ($orderlist as $k=>$v){

			$orderlist[$k]['goods_name'] = $goods[$v['order_goods_id']];



			$orderlist[$k]['stauas'] = $status_name[$v['stauas']];
		}

		$data = $info;
		$data['orderlist'] = $orderlist;

		return response()->json(['data'=>$this->intToStr($data),'desecption'=>'获取成功','state'=>1]);exit;


	}


	/**
	 * 通过处理
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 * @author du 2021年6月3日下午4:47:44
	 */
	public function Json_refund_pass(Request $request ){
		if(!$request->filled('id')||!$request->filled('content') ){
			return response()->json(['data'=>null,'desecption'=>'缺少参数','state'=>3]);exit;
		}

		if($request->input('ser_type')!=1){
			return response()->json(['data'=>null,'desecption'=>'只有服务商可查看','state'=>3]);exit;
		}

		$input = $request->only('admin_id','content','sety_id','id');
		$arr['state'] = 1;
		$arr['updated_at'] = date('Y-m-d H:i:s');

		$id = intval($request->input('id'));

		$infostate =  DB::table('refund')->where('id',$id)->first();

		if(!isset($infostate)){
			return response()->json(['data'=>null,'desecption'=>'ID不存在','state'=>5]);exit;
		}

		if($infostate['state']!='0'){
			return response()->json(['data'=>null,'desecption'=>'状态不正确','state'=>4]);exit;
		}

		$res = DB::table('refund')->where('id',$id)->update($arr);

		$admin_acc = Admin::where('id',$input['admin_id'])->value('admin_acc');

		$serial_number = $infostate['serial_number']??'';

		if($res){
			$adddata['afs_order'] = $infostate['order_num'];
			$adddata['afs_serial'] = $serial_number;
			$adddata['afs_sales'] = 1;
			$adddata['afs_paid'] = '0';

			$adddata['afs_type'] = $input['sety_id'];

			$adddata['afs_content'] = $input['content'];

			$adddata['afs_pid'] = $infostate['pt_id'];
			$adddata['afs_serid'] = $infostate['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);
			$this->Message($input['admin_id'],$infostate['sys_num'],'通过:'.$input['content']."(".$serial_number.")","退款管理(App-android)",$input['admin_id']);

			return response()->json(['data'=>null,'desecption'=>'通过成功','state'=>1]);exit;
		}else{
			return response()->json(['data'=>null,'desecption'=>'通过失败','state'=>2]);exit;
		}


	}

	/**
	 * 退款管理 驳回
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 * @author du 2021年6月3日下午5:20:45
	 */
	public function Json_refund_reject (Request $request)
	{
		if($request->input('ser_type')!=1){
			return response()->json(['data'=>null,'desecption'=>'只有服务商可查看','state'=>3]);exit;
		}
		$input = $request->only('admin_id','content','sety_id','id');
		$arr['state'] = 5;
		$arr['updated_at'] = date('Y-m-d H:i:s');

		$id = intval($request->input('id'));

		$infostate =  DB::table('refund')->where('id',$id)->first();

		if(!isset($infostate)){
			return response()->json(['data'=>null,'desecption'=>'ID不存在','state'=>5]);exit;
		}

		if($infostate['state']==5){
			return response()->json(['data'=>null,'desecption'=>'状态不正确已驳回','state'=>4]);exit;
		}

		$time24 = date("Y-m-d H:i:s",strtotime($infostate['created_at'])+2*3600);

		if($arr['updated_at']>$time24){
			return response()->json(['data'=>null,'desecption'=>'已超过驳回时间','state'=>3]);exit;
		}

		$res = DB::table('refund')->where('id',$id)->update($arr);

		$admin_acc = Admin::where('id',$input['admin_id'])->value('admin_acc');


		if($res){
			$serial_number = $infostate['serial_number']??'';

			$adddata['afs_order'] = $infostate['order_num'];
			$adddata['afs_serial'] = $serial_number;
			$adddata['afs_sales'] = 1;
			$adddata['afs_paid'] = '0';

			$adddata['afs_type'] = $input['sety_id'];

			$adddata['afs_content'] = $input['content'];

			$adddata['afs_pid'] = $infostate['pt_id'];
			$adddata['afs_serid'] = $infostate['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);

			$this->Message($input['admin_id'],$infostate['sys_num'],'驳回:'.$input['content']."(".$serial_number.")","退款管理(App-android)",$input['admin_id']);

			return response()->json(['data'=>null,'desecption'=>'驳回成功','state'=>1]);exit;
		}else{
			return response()->json(['data'=>null,'desecption'=>'驳回失败','state'=>2]);exit;
		}


	}

	/**
	 * 获取退款标签
	 * @return \Illuminate\Http\JsonResponse
	 * @author du 2021年6月3日下午5:32:04
	 */
	function Json_refund_getlabel(){
		$info = DB::table('setmoney_type')->where('lt_parent_id',31)->where('lt_statues',1)->select('sety_id','sety_name','lt_statues')->get()->toarray();
		return response()->json(['data'=>$this->intToStr($info),'state'=>1,'desecption'=>'获取成功']);exit;
	}


	/**
	 *  * @name 处罚单列表
     * @param  til_state      处罚单状态  1:未处理; 5:申诉中; 10:已确认; 20:已执行
     * @param  til_ticnum     处罚单号
     * @param  til_ornum      订单单号
     * @param  til_sernum     派工单号
     * @param  til_creactime  开始时间
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 * @author du 2021年6月4日上午10:57:58
	 */
	public function Json_ticket_list(Request $request){
		if(!$request->filled('til_state')){
			return response()->json(['data'=>null,'desecption'=>'缺少参数','state'=>3]);exit;
		}

		if($request->input('ser_type')!=1){
			return response()->json(['data'=>null,'desecption'=>'只有服务商可查看','state'=>3]);exit;
		}

		if($request->input('limit')>1){

			$offset =($request->input('limit')-1)*10;
		}else{

			$offset = 0;
		}

		$admin_id = $request->input('admin_id');

		$til_state = intval($request->input('til_state'));

		$ticket_list = DB::table('ticket_list');
		//DB::connection()->enableQueryLog();
		$list = $ticket_list
		->leftJoin('order_list','ticket_list.til_sernum','=','order_list.serial_number')
		->select('ticket_list.*','order_list.serial_number','order_list.install_id','order_list.intall_person','order_list.intall_phone','order_list.order_goods_id')
		->where('ticket_list.til_serid',$admin_id)
		//->where('til_state',$til_state)
		->offset($offset)
		->limit('10')
		->get()
		->toarray();//

		if($til_state==10){
			$list = $ticket_list->whereIn('til_state',[10,20])->get()->toarray();
		}else{
			$list = $ticket_list->where('til_state',$til_state)->get()->toarray();
		}
		//print_r(DB::getQueryLog());

		if(!empty($list)){

			$order_goods_id= array_column($list, 'order_goods_id');
			$goods_names = DB::table('order_msg')->whereIn('id',$order_goods_id)->pluck('goods_name','id');

			$nowtime = date("Y-m-d H:i:s");

			$installids = array_column($list,'install_id');
			//dump($installids);
			$installpics = DB::table('install_person')->whereIn('id',$installids)->pluck('install_pic','id');

			$statearr = array('1'=>'未处理','5'=>'申诉中','10'=>'已确认','20'=>'已执行');

			foreach ($list as $k =>$v){

				if(isset($installpics[$v['install_id']])){
					$list[$k]['install_pic'] = $installpics[$v['install_id']];
				}else{
					$list[$k]['install_pic'] = '';
				}
				$list[$k]['goods_name'] = $goods_names[$v['order_goods_id']]??'';
				$list[$k]['state_name'] = $statearr[$v['til_state']];


				$list[$k]['times48'] = date("Y-m-d H:i:s",strtotime($v['til_comptime'])+48*3600);//处理结束时间(工作人员处理)

				//if($v['til_comptime']){
				$list[$k]['times72'] = date("Y-m-d H:i:s",strtotime($v['til_creactime'])+72*3600);//申斥结束时间
				//}

				$list[$k]['times'] = strtotime($v['til_creactime'])+72*3600-time();//耗时

			}

		return response()->json(['data'=>$this->intToStr($list),'desecption'=>'获取成功','state'=>1]);exit;

		}else{
			return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);exit;
		}

	}

	/**
	 * 罚单详情
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 * @author du 2021年6月4日下午4:04:54
	 */
	public function Json_ticket_detail(Request $request){

		if(!$request->filled('id')){
			return response()->json(['data'=>null,'desecption'=>'缺少参数','state'=>3]);exit;
		}

		if($request->input('ser_type')!=1){
			return response()->json(['data'=>null,'desecption'=>'只有服务商可查看','state'=>3]);exit;
		}

		$input = $request->only('admin_id','id');

		$id = intval($input['id']);
		$admin_id = $request->input('admin_id');

		//DB::connection()->enableQueryLog();
		$info = DB::table('ticket_list')
				->leftJoin('order_list','ticket_list.til_sernum','=','order_list.serial_number')
				->select('ticket_list.*','order_list.serial_number','order_list.install_id','order_list.intall_person','order_list.intall_phone','order_list.order_goods_id')
				->where('ticket_list.til_serid',$admin_id)
				->where('til_id',$id)
				->first();
		//print_r(DB::getQueryLog());

		if(!isset($info)){
			return response()->json(['data'=>null,'desecption'=>'ID不存在','state'=>5]);exit;
		}

		$info['goods_name'] = DB::table('order_msg')->where('id',$info['order_goods_id'])->value('goods_name');

		$install_info = DB::table('install_person')->where('id',$info['install_id'])->first();

		$info['install_type'] = $install_info['install_type']??'1';

		if($install_info['install_year'] == ""){
			$year = "未登记";
		}else{
			if(count(explode('-',$install_info['install_year'])) >='2'){
				$install_year=explode('-',$install_info['install_year']);
				$year=date('Y')-$install_year[0];
				$mounth=date('m')-$install_year[1];
				if($mounth>0){
					$year=$year+1;
				}
				$year = $year."年技师";
			}else{
				$year = '未登记';
			}


		}

		$info['year'] = $year;

		if($install_info['install_pic']==""){
			$info['install_pic'] = '';
		}else{
			$info['install_pic'] = $this->picurl($install_info['install_pic']);
		}

		$list = DB::table('ticket_data')->where('til_evid',$id)->orderBy('til_creactime','ASC')->get()->toArray();

		$statearr = array('1'=>'未处理','5'=>'申诉中','10'=>'已确认','20'=>'已执行','30'=>'已撤销');
		$info['state_name'] = $statearr[$info['til_state']];


		$info['times48'] = date("Y-m-d H:i:s",strtotime($info['til_comptime'])+48*3600);//处理结束时间(工作人员处理)

		//if($v['til_comptime']){
		$info['times72'] = date("Y-m-d H:i:s",strtotime($info['til_creactime'])+72*3600);//申斥结束时间

		//图片处理

	/*	$feedarr=[];
		foreach($json as $k=>$v){
			$feedarr[$k] = $v;
			$feedarr[$k]['img_list'] = $pic[$v['til_creactime']]??[];
			if(isset($pic[$v['til_creactime']])){
				unset($pic[$v['til_creactime']]);
			}
		}
		if(!empty($pic)){
			$feedarrs=[];
			$num=0;
			foreach($pic as $k=>$v){
				$feedarrs[$num]=$centent[$k];
				$feedarrs[$num]['content']='';
				$feedarrs[$num]['img_list']=$v;
			}
			$feedarr = array_merge($feedarrs,$feedarr);
			$note_time = array_column($feedarr,'note_time');
			array_multisort($note_time,SORT_DESC,$feedarr);
		} */






		$data = $info;
		$data['list'] = $list;

		return response()->json(['data'=>$this->intToStr($data),'desecption'=>'获取成功','state'=>1]);exit;



	}


	/** 罚单申诉
	 * @param Request $request
	 * @param til_ticnum 处罚单号
	 * @param appeal_center 内容
	 * @param dediips  ip地址
	 * @param admin_id 服务商id
	 * @return Json
	 */
	public function Json_ticket_appeal (Request $request){

		if($request->input('ser_type')!=1){
			return response()->json(['data'=>null,'desecption'=>'只有服务商可查看','state'=>3]);exit;
		}


		DB::beginTransaction();
		if(!$request->filled('id') || $request->input('til_ticnum')=="" || $request->input('appeal_center')=="" || $request->input('admin_id')==""){
			return response()->json(['data'=>null,'desecption'=>'参数错误','state'=>3]);exit;
		}
		$input = $request->only('til_ticnum','appeal_center','admin_id','dediips','id','til_pic','til_sound','pic2','pic3','pic4','pic5','phoneType');

		$id = intval($input['id']);

		$infostate =  DB::table('ticket_list')->where('til_id',$id)->first();
		if(!isset($infostate)){
			return response()->json(['data'=>null,'desecption'=>'ID不存在','state'=>4]);exit;
		}
        $sys_num = OrderService::getOrderBy('order_num', $infostate['til_ornum'],['sys_num']);
		if($infostate['til_state']==5){
			return response()->json(['data'=>null,'desecption'=>'已提交过申诉','state'=>5]);exit;
		}

		if($infostate['til_state']>=10){
			return response()->json(['data'=>null,'desecption'=>'已确认','state'=>6]);exit;
		}

		$poss['til_comptime'] = date("Y-m-d H:i:s");

		$time48 = date("Y-m-d H:i:s",strtotime($infostate['til_creactime'])+72*3600);

		if($time48<$poss['til_comptime']){
			return response()->json(['data'=>null,'desecption'=>'已超过了申诉时间','state'=>7]);exit;
		}


		$poss['til_state'] = 5;

		$res = DB::table('ticket_list')->where('til_id',$id)->update($poss);

		$admin_acc = Admin::where('id',$input['admin_id'])->value('admin_acc');

		$sarr['til_content'] = $input['appeal_center'];
		$sarr['til_evid'] = $id;
		$sarr['til_type'] = 5;
		$sarr['til_creactime'] = date("Y-m-d H:i:s");
		$sarr['til_pic'] = $input['til_pic']??'';
		$sarr['til_creacter'] = $admin_acc;
		$sarr['til_creactid'] = $input['admin_id'];
		$sarr['til_sound'] = $input['til_sound']??'';

		$result = DB::table('ticket_data')->insertGetId($sarr);


		if($request->filled('pic2')){
			unset($sarr['til_content']);
			$sarr['til_pic'] = $input['pic2'];
			$result = DB::table('ticket_data')->insertGetId($sarr);

		}

		if($request->filled('pic3')){
			unset($sarr['til_content']);
			$sarr['til_pic'] = $input['pic3'];
			$result = DB::table('ticket_data')->insertGetId($sarr);

		}

		if($request->filled('pic4')){
			unset($sarr['til_content']);
			$sarr['til_pic'] = $input['pic4'];
			$result = DB::table('ticket_data')->insertGetId($sarr);

		}

		if($request->filled('pic5')){
			unset($sarr['til_content']);
			$sarr['til_pic'] = $input['pic5'];
			$result = DB::table('ticket_data')->insertGetId($sarr);

		}


		$ret = $this->Message($input['admin_id'],$sys_num,$input['appeal_center'],"申诉理由(".$input['phoneType'].")",'0');

		if($result&&$res && $ret!="失败" ){
			DB::commit();
			$this->addAppLog($input['admin_id'],$input['dediips'],'罚单列表('.$input['phoneType'].')','罚单列表',"罚单申诉(".$input['til_ticnum'].")",$sys_num);
			//echo '{"data":null,"desecption":"succes","state":1}';exit;
			return response()->json(['data'=>null,'desecption'=>'提交成功','state'=>1]);exit;
		}else{
			DB::rollback();//不成功，则回滚
			return response()->json(['data'=>null,'desecption'=>'提交失败','state'=>2]);exit;
		}
	}

	/**
	 * 罚单确认
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 * @author du 2021年6月4日下午3:55:36
	 */
	public function Json_ticket_confirm(Request $request){
		if(!$request->filled('id')|| $request->input('admin_id')==""){
			return response()->json(['data'=>null,'desecption'=>'参数错误','state'=>3]);exit;
		}

		if($request->input('ser_type')!=1){
			return response()->json(['data'=>null,'desecption'=>'只有服务商可查看','state'=>3]);exit;
		}

		$input = $request->only('admin_id','dediips','id','til_ticnum');

		$id = intval($input['id']);

		$infostate =  DB::table('ticket_list')->where('til_id',$id)->value('til_state');
		if(!isset($infostate)){
			return response()->json(['data'=>null,'desecption'=>'ID不存在','state'=>4]);exit;
		}

		if($infostate==10){
			return response()->json(['data'=>null,'desecption'=>'已确认过','state'=>5]);exit;
		}
		$arr['til_state'] = 10;
		$result = DB::table('ticket_list')->where('til_id',$id)->update($arr);
		if($result){

			$this->addAppLog($input['admin_id'],$input['dediips'],'罚单列表('.$input['phoneType'].')','罚单列表',"罚单确认(".$input['til_ticnum'].")",$input['til_ticnum']);
			//echo '{"data":null,"desecption":"succes","state":1}';exit;
			return response()->json(['data'=>null,'desecption'=>'确认成功','state'=>1]);exit;
		}else{

			return response()->json(['data'=>null,'desecption'=>'确认失败','state'=>2]);exit;
		}

	}



	/**
	 * 客户评价列表
	 * @param eva_status : 3:未处理；  5：申诉 ；  11：已处理
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 * @author du 2021年6月7日下午2:00:40
	 */
	public function EvaluationFormList(Request $request){

		if(!$request->filled('eva_status')){
			return response()->json(['data'=>null,'desecption'=>'缺少参数','state'=>3]);exit;
		}

		if($request->input('ser_type')!=1){
			return response()->json(['data'=>null,'desecption'=>'只有服务商可查看','state'=>3]);exit;
		}

		if($request->input('limit')>1){

			$offset =($request->input('limit')-1)*10;
		}else{
			$offset = 0;
		}

		$admin_id = $request->input('admin_id');

		$eva_status = intval($request->input('eva_status'));

		$arr = array(3,5,11);

		if(!in_array($eva_status,$arr)){

			return response()->json(['data'=>null,'desecption'=>'参数错误','state'=>3]);exit;

		}

		$evaluation_form = DB::table('evaluation_form');
		$list = $evaluation_form
		->leftJoin('order_list','evaluation_form.plat_number','=','order_list.order_num')
		->select('evaluation_form.*','order_list.serial_number','order_list.install_id','order_list.intall_person','order_list.intall_phone','order_list.p_id')
		->where('evaluation_form.ser_id',$admin_id)
		->offset($offset)
		->limit('10')
		->get()
		->toarray();//

		if($eva_status==11){
			$list = $evaluation_form->whereIn('eva_status',[10,15])->get()->toarray();
		}else{
			$list = $evaluation_form->where('eva_status',$eva_status)->get()->toarray();
		}

		if(!empty($list)){

			$installids = array_column($list,'install_id');
			//dump($installids);
			$installpics = DB::table('install_person')->whereIn('id',$installids)->pluck('install_pic','id');
			//数据状态：1新录入，10已审核，5申诉中，15申诉成功
			$statearr = array('3'=>'未处理','5'=>'申诉中');
			foreach ($list as $k =>$v){

				if(isset($installpics[$v['install_id']])){
					$list[$k]['install_pic'] = $installpics[$v['install_id']];
				}else{
					$list[$k]['install_pic'] = '';
				}

				if($v['eva_status']>=10){
					$list[$k]['state_name'] = '已处理';
				}else{
					$list[$k]['state_name'] = $statearr[$v['eva_status']];
				}

			}

		return response()->json(['data'=>$this->intToStr($list),'desecption'=>'获取成功','state'=>1]);exit;

		}else{
			return response()->json(['data'=>null,'desecption'=>'暂无数据','state'=>2]);exit;
		}

	}

	/**
	 * 客户评价详单
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 * @author du 2021年6月7日下午2:21:13
	 */
	public function EvaluationFormDetail(Request $request){
		if(!$request->filled('id')){
			return response()->json(['data'=>null,'desecption'=>'缺少参数','state'=>3]);exit;
		}

		if($request->input('ser_type')!=1){
			return response()->json(['data'=>null,'desecption'=>'只有服务商可查看','state'=>3]);exit;
		}

		$input = $request->only('admin_id','id');

		$id = intval($input['id']);

		$info = DB::table('evaluation_form')
				->leftJoin('order_list','evaluation_form.plat_number','=','order_list.order_num')
				->select('evaluation_form.*','order_list.serial_number','order_list.install_id','order_list.intall_person','order_list.intall_phone','order_list.p_id','order_list.customer_id')
				->where('evaluation_form.ser_id',$input['admin_id'])
				->where('eva_id',$id)
				->first();

		if(!isset($info)){
			return response()->json(['data'=>null,'desecption'=>'ID不存在','state'=>5]);exit;
		}


		$user_info = DB::table('user')->where('id',$info['customer_id'])->first();
		$info['shr_name'] = $user_info['shr_name'];
		$info['shr_phone'] = $user_info['shr_phone'];
		$info['shr_adress'] = $user_info['shr_sheng'].$user_info['shr_shi'].$user_info['shr_xian'].$user_info['shr_adress'];

		$install_info = DB::table('install_person')->where('id',$info['install_id'])->first();
		$info['install_type'] = $install_info['install_type']??'1';

		if($install_info['install_year'] == ""){
			$year = "未登记";
		}else{
			if(count(explode('-',$install_info['install_year'])) >='2'){
				$install_year=explode('-',$install_info['install_year']);
				$year=date('Y')-$install_year[0];
				$mounth=date('m')-$install_year[1];
				if($mounth>0){
					$year=$year+1;
				}
				$year = $year."年技师";
			}else{
				$year = '未登记';
			}
		}

		$info['year'] = $year;

		if($install_info['install_pic']==""){
			$info['install_pic'] = '';
		}else{
			$info['install_pic'] = $this->picurl($install_info['install_pic']);
		}

		$list = DB::table('evaluation_data')->where('evld_evid',$id)->orderBy('evld_id','DESC')->get()->toArray();
		$statearr = array('3'=>'未处理','5'=>'申诉中');
		if($info['eva_status']>=10){
			$info['state_name'] = '已处理';
		}else{
			$info['state_name'] = $statearr[$info['eva_status']];
		}


		$data = $info;
		$data['list'] = $list;

		return response()->json(['data'=>$this->intToStr($data),'desecption'=>'获取成功','state'=>1]);exit;
	}


	/**
	 * 客户评价处理
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 * @author du 2021年6月7日下午4:28:59
	 */
	public function EvaluationFormDeal(Request $request){

		if(!$request->filled('id')||!$request->filled('evld_content')){
			return response()->json(['data'=>null,'desecption'=>'缺少参数','state'=>3]);exit;
		}

		if($request->input('ser_type')!=1){
			return response()->json(['data'=>null,'desecption'=>'只有服务商可查看','state'=>3]);exit;
		}

		$input = $request->only('admin_id','id','dediips','evld_content','phoneType');
		$id = intval($input['id']);
		$info = DB::table('evaluation_form')->where('eva_id',$id)->value('eva_status');

		if(!isset($info)){
			return response()->json(['data'=>null,'desecption'=>'ID不存在','state'=>5]);exit;
		}

		if($info!=3){

			return response()->json(['data'=>null,'desecption'=>'状态不正确','state'=>5]);exit;

		}

	/* 	if($info>=10){
			return response()->json(['data'=>null,'desecption'=>'已处理','state'=>5]);exit;
		} */
		DB::beginTransaction();
		$arr['eva_status'] = 10;
		$result = DB::table('evaluation_form')->where('eva_id',$id)->update($arr);

		$admin_acc = Admin::where('id',$input['admin_id'])->value('admin_acc');

		$arrdata['evld_content'] = $input['evld_content'];
		$arrdata['evld_type'] = 10;//商家已处理
		$arrdata['evld_evid'] = $id;
		$arrdata['evld_creactime'] = date("Y-m-d H:i:s");

		$arrdata['evld_creacter'] = $admin_acc;
		$arrdata['evld_creactid'] = $input['admin_id'];


		$ret = DB::table('evaluation_data')->insert($arrdata);

		if($result&&$ret){
			DB::commit(); //提交
			$this->addAppLog($input['admin_id'],$input['dediips'],'客户评价列表('.$input['phoneType'].')','客户评价列表',"客户评价处理(".$id.")",$id);
			//echo '{"data":null,"desecption":"succes","state":1}';exit;
			return response()->json(['data'=>null,'desecption'=>'处理成功','state'=>1]);exit;
		}else{
			DB::rollback();//不成功，则回滚
			return response()->json(['data'=>null,'desecption'=>'处理失败','state'=>2]);exit;
		}

	}


	/**
	 * 客户评价申斥
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 * @author du 2021年6月7日下午5:10:19
	 */
	public function EvaluationFormAppeal(Request $request){

		if(!$request->filled('id')){
			return response()->json(['data'=>null,'desecption'=>'缺少参数','state'=>3]);exit;
		}

		if($request->input('ser_type')!=1){
			return response()->json(['data'=>null,'desecption'=>'只有服务商可查看','state'=>3]);exit;
		}

		$input = $request->only('admin_id','id','dediips','evld_content','evld_sound','evld_pic','content','sety_id','p_id','serial_number','pic2','pic3','pic4','pic5','phoneType');
		$id = intval($input['id']);
		$info = DB::table('evaluation_form')->where('eva_id',$id)->first();

		if(!isset($info)){
			return response()->json(['data'=>null,'desecption'=>'ID不存在','state'=>5]);exit;
		}

		if($info['eva_status']==5){
			return response()->json(['data'=>null,'desecption'=>'已提交过申诉','state'=>5]);exit;
		}

		if($info['eva_status']>=10){
			return response()->json(['data'=>null,'desecption'=>'已处理','state'=>6]);exit;
		}
		DB::beginTransaction();
		$arr['eva_status'] = 5;
		$result = DB::table('evaluation_form')->where('eva_id',$id)->update($arr);

		$admin_acc = Admin::where('id',$input['admin_id'])->value('admin_acc');

		$arrdata['evld_content'] = $input['content'].':'.$input['evld_content'];
		$arrdata['evld_type'] = 5;//商家已处理

		$arrdata['evld_evid'] = $id;
		$arrdata['evld_creactime'] = date("Y-m-d H:i:s");
		$arrdata['evld_pic'] = $input['evld_pic']??'';
		$arrdata['evld_creacter'] = $admin_acc;
		$arrdata['evld_creactid'] = $input['admin_id'];
		$arrdata['evld_sound'] = $input['evld_sound']??'';
		$arrdata['evld_label'] = $input['sety_id'];
		$ret = DB::table('evaluation_data')->insert($arrdata);

		if($request->filled('pic2')){
			unset($arrdata['evld_content']);
			$arrdata['evld_pic'] = $input['pic2'];
			$result = DB::table('evaluation_data')->insertGetId($arrdata);

		}

		if($request->filled('pic3')){
			unset($arrdata['evld_content']);
			$arrdata['evld_pic'] = $input['pic3'];
			$result = DB::table('evaluation_data')->insertGetId($arrdata);

		}

		if($request->filled('pic4')){
			unset($arrdata['evld_content']);
			$arrdata['evld_pic'] = $input['pic4'];
			$result = DB::table('evaluation_data')->insertGetId($arrdata);

		}

		if($request->filled('pic5')){
			unset($arrdata['evld_content']);
			$arrdata['evld_pic'] = $input['pic5'];
			$result = DB::table('evaluation_data')->insertGetId($arrdata);

		}




		$adddata['afs_order'] = $info['plat_number'];
		$adddata['afs_serial'] = $input['serial_number'];
		$adddata['afs_sales'] = 1;
		$adddata['afs_paid'] = '0';

		$adddata['afs_type'] = $input['sety_id'];

		$adddata['afs_content'] = $input['content'];

		$adddata['afs_pid'] = $input['p_id'];
		$adddata['afs_serid'] = $info['ser_id']??0;

		$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($result&&$ret){
			DB::commit(); //提交
			$this->addAppLog($input['admin_id'],$input['dediips'],'客户评价列表('.$input['phoneType'].')','客户评价列表',"客户评价申诉(".$id.")",$id);
			//echo '{"data":null,"desecption":"succes","state":1}';exit;
			return response()->json(['data'=>null,'desecption'=>'申诉成功','state'=>1]);exit;
		}else{
			DB::rollback();//不成功，则回滚
			return response()->json(['data'=>null,'desecption'=>'申诉失败','state'=>2]);exit;
		}


	}

	/**
	 * 获取申诉标签
	 * @param Request $request
	 * @return \Illuminate\Http\JsonResponse
	 * @author du 2021年6月8日上午9:21:14
	 */
	public function EvaluationFormGetLab (Request $request)
	{
		$res = DB::table('setmoney_type')->where('lt_parent_id',242)->select('sety_name','sety_id')->get()->toArray();
		if ($res) {

			return response()->json(['data' => $this->intToStr($res), 'state' => 1, 'desecption' => '获取成功']);
			exit;
		} else {
			return response()->json(['data' => '', 'desecption' => '暂无数据','state' => 2]);
			exit;
		}
	}





	/**获取罚单备注
	 * @param Request $request
	 * @param til_ticnum 处罚单号
	 * @param admin_id   服务商id
	 * @return Json
	 */
	public function Json_ticket_note(Request $request){
		$input = $request->only('til_ticnum','admin_id');
		$res=DB::table('note')->where('orders_id',$input['til_ticnum'])->select('note_content','note_type')->orderBy('note_time','ASC')->get();
		if($res){
			$res =$res->toArray();
			return response()->json(['data'=>$res,'desecption'=>'获取成功','state'=>1]);exit;
		}
		return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
	}



	/**
	 * @name 处罚单详情
	 * @param serial_number 处罚单号
	 * @return json
	 */
	public function Json_punish (Request $request){
		$data = DB::table('ticket_list')->where('til_ticnum',$request->input('serial_number'))->select('til_sernum','til_watnum','til_wats','til_price','til_creactime','til_state')->first();
		if($data['til_state'] == '1'){
			$data['state']='新罚单';
		}elseif($data['til_state'] == '5'){
			$data['state']='已确认';
		}elseif($data['til_state'] == '10'){
			$data['state']='申诉中';
		}
		if(!$data['til_watnum']){
			$data['til_watnum']='无';
		}
		if(!$data['til_wats']){
			$data['til_wats']='无';
		}

		//dd($data);
		if($data){
			return response()->json(['data'=>$this->intToStr($data),'desecption'=>'成功','state'=>1]);exit;
		}else{
			return response()->json(['data'=>null,'desecption'=>'失败','state'=>2]);exit;
		}

	}


    //接口访问
    function https_post($url,$data){
        $postdata = http_build_query($data);
        $options = array('http' => array('method' =>'POST','header' =>'Content-type:application/x-www-form-urlencoded','content' =>$postdata, 'timeout' =>15 * 60));
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;

    }

    //不参与奖惩平台
    public function rulesout ( ){
        $pt_id=array('111','112','108','95','106','110','120','136');
        $pttype = PlatformService::getPtIdByPtType();
        $pt_id = array_merge($pt_id,$pttype);
        return $pt_id;
    }


}
