<?php
namespace app\controller;

use app\BaseController;
use app\model\CarInfoT;
use app\model\JobsT;
use app\model\PeerPhoneT;
use app\model\RepeatFrameT;
use library\Tree;
use think\facade\Db;
use think\facade\Filesystem;
use think\response\Json;

class Index extends BaseController
{
    /**
     * @var CarInfoT
     */
    private $model;

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

    /**
     * 显示资源列表
     *
     * @return string
     * @throws \Exception
     */
    public function index()
    {
        $peer_phone_count = PeerPhoneT::count();
        $repeat_frame_count = RepeatFrameT::count();
        $this->assign('peer_phone_count', $peer_phone_count);
        $this->assign('repeat_frame_count', $repeat_frame_count);
        return $this->fetch();
    }

    /**
     * @return Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function carInfo(){
        $params = $this->request->param();
        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 20);
        if ($page <= 1) {
            $page = 1;
        }
        $offset = ($page - 1) * $limit;
        $map = $this->getQueryCondition($params);
        $jobs_name = [];
        if (isset($params['is_check_peer_phone']) && $params['is_check_peer_phone'] > 0) {
            $params['data_check'] = 'car_phone_check';
        }
        if ((isset($params['is_check_repeat_frame']) && $params['is_check_repeat_frame'] > 0) ||
            isset($params['is_delete_frame']) && $params['is_delete_frame'] > 0) {
            $params['data_check'] = 'car_frame_check';
        }
        if(isset($params['data_check']) && $params['data_check'] == 'car_frame_check'){
            $query = Db::table('repeat_data_t')->alias('car_info_t')->field('car_info_t.*')
                    ->where($map)
                    ->order('repeat_data_t.car_frame_no desc');
            if (isset($params['is_delete_frame']) && $params['is_delete_frame'] > 0) {
                $query = $query->where('repeat_data_t.repeat_id', '=', $params['is_delete_frame']);
            }
        }else if(isset($params['data_check']) && $params['data_check'] == 'car_phone_check'){
            $query = $this->model->rightJoin('peer_phone_t','peer_phone_t.phone = car_info_t.car_phone')->field('car_info_t.*')->where($map)->order('peer_phone_t.phone desc');
            if (isset($params['is_check_peer_phone']) && $params['is_check_peer_phone'] > 0) {
                $jobs_info = JobsT::find($params['is_check_peer_phone']);
                $job_info_payload = json_decode($jobs_info->payload, true)['data']['params'];
                if (isset($job_info_payload['export_date1']) && $job_info_payload['export_date1'] != '') {
                    $query = $query->where('car_info_t.register_date', '>=', $job_info_payload['export_date1']);
                }
                if (isset($job_info_payload['export_date2']) && $job_info_payload['export_date2'] != '') {
                    $query = $query->where('car_info_t.register_date', '<=', $job_info_payload['export_date2']);
                }
                $query = $query->where('peer_phone_t.source', '=', $params['is_check_peer_phone'])->where('car_info_t.car_number', 'REGEXP', '^[1-9][[:digit:]]{7}((0[[:digit:]])|(1[0-2]))(([0|1|2][[:digit:]])|3[0-1])[[:digit:]]{3}$|^[1-9][[:digit:]]{5}[1-9][[:digit:]]{3}((0[[:digit:]])|(1[0-2]))(([0|1|2][[:digit:]])|3[0-1])[[:digit:]]{3}([0-9]|X)$');
            }
        } else if (isset($params['export_name']) && $params['export_name'] != '') {
            $export_name = JobsT::where('queue', 'like', '%' . $params['export_name'] . '%')->column('queue,download_times', 'id');
            $ids = array_keys($export_name);
            $query = $this->model->where($map)->where(function ($query) use ($ids) {
                $query->whereOr(['car_info_t.is_export_bhx' => $ids, 'car_info_t.is_export_bmc' => $ids]);
            })->field('*')->order('is_export_bhx desc,is_export_bmc desc');
        } else {
            $query = $this->model->where($map)->order('id desc');
        }
        $map_or1 = [];
        $map_or2 = [];
		$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);
        }
        if (count($map_or1) > 0 && count($map_or2) > 0) {
            $query = $query->where(function ($query) use ($map_or1, $map_or2) {
                if (count($map_or1) > 0 && count($map_or2) > 0) {
                    $query->whereOr([$map_or1, $map_or2]);
                }
            });
        }
        if (isset($params['data_filter']) && !empty($params['data_filter'])) {
            $map = $this->getAddStatusQuery(array_flip($params['data_filter']));
            if(count($map) > 1 ){
                $query = $query->where(function ($query) use ($map) {
                    if (count($map) > 0){
                        $query->whereOr($map);
                    }
                });
            }else {
                $query = $query->where($map);
            }
        }
        $count = $query->count();
        $list = $query->limit($offset, $limit)->select()->toArray();
        if(isset($export_name) && count($export_name) > 0 ){
            $jobs_name = $jobs_name + $export_name;
        }
        foreach ($list as &$item) {
            $jobs_name[$item['is_export_bhx']] = $jobs_name[$item['is_export_bhx']] ?? JobsT::find($item['is_export_bhx']);
            $jobs_name[$item['is_export_bmc']] = $jobs_name[$item['is_export_bmc']] ?? JobsT::find($item['is_export_bmc']);
            $item['export_bhx_name'] = $jobs_name[$item['is_export_bhx']]['queue'] ?? '';
            $item['export_bmc_name'] = $jobs_name[$item['is_export_bmc']]['queue'] ?? '';
            $item['bhx_download_times'] = $jobs_name[$item['is_export_bhx']]['download_times'] ?? 0;
            $item['bmc_download_times'] = $jobs_name[$item['is_export_bmc']]['download_times'] ?? 0;
        }
        $this->layui_data['data'] = $list;
        $this->layui_data['count'] = $count;
        return json($this->layui_data);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit($id)
    {
        $car_info = $this->model->find($id);
        if($this->request->isGet()){
            $this->assign('info', $car_info);
            return $this->fetch();
        }else if($this->request->isPost()){
            $data = $this->request->param();
            $car_info->car_no = $data['car_no'] ?? $car_info->car_no;
            $car_info->car_frame_no = $data['car_frame_no'] ?? $car_info->car_frame_no;
            $car_info->engine_no = $data['engine_no'] ?? $car_info->engine_no;
            $car_info->factory_model = $data['factory_model'] ?? $car_info->factory_model;
            $car_info->register_date = $data['register_date'] ?? $car_info->register_date;
            $car_info->purchase_price = $data['purchase_price'] ?? $car_info->purchase_price;
            $car_info->company = $data['company'] ?? $car_info->company;
            $car_info->insurer1_date = $data['insurer1_date'] ?? $car_info->insurer1_date;
            $car_info->insurer2_date = $data['insurer2_date'] ?? $car_info->insurer2_date;
            $car_info->car_man = $data['car_man'] ?? $car_info->car_man;
            $car_info->car_number = $data['car_number'] ?? $car_info->car_number;
            $car_info->car_phone = $data['car_phone'] ?? $car_info->car_phone;
            $car_info->id_man = $data['id_man'] ?? $car_info->id_man;
            $car_info->id_number = $data['id_number'] ?? $car_info->id_number;
            $car_info->id_phone = $data['id_phone'] ?? $car_info->id_phone;
            $car_info->insured_man = $data['insured_man'] ?? $car_info->insured_man;
            $car_info->insured_number = $data['insured_number'] ?? $car_info->insured_number;
            $car_info->insured_phone = $data['insured_phone'] ?? $car_info->insured_phone;

            $car_info->update_timestamp = date('Y-m-d H:i:s');
            if($car_info->save()){
                return json($this->json_data);
            }else {
                $this->json_data['code'] = 0;
                $this->json_data['msg'] = '保存失败';
                return json($this->layui_data);
            }
        }

    }

    /**
     * 删除指定资源
     * @param $id
     * @return Json
     */
    public function delete($id)
    {
        //
        $car_frame_no = $this->model->where('id', $id)->value('car_frame_no');
        Db::startTrans();
        try {
            $this->model->destroy($id);
            if ($this->model->where('car_frame_no', $car_frame_no)->count() == 1)
                RepeatFrameT::where('car_frame_no', $car_frame_no)->delete();
            $this->json_data['code'] = 1;
            $this->json_data['msg'] = $this->json_data['code'] ? '删除成功' : '删除失败';
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '删除失败: '. $e->getMessage();
        }

        return json($this->json_data);
    }

