<?php
declare (strict_types = 1);

namespace app\controller;

use app\BaseController;
use app\model\CarInfoT;
use app\model\ExportLogT;
use app\model\JobsT;
use app\model\PeerPhoneT;
use app\model\RepeatFrameT;
use excel\Excel;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Filesystem;
use think\facade\Queue;
use think\Request;
use think\response\Json;

class Task extends BaseController
{
    /**
     * @var JobsT
     */
    private $model;

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model = new JobsT;
    }

    public function test(){
        return Db::table('jobs_t')->where('id',8917)->update(['payload' => '{"job":"app\\jobs\\DelayQueue","maxTries":null,"timeout":null,"data":{"params":{"task_type":"5","original_filename":"\u5bfc\u51fa\u6e05\u6d17\u5931\u8d252019-02-01\u20142019-02-28\u7b2c3\u62791472\u6761(\u6267\u884c\u7ed3\u679c)","filename":"uploads\/20201122\\88559f1802f684d14c2e9aa1def8353e.xlsx"},"controller":"service\\CarInfoHandle","action":"carInfoUpdate"}}']);
    }

    /**
     * 显示资源列表
     *
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        return $this->fetch();
    }

    /**
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function taskInfo(){
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 20);
        $queue = $this->request->param('queue', '');
        if ($page <= 1) {
            $page = 1;
        }
        $offset = ($page - 1) * $limit;
        $query = $this->model->field(['id','payload','remark', 'type', 'queue', 'download_times',
            "(case `status` when 2 then '100' else '0' end)" => 'process',
            'date_format(from_unixtime(create_time),"%Y-%m-%d %H:%i:%s") as create_timestamp',
            "(case `type` when 1 then '导入' when 2 then '导出' when 3 then '同行电话' when 4 then '重复车架号' when 5 then '更新车辆信息' when 6 then '清除重复电话' when 7 then '删除重复数据' else '' end)" => 'type_txt',
            "(case `status` when 0 then '排队中' when 1 then '处理中' when 2 then '已完成' when 3 then '失败' else '' end)" => 'status', 'create_time']);
        if($queue != ''){
            $query = $query->where('queue','like','%'. $queue .'%')->whereOr('payload','like','%'. str_replace(['\\','"'],['_',''],json_encode($queue)) .'%');
        }
        $count = $query->count();
        $list = $query->limit($offset, (int)$limit)->order('id desc')->select()->toArray();
        foreach ($list as &$item){
            if($item['type'] == 1 || $item['type'] == 5){
                $item['type_txt'] = json_decode($item['payload'],true)['data']['params']['original_filename'] ?? '';
            }
            if ($item['type'] == 2) {
                $item['type_txt'] = $item['queue'] != 'default' ? $item['queue']: $item['type_txt'];
            }
            if($item['type'] == 3){
                $item['info_num'] = PeerPhoneT::where(['source' => $item['id']])->count();
            }
            if($item['type'] == 4){
                $item['info_num'] = RepeatFrameT::where(['source' => $item['id'], 'is_delete' => 0])->count();
            }
        }
        $this->layui_data['data'] = $list;
        $this->layui_data['count'] = $count;
        return json($this->layui_data);
    }

    /**
     * 显示创建资源表单页.
     *
     */
    public function create()
    {

    }

    /**
     * 保存新建的资源
     *
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function save()
    {
        $params = $this->request->param();
        $type = $this->request->param('task_type', '0');
        $original_filename = $this->request->param('original_filename');
        $filename = $this->request->param('filename');
        $peer_phone_number = $this->request->param('peer_phone_number');
        $queue = $this->request->param('queue', '');
        if(isset($params['source_id']) && $params['source_id'] > 0) {
            $job_info = JobsT::find($params['source_id']);
            $job_info_payload = json_decode($job_info->payload,true)['data']['params'];
            $params = [];
            $params['export_type'] = 'repeat';
            $params['export_limit'] = 0;
            $params['export_table'] = $job_info->type == 3? 'peer_phone_t': ($job_info->type == 4?'repeat_frame_t':'');
            $params['source_id'] = $job_info->id;
        }
        if (($type == 1 || $type == 5) && ( $filename == '' || ($filename != '' && !file_exists(public_path('public/storage') . $filename)))) {
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '导入文件不存在';
            return json($this->json_data);
        } else if ($type == 1 || $type == 5) {
            $original_filename = basename($original_filename);
            $original_filename = str_replace(strrchr($original_filename, '.'), '', $original_filename);
            $params['original_filename'] = $original_filename;
        }
        if ($type == 2 && (!isset($params['source_id']) || $params['source_id'] <= 0) && $params['export_date1'] == '' && $params['export_date2'] == '') {
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '请先填写注册日期';
            return json($this->json_data);
        } else if ($type == 2 && isset($params['export_type']) && $params['export_type'] != '' && !in_array($params['export_type'], ['bhx', 'bmc', 'failed', 'repeat', 'failed_bmc', 'none_bmc', 'success_bmc', 'repeat_delete'])) {
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '导出类型错误,请选择正确的导出类型';
            return json($this->json_data);
        } else if ($type == 2) {
			if(trim($params['export_limit'] . '') === ''){
				$this->json_data['code'] = 0;
				$this->json_data['msg'] = '导出数量必填';
				return json($this->json_data);
			}
            $where = [];
            $map_or1 = [];
            $map_or2 = [];
            if(isset($params['export_date1']) && $params['export_date1'] != ''){
                $where[] = ['car_info_t.register_date', '>=', $params['export_date1']];
            }
            if(isset($params['export_date2']) && $params['export_date2'] != ''){
                $where[] = ['car_info_t.register_date', '<=', $params['export_date2']];
            }
            if (isset($params['price1']) && $params['price1'] != '') {
                $where[] = ['car_info_t.purchase_price', '>=', $params['price1'] * 10000];
            }
            if (isset($params['price2']) && $params['price2'] != '') {
                $where[] = ['car_info_t.purchase_price', '<=', $params['price2'] * 10000];
            }
            if (isset($params['tag']) && $params['tag'] != '') {
                $where[] = ['car_info_t.tag', '=', $params['tag']];
            }
            if(isset($params['empty_phone_check']) && $params['empty_phone_check'] == 'yes'){
                $where[] = ['car_phone', '<>', ''];
            }
            if(isset($params['export_field'])){
                foreach ($params['export_field'] as $item){
                    $where[] = [$item, '<>', ''];
                }
            }
            if(isset($params['export_type']) && $params['export_type'] != '' && $params['export_limit'] != 0){
                if($params['export_type'] == 'bhx'){
                    $where[] = ['is_export_bhx', '=', 0];
                    $where[] = ['is_update_bhx', '=', 0];
                    $where[] = ['is_export_bmc', '=', 0];
                    $where[] = ['is_export_failed', '=', 0];
                    $where[] = ['is_export_failed_bmc', '=', 0];
                }
                if($params['export_type'] == 'bmc'){
                    $where[] = ['is_export_bhx', '>', 0];
                    $where[] = ['is_update_bhx', '>', 0];
                    $where[] = ['is_export_bmc', '=', 0];
                    if($params['update_no'] > 0){
                        $where[] = ['is_update_bhx', '=', $params['update_no']];
                    }
                }
                if ($params['export_type'] == 'failed') {
                    $where[] = ['is_export_bhx', '>', 0];
                    $where[] = ['is_update_bhx', '<', 0];
                    $where[] = ['is_export_bmc', '=', 0];
                    $where[] = ['is_export_failed', '=', 0];
                }
                if ($params['export_type'] == 'failed_bmc') {
                    $where[] = ['is_export_bhx', '>', 0];
                    $where[] = ['is_update_bhx', '<', 0];
                    $where[] = ['is_export_bmc', '=', 0];
                    $where[] = ['is_export_failed_bmc', '=', 0];
                }
                if ($params['export_type'] == 'none_bmc') {
                    $where[] = ['is_export_bhx', '=', 0];
                    $where[] = ['is_update_bhx', '=', 0];
                    $where[] = ['is_export_bmc', '=', 0];
                    $where[] = ['is_export_failed', '=', 0];
                    $where[] = ['is_export_failed_bmc', '=', 0];
                    $where[] = ['is_export_none_bmc', '=', 0];
                }
                if ($params['export_type'] == 'success_bmc') {
                    $where[] = ['is_export_bhx', '>', 0];
                    $where[] = ['is_update_bhx', '>', 0];
                    $where[] = ['is_export_bmc', '>', 0];
                    $insurer_date1 = $params['insurer_date1']??'';
                    $insurer_date2 = $params['insurer_date2']??'';
                    if($insurer_date1!=''){
                        $map_or1[] = ['car_info_t.insurer1_date', '>=', $insurer_date1];
                        $map_or2[] = ['car_info_t.insurer2_date', '>=', $insurer_date1];
                    }
                    if($insurer_date2!=''){
                        $map_or1[] = ['car_info_t.insurer1_date', '<=', $insurer_date2];
                        $map_or2[] = ['car_info_t.insurer2_date', '<=', $insurer_date2];
                    }
                }
            }
            $insurer_month1 = $params['insurer_month1']??'';
            $insurer_day1 = $params['insurer_day1']??'';
            $insurer_month2 = $params['insurer_month2']??'';
            $insurer_day2 = $params['insurer_day2']??'';
            if($insurer_month1 != '' && $insurer_day1 == '') {
                $map_or1[] = [Db::raw('month(car_info_t.insurer1_date)'), '>=', $insurer_month1];
                $map_or2[] = [Db::raw('month(car_info_t.insurer2_date)'), '>=', $insurer_month1];
            } else if ($insurer_month1 == '' && $insurer_day1 != '') {
                $map_or1[] = [Db::raw('day(car_info_t.insurer1_date)'), '>=', $insurer_day1];
                $map_or2[] = [Db::raw('day(car_info_t.insurer2_date)'), '>=', $insurer_day1];
            } else if ($insurer_month1 != '' && $insurer_day1 != '') {
                $map_or1[] = [Db::raw('DATE_FORMAT(car_info_t.insurer1_date,"%m-%d")'), '>=', substr('0' . $insurer_month1, -2) . '-' . substr('0' . $insurer_day1, -2)];
                $map_or2[] = [Db::raw('DATE_FORMAT(car_info_t.insurer2_date,"%m-%d")'), '>=', substr('0' . $insurer_month1, -2) . '-' . substr('0' . $insurer_day1, -2)];
            }
            if($insurer_month2 != '' && $insurer_day2 == '') {
                $map_or1[] = [Db::raw('month(car_info_t.insurer1_date)'), '<=', $insurer_month2];
                $map_or2[] = [Db::raw('month(car_info_t.insurer2_date)'), '<=', $insurer_month2];
            } else if ($insurer_month2 == '' && $insurer_day2 != '') {
                $map_or1[] = [Db::raw('day(car_info_t.insurer1_date)'), '<=', $insurer_day2];
                $map_or2[] = [Db::raw('day(car_info_t.insurer2_date)'), '<=', $insurer_day2];
            } else if ($insurer_month2 != '' && $insurer_day2 != '') {
                $map_or1[] = [Db::raw('DATE_FORMAT(car_info_t.insurer1_date,"%m-%d")'), '<=', substr('0' . $insurer_month2, -2) . '-' . substr('0' . $insurer_day2, -2)];
                $map_or2[] = [Db::raw('DATE_FORMAT(car_info_t.insurer2_date,"%m-%d")'), '<=', substr('0' . $insurer_month2, -2) . '-' . substr('0' . $insurer_day2, -2)];
            }
            if(count($map_or1) > 0){
                $map_or1 = array_merge([['car_info_t.insurer1_date', '<>', '']],$map_or1);
            }
            if(count($map_or2) > 0){
                $map_or2 = array_merge([['car_info_t.insurer1_date', '=', ''],['car_info_t.insurer2_date', '<>', '']],$map_or2);
            }
            $query = CarInfoT::where($where)->where(function ($query) use ($map_or1, $map_or2) {
                if (count($map_or1) > 0 && count($map_or2) > 0){
                    $query->whereOr([$map_or1, $map_or2]);
                }
            });
            $count = $query->count();
            if ($count < $params['export_limit']) {
                $this->json_data['code'] = 0;
                $this->json_data['msg'] = '当前导出数量为' . $count . ', 不足' . $params['export_limit'] . ',请检查条件';
                return json($this->json_data);
            }
        }
        if ($type == 3 && $peer_phone_number <= 0) {
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '请填写正确的个人电话重复数';
            return json($this->json_data);
        }
        if ($type == 3 || $type == 4) {
            $count = CarInfoT::count();
            if ($count <= 0) {
                $this->json_data['code'] = 0;
                $this->json_data['msg'] = '当前待处理数据为空,请检查条件';
                return json($this->json_data);
            }
        }
        $cache_name = md5(http_build_query($params));
        if (Cache::get($cache_name)) {
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '表单已提交,请勿重复操作';
            return json($this->json_data);
        }
        Cache::set($cache_name, 1, 60);
        $action = [
            '1'=>'import',
            '2'=>'export',
            '3'=>'peerPhones',
            '4'=>'carFrameNo',
            '5'=>'carInfoUpdate',
            '6'=>'deletePeerPhones',
            '7'=>'deleteCarFrameNo',
        ];
        $id = Queue::push(
            'app\jobs\DelayQueue',
            ['params' => $params, 'controller' => 'service\\CarInfoHandle', 'action' => $action[$type]],
            $queue, $type);
        if (!$id) {
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '任务创建失败';
        }
        return json($this->json_data);
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        //
    }

    /**
     * @return Json
     */
    public function upload(){
        $file = request()->file('file');
        $savename = Filesystem::disk('public')->putFile('uploads', $file);
        $filename = public_path('public\storage') . $savename;
        if ($this->checkUploadTpl($filename, $this->request->param('task_type'))) {
            $this->json_data['msg'] = '上传成功';
            $this->json_data['original_filename'] = $file->getOriginalName();
            $this->json_data['filename'] = $savename;
        } else {
            @unlink($filename);
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '上传文件[' . $file->getOriginalName() . ']与模板不匹配,请检查文件重新上传';
        }
        return json($this->json_data);
    }

    public function download($id)
    {
        $job_info = JobsT::find($id);
        $job_info->download_times = Db::raw('download_times+1');
        $downloadName = $this->downloadName($job_info);
        $job_info->save();
        return download(root_path(). 'public' . $job_info->remark, $downloadName);
    }

    public function process(){
        $list = JobsT::where('status', '=', 1)
            ->whereOr('create_time', '>=', strtotime(date('Y-m-d')))
            ->order('create_time desc')
            ->select();
        foreach ($list as $item) {
            $process = cache('shell_process_' . $item['id']);
            if($item->status == 1 || $process){
                $this->json_data['data'][] = [
                    'id' => $item['id'],
                    'process' => $process,
                ];
            }
            if($process >= 100){
                Cache::delete('shell_process_' . $item['id']);
            }
        }
        return json($this->json_data);
    }

    /**
     * 导出名称
     * @return \think\response\Json
     */
    public function exportName()
    {
        $export_date1 = $this->request->param('export_date1');
        $export_date2 = $this->request->param('export_date2');
        if ($export_date1 == '' || $export_date2 == '') {
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '注册日期范围不能为空';
            return json($this->json_data);
        }
        $type = $this->request->param('export_type');
        $export_limit = $this->request->param('export_limit');
        $name = '';
        if ($type == 'bhx') {
            $name = '导出清洗';
        } else if ($type == 'failed') {
            $name = '导出清洗失败';
        } else if ($type == 'bmc') {
            $name = '导出清洗成功至上传';
        } else if ($type == 'failed_bmc') {
            $name = '导出清洗失败至上传';
        } else if ($type == 'none_bmc') {
            $name = '导出未处理至上传';
        } else if ($type == 'success_bmc') {
            $name = '导出清洗成功再次清洗';
        }
        $count = ExportLogT::where('name','like', $name . $export_date1 . '—' . $export_date2 . '%')->count();
        $name .= $export_date1 . '—' . $export_date2 . '第' . ($count + 1) . '批' . $export_limit . '条';
        $this->json_data['name'] = $name;
        return json($this->json_data);
    }

    /**
     * 任务操作
     * @param $jobId
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function taskBtn($jobId){
        $job_info = JobsT::find($jobId);
        if($job_info->type == 2){
            $this->json_data['btns'] = '<a class="layui-btn" href="' . url('task/download', ['id' => $job_info->id]) . '">下载文件</a>';
        }else if($job_info->type == 3 && PeerPhoneT::where(['source' => $job_info->id])->count() > 0){
            $this->json_data['btns'] = '
                <button type="button" class="layui-btn" onclick="task_create(2,' . $job_info->id . ')">导出</button>
                <button type="button" class="layui-btn layui-btn-danger" onclick="task_create(6,' . $job_info->id . ')">清除重复电话</button>
                ';
        }else if($job_info->type == 4 && RepeatFrameT::where(['source' => $job_info->id, 'is_delete' => 0])->count() > 0){
            $this->json_data['btns'] = '
                <button type="button" class="layui-btn" onclick="task_create(2,' . $job_info->id . ')">导出</button>
                <button type="button" class="layui-btn layui-btn-danger" onclick="task_create(7,' . $job_info->id . ')">删除重复数据</button>
                ';
        }
        return json($this->json_data);
    }

    public function exportNum(){
        $params = $this->request->param();
        $where = [];
        $map_or1 = [];
        $map_or2 = [];
        if(isset($params['export_date1']) && $params['export_date1'] != ''){
            $where[] = ['car_info_t.register_date', '>=', $params['export_date1']];
        }
        if(isset($params['export_date2']) && $params['export_date2'] != ''){
            $where[] = ['car_info_t.register_date', '<=', $params['export_date2']];
        }
        if (isset($params['price1']) && $params['price1'] != '') {
            $where[] = ['car_info_t.purchase_price', '>=', $params['price1'] * 10000];
        }
        if (isset($params['price2']) && $params['price2'] != '') {
            $where[] = ['car_info_t.purchase_price', '<=', $params['price2'] * 10000];
        }
        if (isset($params['tag']) && $params['tag'] != '') {
            $where[] = ['car_info_t.tag', '=', $params['tag']];
        }
        if(isset($params['empty_phone_check']) && $params['empty_phone_check'] == 'yes'){
            $where[] = ['car_phone', '<>', ''];
        }
        if(isset($params['export_field'])){
            foreach ($params['export_field'] as $item){
                $where[] = [$item, '<>', ''];
            }
        }
        if(isset($params['export_type']) && $params['export_type'] != ''){
            if($params['export_type'] == 'bhx'){
                $where[] = ['is_export_bhx', '=', 0];
                $where[] = ['is_update_bhx', '=', 0];
                $where[] = ['is_export_bmc', '=', 0];
                $where[] = ['is_export_failed', '=', 0];
                $where[] = ['is_export_failed_bmc', '=', 0];
            }
            if($params['export_type'] == 'bmc'){
                $where[] = ['is_export_bhx', '>', 0];
                $where[] = ['is_update_bhx', '>', 0];
                $where[] = ['is_export_bmc', '=', 0];
                if($params['update_no'] > 0){
                    $where[] = ['is_update_bhx', '=', $params['update_no']];
                }
            }
            if ($params['export_type'] == 'failed') {
                $where[] = ['is_export_bhx', '>', 0];
                $where[] = ['is_update_bhx', '<', 0];
                $where[] = ['is_export_bmc', '=', 0];
                $where[] = ['is_export_failed', '=', 0];
            }
            if ($params['export_type'] == 'failed_bmc') {
                $where[] = ['is_export_bhx', '>', 0];
                $where[] = ['is_update_bhx', '<', 0];
                $where[] = ['is_export_bmc', '=', 0];
                $where[] = ['is_export_failed_bmc', '=', 0];
            }
            if ($params['export_type'] == 'none_bmc') {
                $where[] = ['is_export_bhx', '=', 0];
                $where[] = ['is_update_bhx', '=', 0];
                $where[] = ['is_export_bmc', '=', 0];
                $where[] = ['is_export_failed', '=', 0];
                $where[] = ['is_export_failed_bmc', '=', 0];
                $where[] = ['is_export_none_bmc', '=', 0];
            }
            if ($params['export_type'] == 'success_bmc') {
                $where[] = ['is_export_bhx', '>', 0];
                $where[] = ['is_update_bhx', '>', 0];
                $where[] = ['is_export_bmc', '>', 0];
                $insurer_date1 = $params['insurer_date1']??'';
                $insurer_date2 = $params['insurer_date2']??'';
                if($insurer_date1!=''){
                    $map_or1[] = ['car_info_t.insurer1_date', '>=', $insurer_date1];
                    $map_or2[] = ['car_info_t.insurer2_date', '>=', $insurer_date1];
                }
                if($insurer_date2!=''){
                    $map_or1[] = ['car_info_t.insurer1_date', '<=', $insurer_date2];
                    $map_or2[] = ['car_info_t.insurer2_date', '<=', $insurer_date2];
                }
            }
        }
		$insurer_month1 = $params['insurer_month1']??'';
		$insurer_day1 = $params['insurer_day1']??'';
		$insurer_month2 = $params['insurer_month2']??'';
		$insurer_day2 = $params['insurer_day2']??'';
		if($insurer_month1 != '' && $insurer_day1 == '') {
			$map_or1[] = [Db::raw('month(car_info_t.insurer1_date)'), '>=', $insurer_month1];
			$map_or2[] = [Db::raw('month(car_info_t.insurer2_date)'), '>=', $insurer_month1];
		} else if ($insurer_month1 == '' && $insurer_day1 != '') {
			$map_or1[] = [Db::raw('day(car_info_t.insurer1_date)'), '>=', $insurer_day1];
			$map_or2[] = [Db::raw('day(car_info_t.insurer2_date)'), '>=', $insurer_day1];
		} else if ($insurer_month1 != '' && $insurer_day1 != '') {
			$map_or1[] = [Db::raw('DATE_FORMAT(car_info_t.insurer1_date,"%m-%d")'), '>=', substr('0' . $insurer_month1, -2) . '-' . substr('0' . $insurer_day1, -2)];
			$map_or2[] = [Db::raw('DATE_FORMAT(car_info_t.insurer2_date,"%m-%d")'), '>=', substr('0' . $insurer_month1, -2) . '-' . substr('0' . $insurer_day1, -2)];
		}
		if($insurer_month2 != '' && $insurer_day2 == '') {
			$map_or1[] = [Db::raw('month(car_info_t.insurer1_date)'), '<=', $insurer_month2];
			$map_or2[] = [Db::raw('month(car_info_t.insurer2_date)'), '<=', $insurer_month2];
		} else if ($insurer_month2 == '' && $insurer_day2 != '') {
			$map_or1[] = [Db::raw('day(car_info_t.insurer1_date)'), '<=', $insurer_day2];
			$map_or2[] = [Db::raw('day(car_info_t.insurer2_date)'), '<=', $insurer_day2];
		} else if ($insurer_month2 != '' && $insurer_day2 != '') {
			$map_or1[] = [Db::raw('DATE_FORMAT(car_info_t.insurer1_date,"%m-%d")'), '<=', substr('0' . $insurer_month2, -2) . '-' . substr('0' . $insurer_day2, -2)];
			$map_or2[] = [Db::raw('DATE_FORMAT(car_info_t.insurer2_date,"%m-%d")'), '<=', substr('0' . $insurer_month2, -2) . '-' . substr('0' . $insurer_day2, -2)];
		}
        if(count($map_or1) > 0){
            $map_or1 = array_merge([['car_info_t.insurer1_date', '<>', '']],$map_or1);
        }
        if(count($map_or2) > 0){
            $map_or2 = array_merge([['car_info_t.insurer1_date', '=', ''],['car_info_t.insurer2_date', '<>', '']],$map_or2);
        }
        $query = CarInfoT::where($where)->where(function ($query) use ($map_or1, $map_or2) {
            if (count($map_or1) > 0 && count($map_or2) > 0){
                $query->whereOr([$map_or1, $map_or2]);
            }
        });
        $this->json_data['data'] = $query->count();
        $this->json_data['sql'] = CarInfoT::getLastSql();
        return json($this->json_data);
    }

    public function checkIsExistName($name,$type){
        if($name == ''){
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '文件名为空,请检查';
            return json($this->json_data);
        }
        if($type == 'update'){
            $name = basename($name);
            $name = str_replace(strrchr($name, '.'), '', $name);
        }
        $count = $this->model->where('queue', '=', $name)
            ->whereOr('payload', 'like', '%' . str_replace(['\\', '"'], ['_', ''], json_encode($name)) . '%')
            ->count();
        if ($count > 0) {
            $this->json_data['msg'] = $type == 'upload' ? '当前文件已处理,确定继续?' : '当前任务名已存在,是否继续';
        }else {
            $this->json_data['code'] = 2;
        }
        return json($this->json_data);
    }

    private function downloadName(JobsT $job_info){
        $job_params = json_decode($job_info->payload,true)['data']['params'];
        list(,$ext) = explode('.', $job_info->remark);
        if (empty($job_params['export_date1']))
            $downloadName = date('Y-m-d');
        else
            $downloadName = $job_params['export_date1'] . '-' . $job_params['export_date2'];
        if($job_info->queue != 'default'){
            $downloadName = $job_info->queue;
        }else if($job_params['export_type'] == 'repeat' && $job_params['export_table'] == 'repeat_frame_t'){
            $downloadName = '重复车架' . $downloadName;
        } else if($job_params['export_type'] == 'repeat' && $job_params['export_table'] == 'peer_phone_t'){
            $downloadName = '重复电话' . $downloadName;
        }
        $downloadName .= '.' . $ext;
        return $downloadName;
    }

    private function checkUploadTpl($file, $type)
    {
        $path_info = pathinfo($file);
        if ($type == 1) {
            $spreadsheetReader = Excel::loadFile($file);
            $sheet = $spreadsheetReader->getSheet(0);
            $highestColumn = $sheet->getHighestColumn(); // e.g 'F'
            $title = $sheet->rangeToArray("A1:{$highestColumn}1")[0];

			$tpl_title = ['税号', '初登日期', '车主', '证件号', '电话号码', '车架号', '车牌号', '发动机号', '车型', '新车购置价', '自定义标签'];
            // $tpl_title = ['区域', '购车日期', '客户姓名', '证件号码', '联系方式', '车架号', '车牌号', '发动机号', '品牌型号', '新车购置价', '保险公司', '商业止保日期', '交强止保日期', '被保险人', '被保险人证件号'];
            if (count(array_diff($tpl_title, $title)) > 0) {
                return false;
            }
        } else if ($type == 5 && $path_info['extension'] == 'xlsx') {
            $spreadsheetReader = Excel::loadFile($file);
            $sheet = $spreadsheetReader->getSheet(0);
            $highestColumn = $sheet->getHighestColumn(); // e.g 'F'
            $title = $sheet->rangeToArray("A1:{$highestColumn}1")[0];

            $tpl_title = ['车牌号', '车架号', '发动机号', '车主证件号码', '车主姓名', '被保人证件号', '被保人姓名', '投保人证件号', '投保人姓名', '品牌型号', '注册日期', '去年投保公司', '交强险到期时间', '商业险到期时间', '客户姓名', '客户电话1', '客户电话2', '客户类别', '地址信息', '客户备注1', '客户备注2', '用户姓名', '用户账号'];
            if (count(array_diff($tpl_title, $title)) > 0) {
                return false;
            }
        }
        return true;
    }
}