<?php
namespace App\Http\Controllers\RemarkNotes;
use App\Models\Admin;
use App\Services\AftersaleOrderService;
use Illuminate\Http\Request;
use App\Models\Orders;
use App\Models\User;
use App\Models\PreliminaryNote;
use App\Services\CommonService;
use BlueCity\Core\Inc\ErrorInc;
use DB;
use App\Http\Controllers\BaseController;
use App\Services\BmmcService;
use App\Models\Reply;
use App\Services\OrderService;

class NoteListController extends BaseController
{
	/**
	 * @name  预备注列表
 	 * @param order_num 平台单号
	 * @param Request $request
	 * @return \BlueCity\Core\Controllers\mixed
	 * @author du 2021年7月27日下午3:05:19
	 */
    public function index (Request $request)
    {
    	$Db = new PreliminaryNote();
        $session = $request->get('session_token');
        $where1 = [];
        $where1[1] = 1;

        if ($session['admin_groupnew'] != 7) {//管理员可以看全部
            $where1['company_id'] = $session['company_id'];
        }
        $where1 = CommonService::jointWhere($where1);

        $wcl = PreliminaryNote::where('cl_type','1')->whereRaw($where1)->count();
        $ycl = PreliminaryNote::where('cl_type','2')->whereRaw($where1)->count();
        //$re_count = PreliminaryNote::where('cl_type','3')->where('is_type',4)->count();
        $re_count = PreliminaryNote::where('cl_type','3')->whereRaw($where1)->count();
        $qb = PreliminaryNote::whereRaw($where1)->count();
        $show_Menu = [
            ['show_name'=>"全部",'show_num'=>$qb,'status'=>0],
            ['show_name'=>"未处理",'show_num'=>$wcl,'status'=>1],
            ['show_name'=>"已处理",'show_num'=>$ycl,'status'=>2],
        	['show_name'=>"已回复",'show_num'=>$re_count,'status'=>3],
        ];

        if ($request->filled('is_type') && !empty($request->input('is_type'))) {//数据类型
            if(!is_array($request->input('is_type'))){
                return $this->error('数据类型不正确', ErrorInc::FAILED_PARAM);
            }
        	$Db = $Db->whereIn('is_type',$request->input('is_type'));
        }
         //订单号
        if($request->filled('order_num')){
            $Db = $Db->where('order_num','like','%'.$request->input('order_num').'%');
        }
        if($request->filled('status')){
            $cl_type = $request->input('status');
            if($cl_type == 1){
                $Db = $Db->where('cl_type','1');
            }elseif($cl_type== 2){
                $Db = $Db->where('cl_type','2');
            }elseif($cl_type== 3){
                $Db = $Db->where('cl_type','3');
            }
        }
        $end_time = $request->input('end_time');

         if($request->input('start_time') == $end_time){
            $end_time = strtotime($end_time);
            $end_time = $end_time + "86400";
            $end_time = date("Y-m-d H:i:s",$end_time);
        }
        //开始时间
        if($request->filled('start_time')){
            $Db = $Db->where('create_time','>=',$request->input('start_time'));
        }

        //添加人
        if($request->filled('creactid')){
            $Db = $Db->where('creactid',$request->input('creactid'));
        }
        //结束时间
        if($request->filled('end_time')){
            $Db = $Db->where('create_time','<=',$end_time);
        }
        $page_size = (int)$request->input('page_size', 10);
        $page = (int)$request->input('page', 1);
        if ($page < 1) {
            $page = 1;
        }
        $paginate = $Db->whereRaw($where1)->paginate($page_size);
        $list = self::dataToArray($paginate->items());

        $all_button = BmmcService::whereButton($request->input('token'),$request->input('Pri_id'));

        $export = BmmcService::getTopButton('addNote,selectTb,replyDatas','', $all_button);
        $data['button_top'] = $export['button_top']??[];//顶部按钮
        $data['button_search'] = $export['button_search']??[];//搜索栏按钮
        $data['show_Menu'] = $show_Menu;
        if ($list) {
	        //$statueArr = array("1"=>'新订单','5'=>'处理中','10'=>'可派单','20'=>'已派单','34'=>'待完成','40'=>'已完成','50'=>'已撤销','55'=>'已撤销(补油费)');
	        $statueArr = OrderService::getOrderStatusName();
	        foreach($list as $k=>$v){
		         switch ( $v['is_type'] )
		            {
		            	case 1:
		            		$list[$k]['type_name'] = '留言备注';
		            		break;
	            		case 2:
	            			$list[$k]['type_name'] = '售后（无回复）';
	            			break;
	            		case 4:
	            			$list[$k]['type_name'] = '咨询备注';
	            			break;
                        case 5:
                             $list[$k]['type_name'] = '咨询备注';
                             break;
		            	default:
		            		$list[$k]['type_name'] = '留言备注';
		            		break;
		            }

		         $list[$k]['service_schedule'] = $statueArr[$v['service_schedule']]??'';

	            $button = [];

	            if($list[$k]['type'] == 1){
		            if($v['is_type']=='2'){
			            $button[] ='open,searchpic';
		            }elseif($v['is_type']=='4'|| $v['is_type']=='5'){

		            	//$btn.=',replay';
		            	/* if($v['cl_type']==3){
		            		$btn.=',show';
		            	}else */if($v['cl_type']==1){
		            		$button[] ='replay';
		            	}else{
		            		$button[] = 'show';
		            	}

		            }else{
		            	$button[] = 'open';
	            	}
	            }else{
		            if($v['is_type']=='2'){
			            $button[] = 'noOpen,searchpic';
		            }elseif($v['is_type']=='4' || $v['is_type']=='5'){
		            	/* if($v['cl_type']==3){
		            		$btn.=',show';
		            	}else */if($v['cl_type']==1){
		            		$button[] = 'replay';
		            	}else{
		            		$button[] = 'show';
		            	}

		            }else{
		            	$button[] = 'noOpen';
	            	}
	            }
	            if($list[$k]['cl_type'] == 1){
		            if($v['is_type']=='2'){
			            $button[] = 'typeDo,qualityAssurance';
		            }else{
		            	if($v['is_type']!=4){
		            		$button[] = 'typeDo';
		            	}
	            	}
	            }

	            if($list[$k]['tb_type'] == 1){
		            $button[] = 'tbType';
	            }

	            if($list[$k]['sys_type'] == 1){
		            $button[] = 'SynData';
	            }
	             if(!empty($v['sys_num'])){
		             $button[] = 'remarks';
	            }
	            $button = BmmcService::getListButton($button,$all_button);
	            $list[$k]['button_one'] = $button['button_one']??[];
	            $list[$k]['button_two'] = $button['button_two']??[];
	            $list[$k]['button_three'] = $button['button_three']??[];

	        }
	        	$data['list'] = $list;
	     		$data['page'] = [
	     			'count' => $paginate->total(),
	                'page'=> $paginate->currentPage(),
	                'page_size'=> $page_size,
	                'allPage'=> $paginate->lastPage()
	     		];

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

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

    /**
     * @name  公开操作
     * @param id  数据id
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月27日下午3:04:53
     */
    public function open(Request $request){
    	 if(!$request->filled('id')){
    	 	return $this->error('参数错误无id', ErrorInc::FAILED_PARAM, []);exit;
    	 }
        $id = intval($request->input('id'));
        $data['type'] = 2;
       // DB::connection()->enableQueryLog();
        $res = PreliminaryNote::where('id',$id)->update($data);
       // print_r(DB::getQueryLog());
        if($res){
        	$this->insertingLog('公开操作','', '修改ID为'.$id.'公开', '预备注', $request->ip(), $request->get('session_token')['admin_acc']);//日志
         	return $this->success('操作成功', $data); exit;

       } else {
        	return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);exit;
        }
    }

    /**
     * @name  公开操作
     * @param id       数据id
     * @param type      公开状态
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年7月28日上午11:44:42
     */
      public function noOpen(Request $request){
        if(!$request->filled('id')){
    	 	return $this->error('参数错误无id', ErrorInc::FAILED_PARAM, []);exit;
    	 }
        $id = intval($request->input('id'));
        $data['type'] = 1;
        $res = PreliminaryNote::where('id',$id)->update($data);
        if($res){
        	$this->insertingLog('公开操作','', '修改ID为'.$id.'不公开', '预备注', $request->ip(), $request->get('session_token')['admin_acc']);//日志
        	return $this->success('操作成功', $data); exit;

       } else {
        	return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);exit;
        }
    }