    /**
     * 批量删除
     * @return Json
     * @throws \Exception
     */
    public function deletes()
    {
        //
        $params = array_filter($this->request->param());
        $params_1 = $params;
        unset($params_1['car_phone_empty'], $params['data_check'], $params['car_frame_check']);
        if (empty($params_1)) {
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '搜索条件不能为空';
            return json($this->json_data);
        }
        $map = $this->getQueryCondition($params);
        if($this->model->where($map)->delete()){
            $this->json_data['msg'] = '删除成功';
        }else {
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '删除失败';
        }
        return json($this->json_data);
    }

    /**
     * 批量删除
     * @return Json
     * @throws \Exception
     */
    public function phoneReset()
    {
        //
        $params = array_filter($this->request->param());
        $params_1 = $params;
        unset($params_1['car_phone_empty'], $params['data_check'], $params['car_frame_check']);
        if (empty($params_1)) {
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '搜索条件不能为空';
            return json($this->json_data);
        }
        $map = $this->getQueryCondition($params);
        if($this->model->where($map)->update(['car_phone' => ''])){
            $this->json_data['msg'] = '请求成功';
        }else {
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '请求失败';
        }
        return json($this->json_data);
    }

    /**
     * @param $id
     * @return Json
     */
    public function clearPhone($id){
        $this->json_data['code'] = $this->model->where('id', $id)->update(['car_phone' => '']);
        $this->json_data['msg'] = $this->json_data['code'] ? '操作成功' : '操作失败';
        return json($this->json_data);
    }

    /**
     * 保存更新的资源
     *
     * @param int $id
     * @param $field
     * @param $value
     * @return \think\Response
     */
    public function update($id, $field, $value)
    {
        $this->json_data['code'] = $this->model->where('id', $id)->update([$field => $value]);
        $this->json_data['msg'] = $this->json_data['code'] ? '更新成功' : '更新失败';
        return json($this->json_data);
    }

    public function login(){
        $password = $this->request->param('password','');
        if ($password === 'wuwei088277') {
            session('login_time', time());
            session('last_action', time());
        }else {
            $this->json_data['code'] = 0;
            $this->json_data['msg'] = '密码错误';
        }
        return json($this->json_data);
    }

    /**
     * @param $params
     * @return array
     */
    private function getQueryCondition($params)
    {
        $map = [];
        if (isset($params['car_man']) && $params['car_man'] != '') {
            $car_man = explode(',', str_replace(',', '', $params['car_man']));
            array_walk($car_man, function (&$value) {
                $value = '%' . $value . '%';
            });
            $map[] = ['car_info_t.car_man', 'like', $car_man];
        }
        if (isset($params['tag']) && $params['tag'] != '') {
            $tags = explode(',', str_replace(',', '', $params['tag']));
            array_walk($tags, function (&$value) {
                $value = '%' . $value . '%';
            });
            $map[] = ['car_info_t.tag', 'like', $tags];
        }
        if (isset($params['factory_model']) && $params['factory_model'] != '') {
            $factory_model = explode(',', str_replace(',', '', $params['factory_model']));
            array_walk($factory_model, function (&$value) {
                $value = '%' . $value . '%';
            });
            $map[] = ['car_info_t.factory_model', 'like', $factory_model];
        }
        if (isset($params['car_frame_no']) && $params['car_frame_no'] != '') {
            $map[] = ['car_info_t.car_frame_no', '=', $params['car_frame_no']];
        }
        if (isset($params['car_no']) && $params['car_no'] != '') {
            $map[] = ['car_info_t.car_no', '=', $params['car_no']];
        }
        if (isset($params['car_number']) && $params['car_number'] != '') {
            $map[] = ['car_info_t.car_number', '=', $params['car_number']];
        }
        if (isset($params['car_phone']) && $params['car_phone'] != '') {
            $map[] = ['car_info_t.car_phone', '=', $params['car_phone']];
        }
        if (isset($params['register_date']) && $params['register_date'] != '') {
            $map[] = ['car_info_t.register_date', '=', $params['register_date']];
        }
        if (isset($params['car_phone_empty']) && $params['car_phone_empty'] == 'yes') {
            $map[] = ['car_info_t.car_phone', '<>', ''];
        }
        if (isset($params['car_phone_empty']) && $params['car_phone_empty'] == 'no') {
            $map[] = ['car_info_t.car_phone', '=', ''];
        }
        if (isset($params['car_phone_repeat']) && $params['car_phone_repeat'] == 'yes') {
            $map[] = ['car_info_t.id', '=', 'peer_phone_t.id'];
        }
        if (isset($params['is_update_bhx']) && $params['is_update_bhx'] > 0 ) {
            $map[] = ['car_info_t.is_update_bhx', '=', $params['is_update_bhx']];
        }
        if (isset($params['is_export_bhx']) && $params['is_export_bhx'] > 0 ) {
            $map[] = ['car_info_t.is_export_bhx', '=', $params['is_export_bhx']];
        }
        if (isset($params['is_export_bmc']) && $params['is_export_bmc'] > 0 ) {
            $map[] = ['car_info_t.is_export_bmc', '=', $params['is_export_bmc']];
        }
        if (isset($params['is_export_failed']) && $params['is_export_failed'] > 0 ) {
            $map[] = ['car_info_t.is_export_failed', '=', $params['is_export_failed']];
        }
        if (isset($params['is_export_failed_bmc']) && $params['is_export_failed_bmc'] > 0 ) {
            $map[] = ['car_info_t.is_export_failed_bmc', '=', $params['is_export_failed_bmc']];
        }
        if (isset($params['is_export_none_bmc']) && $params['is_export_none_bmc'] > 0 ) {
            $map[] = ['car_info_t.is_export_none_bmc', '=', $params['is_export_none_bmc']];
        }

        if (isset($params['source']) && $params['source'] > 0 ) {
            $map[] = ['car_info_t.source', '=', $params['source']];
        }
        if(isset($params['register_date1']) && $params['register_date1'] != ''){
            $map[] = ['car_info_t.register_date', '>=', $params['register_date1']];
        }
        if(isset($params['register_date2']) && $params['register_date2'] != ''){
            $map[] = ['car_info_t.register_date', '<=', $params['register_date2']];
        }
        if (isset($params['price1']) && $params['price1'] != '') {
            $map[] = ['car_info_t.purchase_price', '>=', $params['price1'] * 10000];
        }
        if (isset($params['price2']) && $params['price2'] != '') {
            $map[] = ['car_info_t.purchase_price', '<=', $params['price2'] * 10000];
        }
        return $map;
    }