    /**
     * @name  处理操作
     * @param id  数据id
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月28日下午1:40:24
     */
    public function typeDo(Request $request){
    	if(!$request->filled('id')){
    		return $this->error('参数错误无id', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$id = intval($request->input('id'));
        $data['cl_type'] = 2;
        $data['deal_time'] = date("Y-m-d H:i:s");
        $data['deal_id'] = $request->get('session_token')['id'];
        $res = PreliminaryNote::where('id',$id)->update($data);
    	if($res){
    		$this->insertingLog('处理','', '修改'.$id.'已处理', '预备注', $request->ip(), $request->get('session_token')['admin_acc']);//日志
        	return $this->success('操作成功', $data); exit;

       } else {
        	return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);exit;
        }

    }

    /**
     * @name  同步备注
     * @param order_num 平台单号
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月28日下午3:04:46
     */
    public function tbType(Request $request){
    	if(!$request->filled('order_num')){
    		return $this->error('参数错误无order_num', ErrorInc::FAILED_PARAM, []);exit;
    	}
        $session = $request->get('session_token');
    	$order_num = $request->input('order_num');
        $data['tb_type'] = 2; //同步状态 1未同步 2已同步

        $sys_num = Orders::where('order_num',$order_num)->value('sys_num');

        if(!$sys_num){
        	return $this->error('没有该订单数据 无法同步', ErrorInc::MYSQL_FAILED, []);exit;//从订单表查数据
        }
        $remarks = PreliminaryNote::where('order_num',$order_num)->value('remarks');

        $res = CommonService::accMe($sys_num, '预添加备注', $remarks, $order_num, 1, $session['admin_groupnew'], $session['admin_acc'], $session['id']);
        if($res){
            PreliminaryNote::where('order_num',$order_num)->update($data);
            return $this->success('操作成功', []);exit;
        }else{
        	return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);exit;
        }
    }