    /**
     * 添加状态筛选
     * @param $data_filter
     * @return array
     */
    private function getAddStatusQuery($data_filter)
    {
        $tree = new Tree();
        $tree->setNode(1, isset($data_filter['bhx']) ? [['car_info_t.is_export_bhx', '>', 0]] : []);
        $tree->setNode(2, isset($data_filter['none']) ? [['car_info_t.is_export_bhx', '=', 0]] : []);
        if(isset($data_filter['bhx_success'])){
            $tree->setNode(3, [[
                ['car_info_t.is_export_bhx', '>', 0],
                ['car_info_t.is_update_bhx', '>', 0],
            ]],1);
            $tree->setNode(1, [], 0);
        }else {
            $tree->setNode(3, [],1);
        }
        if(isset($data_filter['bhx_failed'])){
            $tree->setNode(4, [[
                ['car_info_t.is_export_bhx', '>', 0],
                ['car_info_t.is_update_bhx', '<', 0],
            ]],1);
            $tree->setNode(1, [], 0);
        }else {
            $tree->setNode(4, [],1);
        }
        if(isset($data_filter['bhx_none'])){
            $tree->setNode(5, [[
                ['car_info_t.is_export_bhx', '>', 0],
                ['car_info_t.is_update_bhx', '=', 0],
            ]],1);
            $tree->setNode(1, [], 0);
        }else {
            $tree->setNode(5, [],1);
        }
        if(isset($data_filter['none_bmc'])){
            $tree->setNode(6, [[
                ['car_info_t.is_export_bhx', '=', 0],
                ['car_info_t.is_export_none_bmc', '>', 0],
            ]],2);
            $tree->setNode(2, [], 0);
        }else {
            $tree->setNode(6, [],2);
        }
        if(isset($data_filter['none_none'])){
            $tree->setNode(7, [[
                ['car_info_t.is_export_bhx', '=', 0],
                ['car_info_t.is_export_none_bmc', '=', 0],
            ]],2);
            $tree->setNode(2, [], 0);
        }else {
            $tree->setNode(7, [],2);
        }
        if(isset($data_filter['bhx_success_bmc'])){
            $tree->setNode(8, [[
                ['car_info_t.is_export_bhx', '>', 0],
                ['car_info_t.is_update_bhx', '>', 0],
                ['car_info_t.is_export_bmc', '>', 0],
            ]],3);
            $tree->setNode(3, [], 0);
        }else {
            $tree->setNode(8, [],3);
        }
        if(isset($data_filter['bhx_success_none'])){
            $tree->setNode(9, [[
                ['car_info_t.is_export_bhx', '>', 0],
                ['car_info_t.is_update_bhx', '>', 0],
                ['car_info_t.is_export_bmc', '=', 0],
            ]],3);
            $tree->setNode(3, [], 0);
        }else {
            $tree->setNode(9, [],3);
        }
        if(isset($data_filter['bhx_failed_bmc'])){
            $tree->setNode(10, [[
                ['car_info_t.is_export_bhx', '>', 0],
                ['car_info_t.is_update_bhx', '<', 0],
                ['car_info_t.is_export_bmc', '=', 0],
                ['car_info_t.is_export_failed', '=', 0],
                ['car_info_t.is_export_failed_bmc', '>', 0],
            ]],4);
            $tree->setNode(4, [], 0);
        }else {
            $tree->setNode(10, [],4);
        }
        if(isset($data_filter['bhx_failed_bhx'])){
            $tree->setNode(11, [[
                ['car_info_t.is_export_bhx', '>', 0],
                ['car_info_t.is_export_bhx', '>', 0],
                ['car_info_t.is_update_bhx', '<', 0],
                ['car_info_t.is_export_bmc', '=', 0],
                ['car_info_t.is_export_failed', '>', 0],
            ]],4);
            $tree->setNode(4, [], 0);
        }else {
            $tree->setNode(11, [],4);
        }
        if(isset($data_filter['bhx_failed_none'])){
            $tree->setNode(12, [[
                ['car_info_t.is_export_bhx', '>', 0],
                ['car_info_t.is_update_bhx', '<', 0],
                ['car_info_t.is_export_bmc', '=', 0],
                ['car_info_t.is_export_failed', '=', 0],
                ['car_info_t.is_export_failed_bmc', '=', 0],
            ]],4);
            $tree->setNode(4, [], 0);
        }else {
            $tree->setNode(12, [],4);
        }

        $map = $tree->getAllChildrenNodes(0, function ($value) {
            return count($value) > 0;
        }, function ($value) {
            return $value;
        });
        return array_column(array_filter($map), null);
    }
}