    /**
     * @name  同步订单信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年7月28日下午3:40:54
     */
    public function synData(Request $request){
    	if(!$request->filled('order_num')){
    		return $this->error('参数错误无order_num', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$order_num = $request->input('order_num');
    	$res = Orders::where('order_num',$order_num)->select('goods_name','order_status','new_customer_id','ser_id','sys_num')->first();

    	if($res){
    		$user = User::where('id',$res['new_customer_id'])->select('shr_phone','shr_name','shr_sheng','shr_shi','shr_xian','shr_adress')->first();
    		if($user){
    			$res['userdata'] = $user['shr_name'].",".$user['shr_phone'].",".$user['shr_sheng'].$user['shr_shi'].$user['shr_xian'].$user['shr_adress'];
    		}
    		$ser = Db::table('admin')->where('id',$res['ser_id'])->select('admin_acc','company_name')->first();
    		if($ser){
    			$res['serdata'] = $ser['admin_acc'].",".$ser['company_name'];
    			$update['serdata'] = $res['serdata'];
    		}
    		$update['userdata'] = $res['userdata']??'';
    		$update['service_schedule'] = $res['order_status'];
    		$update['goods_name'] = $res['goods_name'];
    		$update['sys_num'] = $res['sys_num'];
    		$update['sys_type'] = '2';
    		$data = PreliminaryNote::where('order_num',$order_num)->update($update);
    		if($data){
    			return $this->success('操作成功', []);exit;
    		}else{
    			return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);exit;
    		}
    	}else{
    		return $this->error('没有该订单数据 无法同步', ErrorInc::MYSQL_FAILED, []);exit;
    	}
    }

    /**
     * @name  查看售后图片
     * @param id       数据id
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月28日下午5:09:33
     */
    public function searchpic ( Request $request ){
    	if(!$request->filled('id')){
    		return $this->error('参数错误无id', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$list = Db::table("feedsaltemp")->where("fst_ntid",$request->input('id'))->select('fst_url')->get()->toArray();
    	if($list){
    		return $this->success('操作成功',$list);exit;
    	}else{
    		return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
    	}

    }


    /**
     * @name  添加预备注信息
     * @param array list(order_num,remarks,type,url)
     * @param Request $request
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月29日上午10:28:07
     */
    public function addNote(Request $request){
    	if(!$request->filled('list')){
    		return $this->error('参数错误无list', ErrorInc::FAILED_PARAM, []);exit;
    	}
        $data = $request->input('list');

        foreach ($data as $key => $value) {
        	$sys_num = Db::table('orders')->where('order_num',$data[$key]['order_num'])->value('sys_num');
        	if($sys_num){
        		$data[$key]['sys_num'] = $sys_num;

        		$data[$key]['url'] =  $data[$key]['url']??'';

        		$rest = CommonService::accMe($data[$key]['sys_num'], "预添加备注同步" , $data[$key]['remarks'], '', '', $request->get('session_token')['admin_groupnew'], $request->get('session_token')['admin_acc'], $request->get('session_token')['id']);
        		if($rest){
        			$res = $this->preliminaryNote($data[$key]['order_num'], $data[$key]['remarks'],2,$data[$key]['type'],$request->get('session_token'),$data[$key]['url'] );
        		}else{
        			$res = $this->preliminaryNote($data[$key]['order_num'], $data[$key]['remarks'],1,$data[$key]['type'],$request->get('session_token'),$data[$key]['url'] );
        		}
        	}else{
        		$res = $this->preliminaryNote($data[$key]['order_num'], $data[$key]['remarks'],1,$data[$key]['type'],$request->get('session_token'),$data[$key]['url'] );
        	}
        	if($res){
        		$msgBody['action'] = 'Ordersystem/noteList';
        		$msgBody['pushtype'] = 5;
        		$msgBody['s_type'] = 1;//'1' 新咨询 3：已回复;
        		$msgBody['time'] = date("H:i:s");

        		if($data[$key]['type']==4){
        			$msgBody['tittle'] = '新咨询';//新咨询
        			$msgBody['msg'] = '有新的咨询信息请及时处理';//'有新的咨询信息请及时处理';

        			//推送新咨询
        			$ress = $this->Notifier(1,'','1');
        			$ids = $ress->original['Data']['inn_admin_id'];
        			$ids = explode(',',$ids);
        			foreach ($ids as $k =>$v){
        				$this->pushRecord($msgBody,'',5,$res,$v,0,0);
        			}
        		}elseif($data[$key]['type']==5){
        			$msgBody['tittle'] = '请咨询客户';//新咨询
        			$msgBody['msg'] = '有新的咨询信息请及时处理';//'有新的咨询信息请及时处理';
        			//推送给客服
        			$group = $this->getGroupIds();
        			foreach ($group as $k=>$v){
        				$this->pushRecord($msgBody,'',5,$res,0,0,$v);
        			}
        		}

        	}
        }
        if($res){
        	return $this->success('操作成功', []);exit;
        }else{
        	return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);
        	exit;
        }

    }

   /**
    * 批量同步选择
    * @param Request $request
    * @return \BlueCity\Core\Controllers\mixed
    * @author du 2021年7月29日上午11:26:30
    */
    public function selectTb(Request $request){
        $where['cl_type'] = 1;//处理状态 1未处理 2处理
        //$where['tb_type'] = 2;//同步状态 1未同步 2已同步
        //$where['sys_type'] = 1;//同步订单信息 1未同步 2同步
        $res = Db::table('preliminary_note')->where($where)->select('order_num','user')->get()->toArray();
        $res = array_unique($res, SORT_REGULAR);
         if($res){
         	return $this->success('获取成功', $res);exit;
        }else{
        	return $this->error('暂无数据', ErrorInc::MYSQL_FAILED, []);exit;
        }
    }

    /**
     * 获取类型
     * @return \BlueCity\Core\Controllers\mixed
     * @author du 2021年7月29日下午5:25:16
     */
    public function getSelectType(Request $request){
    	$admin_groupnew = $request->get('session_token')['admin_groupnew'];
    	$groupIds = $this->getGroupIds();
    	if(in_array($admin_groupnew,$groupIds)){
    		$arr = array(['id'=>'1','name'=>'留言备注'],['id'=>'2','name'=>'售后（无回复）']);//,['id'=>'4','name'=>'咨询备注']

    	}else{
    		$arr = array(['id'=>'1','name'=>'留言备注'],['id'=>'2','name'=>'售后（无回复）']);//,['id'=>'5','name'=>'咨询备注']
    	}
    	return $this->success('获取成功', $arr);
    }

    /**
     * 获取部门ＩＤ
     * @return multitype:
     * @author du 2021年7月29日上午11:27:01
     */
    public function getGroupIds(){
    	$result = DB::table('department')->whereRaw("FIND_IN_SET('84',bmmc_pids)")->pluck('id')->toarray();
    	$groupIds = array_merge($result,[84]);

    	return $groupIds;
    }

     /**|----------------------------------------------------------------
     * @name 申请售后
     * @param id 订单id号
     * @param serial_number 派工单号
     * @param order_num 系统单号
     * @return \Illuminate\Http\JsonResponse
     * |----------------------------------------------------------------
     */
     public function qualityAssurance(Request $request)
    {
        if (!$request->filled('id')) {
            return $this->error('缺少数据id', ErrorInc::INVALID_PARAM);
            exit;
        }
        $Input = $request->all();
        $order_id = OrderService::getOrderBy('order_num', $Input['order_num'],['id']);
        if (!$order_id) {
            return $this->error('单号错误', ErrorInc::INVALID_PARAM);
            exit;
        }
        DB::beginTransaction();
        $id = $Input['id'];
        $list=DB::table('feedsaltemp')->where("fst_ntid",$id)->get();
        $list = CommonService::dataToArray($list);
        $pic = [];
        if($list){
            $pic = array_column($list, 'fst_url');
        }
        $Input['pic'] = $pic;
        $Input['id'] = $order_id;
        $data = AftersaleOrderService::addAfter($Input,$request->get('session_token'),$request->ip());
        if($data['code']) {
            $rea = DB::table("preliminary_note")->where("id", $id)->update(['cl_type' => '2', 'deal_time' => date("Y-m-d H:i:s"), 'deal_id' => $request->get('session_token')['id']]);
            if (!$rea) {
                DB::rollBack();
                return $this->error('处理状态修改失败', ErrorInc::MYSQL_STEP_FAILED);
                exit;
            }
            DB::commit();
            $this->operatingTime($data['data']['serserial_number'], '申请质保时间', date("Y-m-d H:i:s"), $data['data']['order_num'], $request->get('session_token')['admin_acc']);//订单操作时间
            $this->insertingLog('申请质保，', $data['data']['sys_num'], '订单' . $data['data']['sys_num'], '订单管理', $request->ip(), $request->get('session_token')['admin_acc']);//日志
            return $this->success($data['msg']);
        }else{
            DB::rollBack();
            return $this->error($data['msg'], $data['data']);exit;
        }
    }


    /**
     * 回复展示信息
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年7月29日上午8:43:04
     */
    public function show(Request $request){
    	if (!$request->filled('id')) {
    		return $this->error('参数错误无id', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$id = intval($request->input('id'));
    	$info = PreliminaryNote::where('id',$id)->first();
    	$list =  Reply::where('info_id',$id)->whereIn('reply_type',[2,3])->get()->toarray();
    	$data = $info;
    	$data['reList'] = $list??'';
    	if($info){
    	 return $this->success('获取成功', $data); exit;
       } else {
        	return $this->error('暂无数据', ErrorInc::DATA_EMPTY,[]);exit;
        }

    }

    /**
     * 咨询回复
     * @param int id
     * @param string reply_content 回复内容
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @author du 2021年7月29日下午4:30:03
     */
    public function reply(Request $request){
    	$input = $request->only('reply_content','id','re_type');
        $checkKey = CommonService::checkKey(['reply_content','id','re_type'],$input);
        if($checkKey['code']!=1){
            return $this->error('参数'.$checkKey['data'].'未填写,或值为空', ErrorInc::INVALID_PARAM);exit;
        }
        $rs = PreliminaryNote::where('id',$request->input('id'))->select('order_num','sys_num','cl_type','is_type','deal_time')->first();
    	if($rs['cl_type']==2){
    		return $this->error('状态不正确已经处理', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$re_type = $request->input('re_type');
    	$admin = $request->get('session_token');

    	if ($re_type==1) {//回复
    	    if($rs['deal_time'] == '' or $rs['deal_time'] == null){
                $arr['deal_time'] = date("Y-m-d H:i:s");
            }
    		$arr['cl_type'] = 3;//已回复
            $reply_type = 2;
    		$re_content = "【回复】".$request->input('reply_content');
    	} elseif ($re_type==2) { //追加
    		$arr['cl_type'] = 1;
            $reply_type = 3;
    		$re_content = "【追问】".$request->input('reply_content');
    	}else{
    		return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	DB::beginTransaction(); //开启事务
    	$result = Reply::insertGetId([
    			'info_id' => $request->input('id'),
    			'reply_content'   => $re_content,
    			'reply_person'   => $admin['admin_acc'],
    			'reply_id'   => $admin['id'],
    			'reply_type'   => $reply_type,
    			'created_at' => date('Y-m-d H:i:s')
    	]);
    	$ret = PreliminaryNote::where('id',$request->input('id'))->update($arr);
    	if ($result && $ret) {
    		DB::commit(); //提交
    		$msgBody['action'] = 'Ordersystem/noteList';
    		$msgBody['pushtype'] = 5;
    		$msgBody['time'] = date("H:i:s");

    		if ($re_type==1) {
    			$msgBody['s_type'] = 3;//'1' 新咨询 3：已回复;
    			$msgBody['tittle'] = '有新的回复信息';//新咨询
    			$msgBody['msg'] = '信息已回复';//'有新的咨询信息请及时处理';
    			$creater_id = DB::table('preliminary_note')->where('id',$request->input('id'))->value('creactid');
    			$this->pushRecord($msgBody,'',5,$result,$creater_id,0,0);
    			//$this->webPushScocket('有新的回复信息', 'Ordersystem/noteList', '信息已回复',3,$result,$creater_id);
    		}elseif ($re_type==2) {
    			$msgBody['s_type'] = 1;
    			if($rs['is_type']==5){
    				$msgBody['tittle'] = '请咨询客户';//新咨询
    				$msgBody['msg'] = '有新的咨询信息请及时处理';//'有新的咨询信息请及时处理';
    				//推送给客服
    				$group = $this->getGroupIds();
    				foreach ($group as $k=>$v){
    					$this->pushRecord($msgBody,'',5,$result,0,0,$v);
    				}

    			}else{
    				$msgBody['tittle'] = '新咨询';//新咨询
    				$msgBody['msg'] = '有新的咨询信息请及时处理';//'有新的咨询信息请及时处理';
	    			$res = $this->Notifier(1,'','1');
	    			$ids = $res->original['Data']['inn_admin_id'];
	    			$ids = explode(',',$ids);
	    			foreach ($ids as $k =>$v){
	    				$this->pushRecord($msgBody,'',5,$result,$v,0,0);
	    			}
    			//$this->webPushScocket('有新的追问信息', 'Ordersystem/noteList', '有新的追问信息请及时处理',1,$result,$ids);
    			}
    		}else{
    			return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);exit;
    		}
    		$this->insertingLog('回复追问', $rs['sys_num'], '订单号' . $rs['order_num'], '预备注', $request->ip(), $request->get('session_token')['admin_acc']);//日志
    		return $this->success('操作成功', []);exit;
    	} else {
    		DB::rollback();//回滚
    		return $this->error('操作失败', ErrorInc::MYSQL_FAILED, []);exit;
    	}
    }


    /**
     * 确认解决 更新为已处理
     * @param id
     * @param  $request
     * @author du 2021年7月29日下午1:37:29
     */
    public function updateStatus(Request $request) {
    	if (!$request->filled('id')) {
    		return $this->error('参数错误无id', ErrorInc::FAILED_PARAM, []);exit;
    	}
    	$id = intval($request->input('id'));
    	$rs = PreliminaryNote::where('id',$id)->select('order_num','sys_num','cl_type','deal_time')->first();
    	if($rs['cl_type']==2){
    		return $this->error('状态不正确已经处理', ErrorInc::FAILED_PARAM, []);exit;
    	}
        if($rs['deal_time'] == '' or $rs['deal_time'] == null){
            $arr['deal_time'] = date("Y-m-d H:i:s");
        }
    	$arr['cl_type'] = 2;
    	$ret = PreliminaryNote::where('id',$id)->update($arr);
    	if ($ret) {
    		$this->insertingLog('更新状态已处理', $rs['sys_num'], '订单号' . $rs['order_num'], '预备注', $request->ip(), $request->get('session_token')['admin_acc']);//日志
    		return $this->success('确认成功', []);exit;
    	} else {
    		return $this->error('确认失败', ErrorInc::MYSQL_FAILED, []);exit;
    	}
    }



    /**
     * @name 添加预备注
     * @param $order_num 平台单号
     * @param $note_type 备注类型
     * @param $note_content 备注内容
     * @param $send_num 派工单号
     * @param $public_state 安装点是否可见 1：可见；2：不可见
     * @param $session
     * @return int
     * @author du 2021年7月28日下午3:27:23
     */
    public function preliminaryNote($order_num,$note_content,$tbType,$is_type,$session,$url)
    {
    	$data['order_num'] = $order_num;
    	$data['user'] = $session['admin_acc'];
    	$data['remarks'] = $note_content;
    	$data['create_time'] = date("Y-m-d H:i:s");
    	$data['tb_type'] = $tbType;
    	$data['is_type'] = $is_type;
    	$data['creactid'] = $session['id'];
        $data['company_id'] = $session['company_id'];
    	$rest = PreliminaryNote::insertGetId($data);
    	if($rest&&$url){
    		foreach ($url as $v){
    			$poss_pic['fst_ordernum'] = $order_num;
    			$poss_pic['fst_url'] = $v ;
    			$poss_pic['fst_ntid'] = $rest;
    			DB::table('feedsaltemp')->insert($poss_pic);
    		}

    	}
    	return $rest;
    }

    /**
     * @name 回复数量统计
     * @param time 时间
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/9/8
     */
    public function replyDatas(Request $request)
    {
        if (!$request->filled('time')) {
            return $this->error('参数错误无time', ErrorInc::FAILED_PARAM, []);exit;
        }
        $rime1 = $request->input('time');
        $rime2 = date("Y-m-d",strtotime($rime1." +1 month"));
        $sql = "SELECT COUNT(id) as num,deal_id FROM gone_preliminary_note where create_time BETWEEN '".$rime1."' and '".$rime2."' and cl_type =2 GROUP BY deal_id";
        $list = DB::select($sql);
        if($list){
            $deal_id = array_column($list,'deal_id');
            $list = array_combine($deal_id,$list);
        }
        $rsql = "SELECT COUNT(id) as num, reply_id FROM gone_reply where created_at BETWEEN '".$rime1."' and '".$rime2."' and reply_type =2 GROUP BY reply_id";
        $reply = DB::select($rsql);
        if($reply){
            $reply_id = array_column($reply,'reply_id');
            $reply = array_combine($reply_id,$reply);
        }
        if($deal_id && $reply_id){
            $admin_id = array_merge($deal_id,$reply_id);
        }elseif($deal_id){
            $admin_id = $deal_id;
        }elseif($reply_id){
            $admin_id = $reply_id;
        }else{
            return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
        }
        $admin_id = array_unique($admin_id);
        $admin = Admin::whereIn('id',$admin_id)->pluck('admin_acc','id');
        foreach( $admin_id as $k => $v ) {
            $data[$k]['admin_acc'] = $admin[$v];
            $data[$k]['num1'] = $list[$v]['num'] ? $list[$v]['num'] : 0;//普通处理数量
            $data[$k]['num2'] = $reply[$v]['num'] ? $reply[$v]['num'] : 0;//回复数量
            $data[$k]['num3'] = $data[$k]['num1']  + $data[$k]['num2'];//总数量
        }
        return $this->success('获取成功',$data);exit;
    }



    /**
     * @name 获取申请售后的必要参数
     * @param Request $request
     * @return mixed
     * @author du
     * @date 2021/12/6
     */
    public function pgNumber(Request $request)
    {
        if(!$request->filled('order_num')){
            return $this->error('参数错误', ErrorInc::FAILED_PARAM, []);
        }else{
            $data = AftersaleOrderService::pgNumber('',$request->input('order_num'));
            if($data){
                return $this->success('成功', $data); exit;
            }else{
                return $this->error('暂无数据', ErrorInc::DATA_EMPTY);exit;
            }
        }
    }


}
