<?php

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\AppointmentHistoryT;
use common\models\AppointmentT;
use common\models\Brand2T;
use common\models\BrandT;
use common\models\BusinessGroupT;
use common\models\CarBT;
use common\models\CarCT;
use common\models\CarDT;
use common\models\CarET;
use common\models\CarFT;
use common\models\CarF1T;
use common\models\CarF2T;
use common\models\CarF3T;
use common\models\CarF4T;
use common\models\CarF5T;
use common\models\CarF6T;
use common\models\CarGiftT;
use common\models\CarInvalidT;
use common\models\CarLogT;
use common\models\CarT;
use common\models\CarTypeT;
use common\models\CarUseT;
use common\models\CityT;
use common\models\DirectionT;
use common\models\Displacement2T;
use common\models\DisplacementT;
use common\models\DistrictT;
use common\models\DuanxinT;
use common\models\FactoryT;
use common\models\FinanceLogT;
use common\models\GiftGroupT;
use common\models\GiftT;
use common\models\GiftType2T;
use common\models\GiftType3T;
use common\models\InsurerCompany2T;
use common\models\MeetT;
use common\models\GiftTicketT;
use common\models\InsurerCompanyT;
use common\models\InsurerTypeT;
use common\models\InvalidT;
use common\models\LinkmanT;
use common\models\ModelT;
use common\models\OrderFinanceLogT;
use common\models\OrderGiftT;
use common\models\OrderT;
use common\models\OrderUserT;
use common\models\PayTypeT;
use common\models\PriceT;
use common\models\RangeT;
use common\models\Region;
use common\models\Series2T;
use common\models\SeriesT;
use common\models\StatusT;
use common\models\UserT;
use common\models\YearT;
use common\models\OrderCaiwuT;
use common\models\OrderAddress;
use common\models\InvalidNew;
use common\models\InvalidRenewal;
use common\models\ZhongjiGiftT;
use GuzzleHttp\Client;
use Yii;
use yii\data\Pagination;
use yii\db\Exception;
use yii\web\Request;
use yii\web\Response;

class CarController extends BaseController
{
    public $enableCsrfValidation = false;
    public $layout = 'blue-main';

    public function actionIndex()
    {
        return $this->renderPartial('index');
    }

    public function actionMycars()
    {
        $user_id = $this->my->id;

        return $this->renderPartial('mycars',[
            'user_id' => $user_id
        ]);
    }
    public function actionOutputOrder()
    {
//        set_time_limit(0);
//        $begin_time = time();
//        $file_path = \Yii::getAlias('@console').'/controllers/';
//        var_dump($row);
        //加上级别筛选

        $car_arr=array();
        $order_info=OrderT::find()->where('insurance_status=3 or insurance_status=1')->andWhere('status_id>1')->all();
        foreach($order_info as $vs){
            $car_arr[$vs->car_no]=$vs->id;
        }

//        dd(count($car_arr));
        $objectPHPExcel = new \PHPExcel();
        $index = 1;
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,'车牌号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,'厂牌型号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,'车型');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,'初登日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$index,'商业到期日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$index,'交强到期日期');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$index,'被保险人');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$index,'被保险人身份证');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$index,'发动机号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$index,'车架号');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$index,'年份');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('L'.$index,'车主');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('M'.$index,'电话');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('N'.$index,'车主身份证');
        $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('O'.$index,'保险公司');

//        $query = OrderT::find();
        foreach($car_arr as $item) {
            $order_item=OrderT::findOne($item);
            $index++;

            $car = $order_item->car;


            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('A'.$index,$order_item->car_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('B'.$index,$car->factory_model);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('C'.$index,$car->car_model);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('D'.$index,$car->register_date);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('E'.$index,$car->insurer1_date);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('F'.$index,$car->insurer2_date);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('G'.$index,$car->id_man);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('H'.$index,$car->id_man_number);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('I'.$index,$car->engine_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('J'.$index,$car->car_frame_no);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('K'.$index,$car->car_year);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('L'.$index,$car->car_man);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('M'.$index,$car->phone);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('N'.$index,$car->car_man_number);
            $objectPHPExcel->setActiveSheetIndex(0)->setCellValue('O'.$index,$car->company);

        }

        header('Content-Type: application/vnd.ms-excel;charset=utf-8');
        header('Content-Disposition:attachment;filename="'.date("YmjHis").'.xls"');
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objectPHPExcel, 'Excel5');
        $objWriter->save('php://output');
    }
    public function actionJsonData()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $user_id = $request->get('user_id',0);

        $car_man = $request->get('car_man','');
        $car_no = $request->get('car_no','');
        $engine_no = $request->get('engine_no','');
        $car_frame_no = $request->get('car_frame_no','');
        $register_begin = $request->get('register_begin','');
        $register_end = $request->get('register_end','');
        $resurer_begin = $request->get('resurer_begin','');
        $resurer_end = $request->get('resurer_end','');
        $sort = $request->get('sort','id');
        $order = $request->get('order','asc');

        $page = $request->get('page',1);
        $limit = $request->get('rows',20);

        $start = ($page-1)*$limit;

        $query = CarT::find();
        if($user_id > 0) {
            $user_items = $this->my->getChildren();
            $user_ids = array();
            if($user_items != null) {
                foreach($user_items as $user_item) {
                    $user_ids[] = $user_item->id;
                }
            }
            $user_ids[] = $this->my->id;
            $query = $query->andWhere(['in','user_id',$user_ids]);
        }
        if($car_man != '') {
            $query = $query->andWhere('car_man="'.$car_man.'"');
        }
        if($car_no != '') {
            $query = $query->andWhere('car_no="'.$car_no.'"');
        }
        if($engine_no != '') {
            $query = $query->andWhere('engine_no="'.$engine_no.'"');
        }
        if($car_frame_no != '') {
            $query = $query->andWhere('car_frame_no="'.$car_frame_no.'"');
        }
        if($register_begin != '') {
            $query = $query->andWhere('register_date>="'.$register_begin.'"');
        }
        if($register_end != '') {
            $query = $query->andWhere('register_date<="'.$register_end.'"');
        }
        $query = $query->orderBy($sort.' '.$order);
        $total = $query->count();
        $query = $query->offset($start)->limit($limit);
        $items = $query->all();
        $data = array();
        foreach($items as $item) {
            $row = array();
            $row['id'] = $item->id;
            $row['car_no'] = $item->car_no;
            $row['car_man'] = $item->car_man;
            $row['phone'] = $item->phone;
            $row['engine_no'] = $item->engine_no;
            $row['car_frame_no'] = $item->car_frame_no;
            $row['seats'] = $item->seats;
            $row['register_date'] = $item->register_date;
            $row['user'] = $item->user?$item->user->getShowName():'';
            $row['created_at'] = $item->created_at;
            $data[] = $row;
        }
        $result['total'] = $total;
        $result['rows'] = $data;
        return $result;
    }

    public function actionEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $back_params = $request->get('back_params');
        $user_id = $request->get('user_id',0);
        if($id > 0) {
            $info = CarT::findOne(['id'=>$id]);
        } else {
            $info = new CarT();
        }
        $car_use_items = CarUseT::find()->all();

        return $this->render('edit',[
            'user_id' => $user_id,
            'info' => $info,
            'car_use_items' => $car_use_items,
            'back_params' => $back_params
        ]);
    }

    public function actionSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $id = $request->post('id',0);
            $car_no = $request->post('car_no');
            $engine_no = $request->post('engine_no');
            $car_frame_no = $request->post('car_frame_no');
            $factory_model = $request->post('factory_model');
            $seats = $request->post('seats');
            $car_use_id = $request->post('car_use_id');
            $register_date = $request->post('register_date');
            $car_man = $request->post('car_man');
            $car_man_type = $request->post('car_man_type');
            $car_man_phone = $request->post('car_man_phone');
            $car_man_number = $request->post('car_man_number');
            $purchase_price = $request->post('purchase_price');
            $remark = $request->post('remark');

            if($car_no == '') {
                $result['msg'] = '请输入车牌号码!';
                return $result;
            }

            $row = null;
            if($id > 0) {
                $row = CarT::findOne(['id'=>$id]);
            } else {
                $row = new CarT();
                $row->user_id = 0;
                $row->location = 1;
            }
            //去除首位空格和字符串中间的空格
            $car_no= trim($car_no);
            $car_no=str_replace(" ","",$car_no);
            
            $row->car_no = $car_no;
            $row->engine_no = $engine_no;
            $row->car_frame_no = $car_frame_no;
            $row->factory_model = $factory_model;
            $row->car_model = $factory_model;
            $row->seats = $seats;
            $row->purchase_price = $purchase_price;
            $row->car_use_id = $car_use_id;
            $row->register_date = $register_date;
            $row->car_man = $car_man;
            $row->car_man_phone = $car_man_phone;
            $row->car_man_number = $car_man_number;
            $row->remark = $remark;
            $row->car_man_type = $car_man_type;
            if(!$row->save()) {
                $result['msg'] = print_r($row->getErrors(), true);
                return $result;
            }

            $result['success'] = true;
            $result['msg'] = '保存成功';
        }
        return $result;
    }

    public function actionDelete()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '删除失败';

        if($request->isPost) {
            $id = $request->post('id',0);

            $tran = CarT::getDb()->beginTransaction();
            try {
                $ids = $request->post('ids',array());

                if($id > 0) {
                    $car_info = CarT::findOne(['id'=>$id]);
                    if($car_info->location != 1) {
                        $result['msg'] = '该车辆必须先回到A库，才能删除';
                        return $result;
                    }
                    //删除预约信息
                    AppointmentT::deleteAll('car_id='.$id);
                    AppointmentHistoryT::deleteAll('car_id='.$id);

                    //删除保单信息
                    $items = OrderT::find()
                        ->where('car_id='.$id)
                        ->all();
                    foreach ($items as $item) {
                        PriceT::deleteAll(['order_id'=>$item->id]);
                        $item->delete();
                    }

                    //删除B、C、D库数据
                    if($car_info->location == 2)
                        CarBT::deleteAll('id='.$car_info->id);
                    if($car_info->location == 3)
                        CarCT::deleteAll('id='.$car_info->id);
                    if($car_info->location == 4)
                        CarDT::deleteAll('id='.$car_info->id);
                    $car_info->delete();

                    //清除操作记录
                    $this->removeLog($id);
                }

                $tran->commit();
                $result['success'] = true;
                $result['msg'] = '删除成功';

            } catch(\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }

    public function actionDeleteAll()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '删除失败';

        if($request->isPost) {
            $tran = CarT::getDb()->beginTransaction();
            try {
                $ids = $request->post('ids',array());

                foreach($ids as $id) {
                    if($id > 0) {
                        $row = CarT::findOne(['id'=>$id]);
                        AppointmentT::deleteAll('car_id='.$id);
                        AppointmentHistoryT::deleteAll('car_id='.$id);
                        $items = OrderT::find()
                            ->where('car_id='.$id)
                            ->all();
                        foreach ($items as $item) {
                            PriceT::deleteAll(['order_id'=>$item->id]);
                            $item->delete();
                        }

                        $row->delete();
                    }
                }

                $tran->commit();
                $result['success'] = true;
                $result['msg'] = '删除成功';

            } catch(\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        }
        return $result;
    }

    public function actionAppointment()
    {
        $request = Yii::$app->request;
        $car_id = $request->get('car_id');
        return $this->renderPartial('appointment',[
            'car_id' => $car_id
        ]);
    }

    public function actionAppointmentJsonData()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $car_id = $request->get('car_id');
        $car_info = CarT::findOne(['id'=>$car_id]);

        $page = $request->get('page',1);
        $limit = $request->get('rows',20);

        $start = ($page-1)*$limit;

        $query = $car_info->getAppointments()
            ->orderBy('pdate DESC,ptime ASC,id DESC');
        $total = $query->count();
        $query = $query->offset($start)->limit($limit);
        $items = $query->all();
        $data = array();
        foreach($items as $item) {
            $row = array();
            $row['id'] = $item->id;
            $row['pdate'] = $item->pdate;
            $row['ptime'] = $item->ptime;
            $row['remark'] = $item->remark;
            $row['user'] = $item->user?$item->user->getShowName():'';
            $data[] = $row;
        }
        $result['total'] = $total;
        $result['rows'] = $data;
        return $result;
    }

    public function actionInsurer()
    {
        $request = Yii::$app->request;
        $car_id = $request->get('car_id');
        return $this->renderPartial('insurer',[
            'car_id' => $car_id
        ]);
    }

    public function actionBaocun()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost){
            $car_id = $request->post('car_id');
            $insurer1_date = $request->post('insurer1_date');
            $insurer2_date = $request->post('insurer2_date');
            $company = $request->post('company');

            $order = CarT::findOne(['id'=>$car_id]);
            $order->insurer1_date = $insurer1_date;
            $order->insurer2_date = $insurer2_date;
            $order->company = $company;
            $order->save();

            //操作日志
            $this->addLog($car_id,'操作了商业止保，交强止保，保险公司',1);

            $result['success'] = true;
            $result['msg'] = '保存成功';
        }
        return $result;
    }

    public function actionBihuSearch()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $car_info = CarT::findOne(['id'=>$id]);
        if($car_info) {
            $url = Yii::$app->params['userPanel']['search_car_url'];
            $token = Yii::$app->params['userPanel']['token'];
            $params = [
                'token' => $token,
                'LicenseNo' => $car_info->car_no,
                'EngineNo' => $car_info->engine_no,
                'CarVin' => $car_info->car_frame_no,
                'RegisterDate' => $car_info->register_date,
            ];
            if($car_info->car_man_number != '' && substr($car_info->car_man_number, -6) != '') {
                $params['SixDigitsAfterIdCard'] = substr($car_info->car_man_number, -6);
            }
            $client = new Client(['timeout'=> 120]);
            $res = $client->request('POST', $url, [
                'form_params' => $params,
                'http_errors' => false,
            ]);
            if($res->getStatusCode() == 200) {
                $obj = json_decode($res->getBody());
                return MyLib::ok3($obj);
            }
            return MyLib::error3($res->getBody());
        }
        return MyLib::error3('车辆信息不存在');
    }

    public function actionBihuCarinfo()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $car_info = CarT::findOne(['id'=>$id]);
        if($car_info) {
            $url = Yii::$app->params['userPanel']['car_info_url'];
            $token = Yii::$app->params['userPanel']['token'];
            $params = [
                'token' => $token,
                'LicenseNo' => $car_info->car_no,
                'EngineNo' => $car_info->engine_no,
                'CarVin' => $car_info->car_frame_no,
            ];
            $client = new Client(['timeout'=> 120]);
            $res = $client->request('POST', $url, [
                'form_params' => $params,
                'http_errors' => false,
            ]);
            if($res->getStatusCode() == 200) {
                $obj = json_decode($res->getBody());
                if($obj->code == 200) {
                    if($obj->data && $obj->data->UserInfo && $obj->data->UserInfo->CarUsedType != '') {
                        $car_user_info = CarUseT::find()->where(['name'=>$obj->data->UserInfo->CarUsedType])->one();
                        if($car_user_info) {
                            $obj->data->UserInfo->CarUsedType = $car_user_info->id;
                        }
                    }
                    return MyLib::ok3($obj->data);
                } else {
                    return MyLib::error3($obj->msg);
                }
            }
            return MyLib::error3($res->getBody());
        }
        return MyLib::error3('车辆信息不存在');
    }

    public function actionPostPrecisePrice()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $url = Yii::$app->params['userPanel']['post-precise-price'];
        $token = Yii::$app->params['userPanel']['token'];
        $types = $request->post('types');
        $nopays = $request->post('nopays');
        $params = [
            'token' => $token,
            'LicenseNo' => $request->post('car_no'),
            'CarOwnersName' => $request->post('car_man'),
            'IdCard' => strtoupper($request->post('car_man_number')),
            'OwnerIdCardType' => $request->post('car_man_type'), //
            'QuoteGroup' => $request->post('company_id'), //
            'InsuredName' => $request->post('id_man'),
            'InsuredIdCard' => strtoupper($request->post('id_man_number')),
            'InsuredIdType' => $request->post('id_man_type'), //
            'HolderIdCard' => strtoupper($request->post('link_man_number')),
            'HolderName' => $request->post('link_man'),
            'HolderIdType' => $request->post('link_man_type'), //
            'CarUsedType' => $request->post('car_use_id'),
            'EngineNo' => strtoupper($request->post('engine_no')),
            'CarVin' => strtoupper($request->post('car_frame_no')),
            'RegisterDate' => $request->post('register_date'),
            'MoldName' => $request->post('factory_model'),
            'ForceTax' => 1,
            'BizTimeStamp' => $request->post('insurer1_begin_date'),
            'ForceTimeStamp' => $request->post('insurer2_begin_date'),
            'BoLi' => 0,
            'BuJiMianCheSun' => isset($nopays[1])?1:0,
            'BuJiMianDaoQiang' => isset($nopays[3])?1:0,
            'BuJiMianSanZhe' => isset($nopays[2])?1:0,
            'BuJiMianChengKe' => isset($nopays[5])?1:0,
            'BuJiMianSiJi' => isset($nopays[4])?1:0,
            'BuJiMianHuaHen' => isset($nopays[7])?1:0,
            'BuJiMianSheShui' => isset($nopays[8])?1:0,
            'BuJiMianZiRan' => isset($nopays[9])?1:0,
            'SheShui' => $types[8]=='是'?1:0,
            'HuaHen' => $types[7],
            'SiJi' => $types[4],
            'ChengKe' => $types[5],
            'CheSun' => floatval($types[1]),
            'DaoQiang' => $types[3]=='是'?1:0,
            'SanZhe' => $types[2],
            'ZiRan' => $types[9]=='是'?1:0,
            'SeatCount' => $request->post('seats'),
            'HcSanFangTeYue' => $types[12]=='是'?1:0,
            'PurchasePrice' => $request->post('purchase_price'),
            'AutoMoldCode' => $request->post('auto_mold_code'),
            'VehicleYear' => $request->post('vehicle_year'),
            'AutoMoldCodeSource' => 3,
        ];
        if($params['QuoteGroup'] == 0) {
            return MyLib::error3('请选择保险公司');
        }
        if($params['CarUsedType'] == 0) {
            return MyLib::error3('请选择车辆使用性质');
        }
        if($params['OwnerIdCardType'] == '身份证') $params['OwnerIdCardType'] = 1;
        else $params['OwnerIdCardType'] = 9;
        if($params['InsuredIdType'] == '身份证') $params['InsuredIdType'] = 1;
        else $params['InsuredIdType'] = 9;
        if($params['HolderIdType'] == '身份证') $params['HolderIdType'] = 1;
        else $params['HolderIdType'] = 9;

        $min_chesun = floatval($request->post('min_chesun'));
        $max_chesun = floatval($request->post('max_chesun'));
        if($params['CheSun'] > 0 && $min_chesun > 0 && $max_chesun > 0 && ($params['CheSun'] < $min_chesun || $params['CheSun'] > $max_chesun)) {
            return MyLib::error3('车损只能填写：'.$min_chesun.' ~ '.$max_chesun.' 之间的值');
        }
        if($params['CheSun'] > 0 && $types[10] == '是' && $types[11] == '是') {
            $params['ForceTax'] = 1;
        }
        if($params['CheSun'] == 0 && $types[10] == '是' && $types[11] == '是') {
            $params['ForceTax'] = 2;
        }
        if($params['CheSun'] > 0 && $types[10] == '否' && $types[11] == '否') {
            $params['ForceTax'] = 0;
        }
        if($types[6] == '国产') {
            $params['BoLi'] = 1;
        }
        if($types[6] == '进口') {
            $params['BoLi'] = 2;
        }
        switch($types[7]) {
            case '2000元':
                $params['HuaHen'] = 2000;
                break;
            case '5000元':
                $params['HuaHen'] = 5000;
                break;
            case '10000元':
                $params['HuaHen'] = 10000;
                break;
            case '20000元':
                $params['HuaHen'] = 20000;
                break;
            default:
                $params['HuaHen'] = 0;
        }
        switch($types[4]) {
            case '1万':
                $params['SiJi'] = 10000;
                break;
            case '2万':
                $params['SiJi'] = 20000;
                break;
            case '3万':
                $params['SiJi'] = 30000;
                break;
            case '4万':
                $params['SiJi'] = 40000;
                break;
            case '5万':
                $params['SiJi'] = 50000;
                break;
            case '10万':
                $params['SiJi'] = 100000;
                break;
            default:
                $params['SiJi'] = 0;
        }
        switch($types[5]) {
            case '1万':
                $params['ChengKe'] = 10000;
                break;
            case '2万':
                $params['ChengKe'] = 20000;
                break;
            case '3万':
                $params['ChengKe'] = 30000;
                break;
            case '4万':
                $params['ChengKe'] = 40000;
                break;
            case '5万':
                $params['ChengKe'] = 50000;
                break;
            case '10万':
                $params['ChengKe'] = 100000;
                break;
            default:
                $params['ChengKe'] = 0;
        }
        switch($types[2]) {
            case '5万':
                $params['SanZhe'] = 50000;
                break;
            case '10万':
                $params['SanZhe'] = 100000;
                break;
            case '15万':
                $params['SanZhe'] = 150000;
                break;
            case '20万':
                $params['SanZhe'] = 200000;
                break;
            case '30万':
                $params['SanZhe'] = 300000;
                break;
            case '50万':
                $params['SanZhe'] = 500000;
                break;
            case '100万':
                $params['SanZhe'] = 1000000;
                break;
            case '150万':
                $params['SanZhe'] = 1500000;
                break;
            case '200万':
                $params['SanZhe'] = 2000000;
                break;
            default:
                $params['SanZhe'] = 0;
        }
        $client = new Client(['timeout'=> 120]);
        $res = $client->request('POST', $url, [
            'form_params' => $params,
            'http_errors' => false,
        ]);
        if($res->getStatusCode() == 200) {
            $obj = json_decode($res->getBody());
            if($obj->code == 200) {
                if($obj->data && $obj->data->UserInfo && $obj->data->UserInfo->CarUsedType != '') {
                    $car_user_info = CarUseT::find()->where(['name'=>$obj->data->UserInfo->CarUsedType])->one();
                    if($car_user_info) {
                        $obj->data->UserInfo->CarUsedType = $car_user_info->id;
                    }
                }
                return MyLib::ok3($obj->data);
            } else {
                return MyLib::error3($obj->msg);
            }
        }
        return MyLib::error3($res->getBody());
    }

    public function actionGetPrecisePrice()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $url = Yii::$app->params['userPanel']['get-precise-price'];
        $token = Yii::$app->params['userPanel']['token'];
        $params = [
            'token' => $token,
            'LicenseNo' => $request->post('car_no'),
            'QuoteGroup' => $request->post('company_id'),
        ];
        $client = new Client(['timeout'=> 120]);
        $res = $client->request('POST', $url, [
            'form_params' => $params,
            'http_errors' => false,
        ]);
//        echo $url;
//        var_dump($params);
//        echo $res->getBody();
//        exit;
        if($res->getStatusCode() == 200) {
            $obj = json_decode($res->getBody());
            if($obj->code == 200) {
                if($obj->data && $obj->data->UserInfo && $obj->data->UserInfo->CarUsedType != '') {
                    $car_user_info = CarUseT::find()->where(['name'=>$obj->data->UserInfo->CarUsedType])->one();
                    if($car_user_info) {
                        $obj->data->UserInfo->CarUsedType = $car_user_info->id;
                    }
                }
                return MyLib::ok3($obj->data);
            } else {
                return MyLib::error3($obj->msg);
            }
        }
        return MyLib::error3($res->getBody());
    }

    public function actionInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);

        $car_info = CarT::findOne(['id'=>$id]);

        $order_info = $car_info->getOrders()->orderBy('id DESC')->one();
        if(!$order_info) {
            $user_id = 0;
            if($car_info->location == 2) {
                $b_info = CarBT::findOne(['id'=>$car_info->id]);
                $user_id = $b_info->user_id;
            }
            if($car_info->location == 3) {
                $c_info = CarCT::findOne(['id'=>$car_info->id]);
                $user_id = $c_info->user_id;
            }
            if($car_info->location == 4) {
                $d_info = CarDT::findOne(['id'=>$car_info->id]);
                $user_id = $d_info->user_id;
            }
            $order_info = new OrderT();
            $order_info->car_id = $car_info->id;
            $order_info->car_no = $car_info->car_no;
            $order_info->engine_no = $car_info->engine_no;
            $order_info->car_frame_no = $car_info->car_frame_no;
            $order_info->car_man = $car_info->car_man;
            $order_info->user_id = $user_id;
            $order_info->status_id = 1;
            $order_info->id_man = $car_info->car_man;
            $order_info->link_man = $car_info->car_man;
            $order_info->link_phone = $car_info->phone;
            $order_info->save();
        }
        $linkMan_items = $car_info->getLinkmen()
            ->orderBy('created_at desc')
            ->all();

        return $this->render('info',[
            'user_id' => $this->my->id,
            'car_info' => $car_info,
            'link_men' => $linkMan_items,
            'order_info' => $order_info,
        ]);
    }
    /*
* 获取地区
*/
    public function actionGetRegion(){
        $request = Yii::$app->request;
        $parent_id =$request->get('parent_id');
        $selected =$request->get('selected',0);
        $data =  Region::find()->where("parent_id=".$parent_id)->asArray()->all();
        $html = '';
        if($data){
            foreach($data as $h){
                if($h['id'] == $selected){
                    $html .= "<option value='{$h['id']}' selected>{$h['name']}</option>";
                }
                $html .= "<option value='{$h['id']}'>{$h['name']}</option>";
            }
        }
        echo $html;
    }


    public function actionGetTown(){

        $request = Yii::$app->request;
        $parent_id =$request->get('parent_id');
        $data =  Region::find()->where("parent_id=".$parent_id)->asArray()->all();
//        $data = M('region')->where("parent_id",$parent_id)->select();
        $html = '';
        if($data){
            foreach($data as $h){
                $html .= "<option value='{$h['id']}'>{$h['name']}</option>";
            }
        }
        if(empty($html)){
            echo '0';
        }else{
            echo $html;
        }
    }
    public function actionInfoView()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $type = $request->get('type',0);
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $page = $request->get('page',1);
        $sort_key = $request->get('sort_key','appointment_t.pdate');
        $sort_value = $request->get('sort_value','ASC');
        $next_index = $request->get('next_index',0);

        $car_info = CarT::findOne(['id'=>$id]);
        $failure_items = InvalidT::getTree(2);

        //礼品
        $gift_items = CarGiftT::find()
            ->where('car_id='.$car_info->id)
            ->orderBy('strategy_id DESC')
            ->all();

        //下一辆
        $next_id = 0;
        if($type == 1) {
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=1 and car_t.is_track=1')
                ->andWhere('appointment_t.pdate<="'.date('Y-m-d').'"');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }
        if($type == 2) {
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=0 and car_t.is_track=1')
                ->andWhere('appointment_t.pdate<="'.date('Y-m-d').'"');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }
        if($type == 3) {
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=0 and car_t.is_track=1');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }
        return $this->render('info-view',[
            'type' => $type,
            'car_info' => $car_info,
            'failure_items' => $failure_items,
            'next_id' => $next_id,
            'next_index' => $next_index,
            'car_man' => $car_man,
            'car_no' => $car_no,
            'phone' => $phone,
            'page' => $page,
            'sort_key' => $sort_key,
            'sort_value' => $sort_value,
            'gift_items' => $gift_items
        ]);
    }

    public function actionInfoTrack() {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        // 车辆信息
        $car_info = CarT::findOne(['id'=>$id]);

        return $this->render('info-track',[
            'car_info' => $car_info
        ]);
    }

    public function actionInfoTrackJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $type = $request->get('type',0);
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $page = $request->get('page',1);
        $sort_key = $request->get('sort_key','appointment_t.pdate');
        $sort_value = $request->get('sort_value','ASC');
        $next_index = $request->get('next_index',0);
        $back_params = $request->get('back_params');

        // 车辆信息
        $car_info = CarT::findOne(['id'=>$id]);
        // 运营性质
        $car_use_items = CarUseT::find()->all();
        // 车辆类型
        $car_type_items = CarTypeT::find()->all();
        // 无效数据
        $failure_items = InvalidT::getTrees();

        //新礼品
        $query = GiftTicketT::find()
            ->orderBy('id DESC');
        $items = $query->andWhere('car_no like "'.$car_info->car_no.'"')->all();

        //旧礼品
        $gift_items = CarGiftT::find()
            ->where('car_id='.$car_info->id)
            ->orderBy('strategy_id DESC')
            ->all();

        //下一辆
        $next_id = 0;
        if($type == 1) { // 首发 预约时间小于当前
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=1 and car_t.is_track=1')
                ->andWhere('appointment_t.pdate<="'.date('Y-m-d').'"');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }
        if($type == 2) { // 历史 预约时间小于当前
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=0 and car_t.is_track=1')
                ->andWhere('appointment_t.pdate<="'.date('Y-m-d').'"');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }

        if($type == 3) { // 历史 预约时间不限
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=0 and car_t.is_track=1');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }

        $list = MeetT::getAllData(2);

        //登陆用户ID
        $uid = $this->my->role_id;
        $aid = $this->my->id;

        //获取业务分组
        $business_group = BusinessGroupT::find()->all();

        return MyLib::ok3([
            'type' => $type,
            'car_info' => $car_info,
            'failure_info' => $failure_items,
            'next_id' => $next_id,
            'appointment_type'  => $list,
            'new_gift_info' => $items,
            'old_gift_info' => $gift_items,
            'uid' => $uid,
            'next_index' => $next_index,
            'car_man' => $car_man,
            'car_no' => $car_no,
            'phone' => $phone,
            'page' => $page,
            'sort_key' => $sort_key,
            'sort_value' => $sort_value,
            'car_use_items' => $car_use_items,
            'car_type_items' => $car_type_items,
            'back_params' => $back_params,
            'business_group' => $business_group,
            'adid' => $aid,
        ]);
    }

    public function actionInfoTrackFix()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $type = $request->get('type',0);
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $page = $request->get('page',1);
        $sort_key = $request->get('sort_key','appointment_t.pdate');
        $sort_value = $request->get('sort_value','ASC');
        $next_index = $request->get('next_index',0);
        $back_params = $request->get('back_params');

        $car_info = CarT::findOne(['id'=>$id]);

        $car_use_items = CarUseT::find()->all();
        $car_type_items = CarTypeT::find()->all();
        $failure_items = InvalidT::getTree(2);

        //新礼品
        $query = GiftTicketT::find()
            ->orderBy('id DESC');
        $items = $query->andWhere('car_no like "'.$car_info->car_no.'"')->all();

        //旧礼品
        $gift_items = CarGiftT::find()
            ->where('car_id='.$car_info->id)
            ->orderBy('strategy_id DESC')
            ->all();

        //下一辆
        $next_id = 0;
        if($type == 1) {
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=1 and car_t.is_track=1')
                ->andWhere('appointment_t.pdate<="'.date('Y-m-d').'"');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }
        if($type == 2) {
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=0 and car_t.is_track=1')
                ->andWhere('appointment_t.pdate<="'.date('Y-m-d').'"');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }
        if($type == 3) {
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=0 and car_t.is_track=1');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }

        $list = MeetT::getAllData(2);

        //登陆用户ID
        $uid = $this->my->role_id;

        //获取业务分组
        $business_group = BusinessGroupT::find()->all();

        $business_group_id = $this->my->business_group_id;

        return $this->render('info-track-fix',[
            'type' => $type,
            'car_info' => $car_info,
            'failure_items' => $failure_items,
            'next_id' => $next_id,
            'list'  => $list,
            'items' => $items,
            'gift_items' => $gift_items,
            'uid' => $uid,
            'next_index' => $next_index,
            'car_man' => $car_man,
            'car_no' => $car_no,
            'phone' => $phone,
            'page' => $page,
            'sort_key' => $sort_key,
            'sort_value' => $sort_value,
            'car_use_items' => $car_use_items,
            'car_type_items' => $car_type_items,
            'back_params' => $back_params,
            'business_group' => $business_group,
            'business_group_id' => $business_group_id,
        ]);
    }

    public function actionInfoRenewal()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $type = $request->get('type',0);
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $page = $request->get('page',1);
        $sort_key = $request->get('sort_key','appointment_t.pdate');
        $sort_value = $request->get('sort_value','ASC');
        $next_index = $request->get('next_index',0);
        $back_params = $request->get('back_params');
        $my_path = $this->my->group?$this->my->group->getPath():'';

        $car_info = CarT::findOne(['id'=>$id]);
        $order_info = $car_info->getOrders()->orderBy('id DESC')->one();
        if(!$order_info) {
            $user_id = 0;
            if($car_info->location == 2) {
                $b_info = CarBT::findOne(['id'=>$car_info->id]);
                $user_id = $b_info->user_id;
            }
            if($car_info->location == 3) {
                $c_info = CarCT::findOne(['id'=>$car_info->id]);
                $user_id = $c_info->user_id;
            }
            if($car_info->location == 4) {
                $d_info = CarDT::findOne(['id'=>$car_info->id]);
                $user_id = $d_info->user_id;
            }
            $order_info = new OrderT();
            $order_info->car_id = $car_info->id;
            $order_info->car_no = $car_info->car_no;
            $order_info->engine_no = $car_info->engine_no;
            $order_info->car_frame_no = $car_info->car_frame_no;
            $order_info->car_man = $car_info->car_man;
            $order_info->user_id = $user_id;
            $order_info->status_id = 1;
            $order_info->id_man = $car_info->car_man;
            $order_info->link_man = $car_info->car_man;
            $order_info->link_phone = $car_info->phone;
            $order_info->save();
        }
        $insurer_type_items = InsurerTypeT::find()->all();
        $insurer_company_items = InsurerCompanyT::find()->all();
        $insurer_company2_items = InsurerCompany2T::find()->all();
        $pay_type_items = PayTypeT::find()->all();
        $car_use_items = CarUseT::find()->all();
        $car_type_items = CarTypeT::find()->all();
        $direction_items = DirectionT::find()
            ->all();
        $range_items = RangeT::find()
            ->all();
        $city_items = CityT::find()
            ->all();
        $district_items = DistrictT::find()
            ->orderBy('order_id ASC')
            ->all();
        $gift_items = GiftT::find()
            ->where('type_id=1')
            ->all();
        $success_items = InvalidT::getTree(1);
        $failure_items = InvalidT::getTreeXubao(2);

        //下一辆
        $next_id = 0;
        if($type == 1) {
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=1 and car_t.location=4')
                ->andWhere('appointment_t.pdate<="'.date('Y-m-d').'"');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }
        if($type == 2) {
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=0 and car_t.location=4')
                ->andWhere('appointment_t.pdate<="'.date('Y-m-d').'"');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }
        if($type == 3) {
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=0 and car_t.location=4');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }
        if($type == 4) {
            $query = OrderT::find()
                ->where('status_id=1 and return_status_id>0')
                ->orderBy('submit_date DESC, id DESC');
            $user_items = $this->my->getChildren();
            $user_ids[] = $this->my->id;
            if($user_items) {
                foreach($user_items as $user_item) {
                    $user_ids[] = $user_item->id;
                }
            }
            $query = $query->andWhere(['in','user_id',$user_ids]);
            if($car_man != '') {
                $query = $query->andWhere('car_man="'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('link_phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_no="'.$car_no.'"');
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }

//        $gift_type_items = GiftType2T::find()->all();
        $gift_group_items = GiftGroupT::find()
            ->where('is_free=0')
            ->all();
        $gift_free_group_items = GiftGroupT::find()
            ->where('is_free=1')
            ->all();
        //获取礼品数据
        $sel_gifts = array();
        $tmp_items = OrderGiftT::find()
            ->where('order_id='.$order_info->id)
            ->all();
        foreach($tmp_items as $item) {
            $sel_gifts[$item->group_id] = $item;
        }

        $list = MeetT::getAllData(1);

        $business_group = BusinessGroupT::find()->all();
        $order_ad=OrderAddress::findOne(['id'=>$order_info->addr_id]);
        $province = Region::find()->asArray()->where(['parent_id'=>0])->andWhere(['level'=>1])->all();
//        if($order_ad){
//            $c = Region::find()->asArray()->where(['parent_id'=>$order_ad->province])->andWhere(['level'=>2])->all();
//            $d = Region::find()->asArray()->where(['parent_id'=>$order_ad->city,'level'=>3])->all();
//            $e = Region::find()->asArray()->where(['parent_id'=>$order_ad->district,'level'=>4])->all();
//
//        }else{
//            $c = Region::find()->asArray()->andWhere(['level'=>2])->all();
//            $d = Region::find()->asArray()->where(['level'=>3])->all();
//            $e = Region::find()->asArray()->where(['level'=>4])->all();
//        }
        $c=[];
        $d=[];
        $e=[];
//        if($order_ad){
//            $c = Region::find()->asArray()->where(['parent_id'=>$order_ad->province])->andWhere(['level'=>2])->all();
//            $d = Region::find()->asArray()->where(['parent_id'=>$order_ad->city,'level'=>3])->all();
//            $e = Region::find()->asArray()->where(['parent_id'=>$order_ad->district,'level'=>4])->all();
//
//        }else{
//            $c = Region::find()->asArray()->andWhere(['level'=>2])->all();
//            $d = Region::find()->asArray()->where(['level'=>3])->all();
//            $e = Region::find()->asArray()->where(['level'=>4])->all();
//        }

        return $this->render('info-renewal',[
            'type' => $type,
            'car_info' => $car_info,
            'insurer_type_items' => $insurer_type_items,
            'order_info' => $order_info,
            'insurer_company_items' => $insurer_company_items,
            'insurer_company2_items' => $insurer_company2_items,
            'pay_type_items' => $pay_type_items,
            'car_use_items' => $car_use_items,
            'car_type_items' => $car_type_items,
            'direction_items' => $direction_items,
            'range_items' => $range_items,
            'city_items' => $city_items,
            'district_items' => $district_items,
            'gift_items' => $gift_items,
            'success_items' => $success_items,
            'failure_items' => $failure_items,
            'next_id' => $next_id,
            'list'  => $list,
            'next_index' => $next_index,
            'car_man' => $car_man,
            'car_no' => $car_no,
            'phone' => $phone,
            'page' => $page,
            'sort_key' => $sort_key,
            'sort_value' => $sort_value,
            'back_params' => $back_params,
//            'gift_type_items' => $gift_type_items,
            'gift_group_items' => $gift_group_items,
            'gift_free_group_items' => $gift_free_group_items,
            'sel_gifts' => $sel_gifts,
            'my_path' => $my_path,
            'business_group' => $business_group,
            'business_group_id' => $this->my->business_group_id,
            'province' => $province,
            'city' =>$c,
            'district' =>$d,
//            'address' =>$address,
            'twon' =>isset($e)?$e:[],
            'order_ad' =>isset($order_ad)?$order_ad:[],
        ]);
    }
    public function actionNonInfoRenewal()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $type = $request->get('type',0);
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $page = $request->get('page',1);
        $sort_key = $request->get('sort_key','appointment_t.pdate');
        $sort_value = $request->get('sort_value','ASC');
        $next_index = $request->get('next_index',0);
        $back_params = $request->get('back_params');
        $my_path = $this->my->group?$this->my->group->getPath():'';

        $car_info = CarT::findOne(['id'=>$id]);
        $order_info = $car_info->getOrders()->orderBy('id DESC')->one();
        if(!$order_info) {
            $user_id = 0;
            if($car_info->location == 2) {
                $b_info = CarBT::findOne(['id'=>$car_info->id]);
                $user_id = $b_info->user_id;
            }
            if($car_info->location == 3) {
                $c_info = CarCT::findOne(['id'=>$car_info->id]);
                $user_id = $c_info->user_id;
            }
            if($car_info->location == 4) {
                $d_info = CarDT::findOne(['id'=>$car_info->id]);
                $user_id = $d_info->user_id;
            }
            $order_info = new OrderT();
            $order_info->car_id = $car_info->id;
            $order_info->car_no = $car_info->car_no;
            $order_info->engine_no = $car_info->engine_no;
            $order_info->car_frame_no = $car_info->car_frame_no;
            $order_info->car_man = $car_info->car_man;
            $order_info->user_id = $user_id;
            $order_info->status_id = 1;
            $order_info->id_man = $car_info->car_man;
            $order_info->link_man = $car_info->car_man;
            $order_info->link_phone = $car_info->phone;
            $order_info->save();
        }
        $insurer_type_items = InsurerTypeT::find()->all();
        $insurer_company_items = InsurerCompanyT::find()->all();
        $insurer_company2_items = InsurerCompany2T::find()->all();
        $pay_type_items = PayTypeT::find()->all();
        $car_use_items = CarUseT::find()->all();
        $car_type_items = CarTypeT::find()->all();
        $direction_items = DirectionT::find()
            ->all();
        $range_items = RangeT::find()
            ->all();
        $city_items = CityT::find()
            ->all();
        $district_items = DistrictT::find()
            ->orderBy('order_id ASC')
            ->all();
        $gift_items = GiftT::find()
            ->where('type_id=1')
            ->all();
        $success_items = InvalidT::getTree(1);
        $failure_items = InvalidT::getTreeXubao(2);

        //下一辆
        $next_id = 0;
        if($type == 1) {
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=1 and car_t.location=4')
                ->andWhere('appointment_t.pdate<="'.date('Y-m-d').'"');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }
        if($type == 2) {
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=0 and car_t.location=4')
                ->andWhere('appointment_t.pdate<="'.date('Y-m-d').'"');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }
        if($type == 3) {
            $query = AppointmentT::find()
                ->leftJoin('car_t','`car_t`.`id`=`appointment_t`.`car_id`')
                ->where('appointment_t.is_first=0 and car_t.location=4');

            $user_ids = $this->getChildrenUserIDs();
            $query = $query->andWhere(['in','appointment_t.user_id',$user_ids]);

            if($car_man != '') {
                $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('car_t.phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
            }
            if($sort_key != '') {
                $query = $query->orderBy($sort_key.' '.$sort_value);
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }
        if($type == 4) {
            $query = OrderT::find()
                ->where('status_id=1 and return_status_id>0')
                ->orderBy('submit_date DESC, id DESC');
            $user_items = $this->my->getChildren();
            $user_ids[] = $this->my->id;
            if($user_items) {
                foreach($user_items as $user_item) {
                    $user_ids[] = $user_item->id;
                }
            }
            $query = $query->andWhere(['in','user_id',$user_ids]);
            if($car_man != '') {
                $query = $query->andWhere('car_man="'.$car_man.'"');
            }
            if($phone != '') {
                $query = $query->andWhere('link_phone="'.$phone.'"');
            }
            if($car_no != '') {
                $query = $query->andWhere('car_no="'.$car_no.'"');
            }
            $next_item = $query->offset($next_index)->one();
            if($next_item) {
                $next_id = $next_item->car_id;
            }
            $next_index++;
        }

//        $gift_type_items = GiftType2T::find()->all();
        $gift_group_items = GiftGroupT::find()
            ->where('is_free=0')
            ->all();
        $gift_free_group_items = GiftGroupT::find()
            ->where('is_free=1')
            ->all();
        //获取礼品数据
        $sel_gifts = array();
        $tmp_items = OrderGiftT::find()
            ->where('order_id='.$order_info->id)
            ->all();
        foreach($tmp_items as $item) {
            $sel_gifts[$item->group_id] = $item;
        }

        $list = MeetT::getAllData(1);

        $business_group = BusinessGroupT::find()->all();
        $order_ad=OrderAddress::findOne(['id'=>$order_info->addr_id]);
        $province = Region::find()->asArray()->where(['parent_id'=>0])->andWhere(['level'=>1])->all();
        if($order_ad){
            $c = Region::find()->asArray()->where(['parent_id'=>$order_ad->province])->andWhere(['level'=>2])->all();
            $d = Region::find()->asArray()->where(['parent_id'=>$order_ad->city,'level'=>3])->all();
            $e = Region::find()->asArray()->where(['parent_id'=>$order_ad->district,'level'=>4])->all();

        }else{
            $c = Region::find()->asArray()->andWhere(['level'=>2])->all();
            $d = Region::find()->asArray()->where(['level'=>3])->all();
            $e = Region::find()->asArray()->where(['level'=>4])->all();
        }

        return $this->render('non-info-renewal',[
            'type' => $type,
            'car_info' => $car_info,
            'insurer_type_items' => $insurer_type_items,
            'order_info' => $order_info,
            'insurer_company_items' => $insurer_company_items,
            'insurer_company2_items' => $insurer_company2_items,
            'pay_type_items' => $pay_type_items,
            'car_use_items' => $car_use_items,
            'car_type_items' => $car_type_items,
            'direction_items' => $direction_items,
            'range_items' => $range_items,
            'city_items' => $city_items,
            'district_items' => $district_items,
            'gift_items' => $gift_items,
            'success_items' => $success_items,
            'failure_items' => $failure_items,
            'next_id' => $next_id,
            'list'  => $list,
            'next_index' => $next_index,
            'car_man' => $car_man,
            'car_no' => $car_no,
            'phone' => $phone,
            'page' => $page,
            'sort_key' => $sort_key,
            'sort_value' => $sort_value,
            'back_params' => $back_params,
//            'gift_type_items' => $gift_type_items,
            'gift_group_items' => $gift_group_items,
            'gift_free_group_items' => $gift_free_group_items,
            'sel_gifts' => $sel_gifts,
            'my_path' => $my_path,
            'business_group' => $business_group,
            'business_group_id' => $this->my->business_group_id,
            'province' => $province,
            'city' =>$c,
            'district' =>$d,
//            'address' =>$address,
            'twon' =>isset($e)?$e:[],
            'order_ad' =>isset($order_ad)?$order_ad:[],
        ]);
    }
    public function actionInfoEdit()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $info = CarT::findOne(['id'=>$id]);

        $car_use_items = CarUseT::find()->all();
        $car_type_items = CarTypeT::find()->all();

        return $this->render('info-edit',[
            'info' => $info,
            'car_use_items' => $car_use_items,
            'car_type_items' => $car_type_items,
        ]);
    }

    public function actionFactories()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $brand_id = $request->get('brand_id',0);

        $factories = FactoryT::find()
            ->where('brand_id='.$brand_id)
            ->all();
        $html = '<option value="0">---请选择---</option>';
        foreach($factories as $factory) {
            $html .= '<option value='.$factory->id.'>'.$factory->name.'</option>';
        }
        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }

    public function actionSeries()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $factory_id = $request->get('factory_id',0);

        $series = Series2T::find()
            ->where('factory_id='.$factory_id)
            ->all();
        $html = '<option value="0">---请选择---</option>';
        foreach($series as $series_info) {
            $html .= '<option value='.$series_info->id.'>'.$series_info->name.'</option>';
        }
        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }

    public function actionSeriesFix()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $brand_id = $request->get('brand_id',0);

        $series = SeriesT::find()
            ->where('brand_id='.$brand_id)
            ->all();
        $html = '<option value="0">---请选择---</option>';
        foreach($series as $series_info) {
            $html .= '<option value='.$series_info->id.'>'.$series_info->name.'</option>';
        }
        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }

    public function actionDisplacements()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $series_id = $request->get('series_id',0);

        $query = Displacement2T::find()
            ->where('series_id='.$series_id);
        $items = $query->all();
        $html = '<option value="0">---请选择---</option>';
        foreach($items as $item) {
            $html .= '<option value='.$item->id.'>'.$item->name.'</option>';
        }
        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }

    public function actionDisplacementsFix()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $series_id = $request->get('series_id',0);

        $query = DisplacementT::find()
            ->where('series_id='.$series_id);
        $items = $query->all();
        $html = '<option value="0">---请选择---</option>';
        foreach($items as $item) {
            $html .= '<option value='.$item->id.'>'.$item->name.'</option>';
        }
        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }

    public function actionYears()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $series_id = $request->get('series_id',0);
        $displacement_id = $request->get('displacement_id',0);

        $query = YearT::find()
            ->where('series_id='.$series_id.' and displacement_id='.$displacement_id);
        $items = $query->all();
        $html = '<option value="0">---请选择---</option>';
        foreach($items as $item) {
            $html .= '<option value='.$item->id.'>'.$item->name.'</option>';
        }
        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }

    public function actionModelsbak()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $series_id = $request->get('series_id',0);
        $displacement_id = $request->get('displacement_id',0);
        $year_id = $request->get('year_id',0);

        $query = ModelT::find()
            ->where('series_id='.$series_id.' and displacement_id='.$displacement_id.' and year_id='.$year_id);
        $items = $query->all();
        $html = '<option value="0">---请选择---</option>';
        foreach($items as $item) {
            $html .= '<option value='.$item->id.'>'.$item->name.'</option>';
        }
        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }

    public function actionModels()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $factory_id = $request->get('factory_id',0);

        $query = ModelT::find()
            ->where('factory_id='.$factory_id);
        $items = $query->all();
        $html = '<option value="0">---请选择---</option>';
        foreach($items as $item) {
            $html .= '<option value='.$item->id.'>'.$item->name.'</option>';
        }
        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }

    //保单信息保存
    public function actionOrderSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';
        if ($request->isPost) {
            //状态
            $status_id = $request->post('status_id', 1);
            //车辆信息
            $car_id = $request->post('car_id', 0);
            $car_no = $request->post('car_no');
            $seats = (int)$request->post('seats');
            $register_date = $request->post('register_date');
            $car_use_id = $request->post('car_use_id');
            $purchase_price = $request->post('purchase_price');
            $car_frame_no = $request->post('car_frame_no');
            $engine_no = $request->post('engine_no');
            $factory_model = $request->post('factory_model');

            //策略信息
            $celuo_id = $request->post('celuo_id');
            $fanxian_id = $request->post('fanxian_id');
            $gift_ids = $request->post('gift_ids', []);
            $quan_ids = $request->post('quan_ids', []);

            //投保信息
            $car_man = $request->post('car_man');
            $car_man_number = $request->post('car_man_number');
            $car_man_type = $request->post('car_man_type');
            $car_man_phone = $request->post('car_man_phone');
            $id_man = $request->post('id_man');
            $id_man_number = $request->post('id_man_number');
            $id_man_type = $request->post('id_man_type');
            $id_man_phone = $request->post('id_man_phone');
            $link_man = $request->post('link_man');
            $link_man_number = $request->post('link_man_number');
            $link_man_type = $request->post('link_man_type');
            $link_man_phone = $request->post('link_man_phone');
            $pay_type_id = $request->post('pay_type_id');

            //送单地址信息
            $send_district_id = $request->post('send_district_id');
            $send_city_id = $request->post('send_city_id');
            $send_address = $request->post('send_address');

            //保单信息
            $order_id = $request->post('id', 0);
            $email = $request->post('email');
            $company_id = $request->post('company_id');
            $insurer1_begin_date = $request->post('insurer1_begin_date');
            $insurer2_begin_date = $request->post('insurer2_begin_date');
            $order_remark = $request->post('order_remark');

            //报价信息
            $total1_clear = $request->post('total1_clear');
            $total1 = $request->post('total1');
            $total1_real = $request->post('total1_real');
            $total1_dis = $request->post('total1_dis');
            $total1_percent = $request->post('total1_percent');
            $total2_clear = $request->post('total2_clear');
            $total2 = $request->post('total2');
            $total3 = $request->post('total3');
            $total_all = $request->post('total_all');
            $total_real = $request->post('total_real');
            $price_remark = $request->post('price_remark');
            $yuangong_money = $request->post('yuangong_money');

            //报价明细
            $types = $request->post('types', array());
            $nopays = $request->post('nopays', array());

            //财务信息条件
            $money_man = $request->post('money_man');
            $money_no = $request->post('money_no');
            $money_bank = $request->post('money_bank');

            //判断起保日期是否正确
            $begin_date = date('Y-m-d', strtotime('+90 day'));
            if ($insurer1_begin_date != '' && $insurer1_begin_date > $begin_date) {
                $result['msg'] = '商业起保日期不正确!';
                return $result;
            }
            if ($insurer2_begin_date != '' && $insurer2_begin_date > $begin_date) {
                $result['msg'] = '交强起保日期不正确!';
                return $result;
            }
            //提交才判断的条件
            if ($status_id > 1) {
                if ($seats == 0) {
                    $result['msg'] = '请输入座位数';
                    return $result;
                }
            }

            $tran = CarT::getDb()->beginTransaction();
            try {
                $order_info = OrderT::findOne(['id' => $order_id]);
                $car_info = $order_info->car;
                //车辆信息
                $car_info->car_no = $car_no;
                $car_info->seats = $seats;
                $car_info->register_date = $register_date;
                $car_info->car_man = $car_man;

                $car_info->car_man_number = $car_man_number;
                $car_info->car_use_id = $car_use_id;
                $car_info->engine_no = $engine_no;
                $car_info->car_frame_no = $car_frame_no;
                $car_info->factory_model = $factory_model;
                $car_info->purchase_price = $purchase_price;
                if(!$car_info->save()) {
                    throw new \Exception(print_r($car_info->getErrors(), true));
                }

                //保单信息
                $order_info->car_no = $car_no;
                $order_info->seats = $seats;
                $order_info->engine_no = $engine_no;
                $order_info->car_frame_no = $car_frame_no;
                $order_info->factory_model = $factory_model;
                $order_info->purchase_price = $purchase_price;
                $order_info->car_man = $car_man;
                $order_info->car_man_phone = $car_man_phone;
                $order_info->car_man_type = $car_man_type;
                $order_info->car_man_number = $car_man_number;
                $order_info->id_man = $id_man;
                $order_info->id_man_phone = $id_man_phone;
                $order_info->id_man_type = $id_man_type;
                $order_info->id_man_number = $id_man_number;
                $order_info->link_man = $link_man;
                $order_info->link_man_phone = $link_man_phone;
                $order_info->link_man_type = $link_man_type;
                $order_info->link_man_number = $link_man_number;

                $order_info->company_id = $company_id;
                $order_info->status_id = $status_id;
                $order_info->return_status_id = 0;
                $order_info->submit_date = date('Y-m-d');
                //商业保险日期
                $order_info->insurer1_begin_date = $insurer1_begin_date;
                $insurer1_end_date = '';
                if ($insurer1_begin_date != '') {
                    $insurer1_end_date = date('Y-m-d', strtotime(date('Y-m-d', strtotime($insurer1_begin_date . "+1 year")) . '-1 day'));
                }
                $order_info->insurer1_end_date = $insurer1_end_date;
                //交强保险日期
                $order_info->insurer2_begin_date = $insurer2_begin_date;
                $insurer2_end_date = '';
                if ($insurer2_begin_date != '')
                    $insurer2_end_date = date('Y-m-d', strtotime(date('Y-m-d', strtotime($insurer2_begin_date . "+1 year")) . '-1 day'));
                $order_info->insurer2_end_date = $insurer2_end_date;

                $order_info->send_district_id = $send_district_id;
                $order_info->send_city_id = $send_city_id;
                $order_info->send_address = $send_address;
                $order_info->email = $email;
                $order_info->remark = $order_remark;

                $order_info->total1_clear = $total1_clear;
                $order_info->total1 = $total1;
                $order_info->total1_real = $total1_real;
                $order_info->total1_dis = $total1_dis;
                $order_info->total1_percent = $total1_percent;
                $order_info->total2_clear = $total2_clear;
                $order_info->total2 = $total2;
                $order_info->total3 = $total3;
                $order_info->total_all = $total_all;
                $order_info->total_real = $total_real;
                $order_info->price_remark = $price_remark;
                $order_info->yuangong_money = $yuangong_money;
                $order_info->pay_type_id = $pay_type_id;

                $order_info->money_man = $money_man;
                $order_info->money_bank = $money_bank;
                $order_info->money_no = $money_no;

                $order_info->celuo_id = $celuo_id;
                $order_info->fanxian_id = $fanxian_id;

                if(!$order_info->save()) {
                    throw new \Exception(print_r($order_info->getErrors(), true));
                }

                //处理操作人员状态 0：正在操作中，1：操作结束，2：退回操作，3：无效操作，4:放弃操作
                if ($status_id > 1) {
                    $order_user_info = OrderUserT::findOne(['user_id' => $this->my->id, 'order_id' => $order_info->id, 'status' => 0]);
                    if ($order_user_info) {
                        $order_user_info->status = 1;
                        if(!$order_user_info->save()) {
                            throw new \Exception(print_r($order_user_info->getErrors(), true));
                        }
                    }
                }
                //险种明细
                foreach ($types as $id => $val) {
                    $price_row = PriceT::find()
                        ->where('order_id=' . $order_info->id . ' and type_id=' . $id)
                        ->one();
                    if (empty($price_row)) {
                        $price_row = new PriceT();
                        $price_row->order_id = $order_info->id;
                        $price_row->type_id = $id;
                    }
                    $price_row->val = $val;
                    if (!empty($nopays[$id]))
                        $price_row->is_nopay = 1;
                    else
                        $price_row->is_nopay = 0;
                    if(!$price_row->save()) {
                        throw new \Exception(print_r($price_row->getErrors(), true));
                    }
                }

                //处理预约
                $result['msg'] = '保存成功';
                if ($status_id > 1) {
                    $tmp_row = AppointmentT::findOne(['car_id' => $car_info->id]);
                    if($tmp_row) {
                        $tmp_row->delete();
                    }
                    $tmp_status_info = StatusT::findOne(['id' => $status_id]);
                    $log_msg = '';
                    if ($tmp_status_info) {
                        $log_msg = '进入' . $tmp_status_info->name;
                    }
                    $this->addLog($car_info->id, $log_msg, 1);
                    $result['msg'] = '提交成功';
                }
                // 处理财务-如果是在线支付-生成财务分支-返现记录
                if ($status_id > 1) {
                    $order_caiwu = OrderCaiwuT::findOne(['order_id'=>$order_info->id]);

                    if(!$order_caiwu){
                        $order_caiwu = new OrderCaiwuT();
                        $order_caiwu->status_id = 2;
                    }

                    $order_caiwu->order_id = $order_info->id;
                    $order_caiwu->money_man = $money_man;
                    $order_caiwu->money_no = $money_no;
                    $order_caiwu->money_bank = $money_bank;
                    if(!$order_caiwu->save()) {
                        throw new \Exception(print_r($order_caiwu->getErrors(), true));
                    }
                }

                //处理策略
                $gift_counts = [];
                OrderGiftT::deleteAll('order_id=' . $order_info->id . ' and status=0');
                //礼品
                foreach($gift_ids as $gift_str) {
                    $tmp = explode('-', $gift_str);
                    $zhongjigift_item = ZhongjiGiftT::findOne(['id'=>$tmp[0]]);
                    $gift_id = $tmp[1];
                    $gift_item = GiftT::findOne(['id'=>$gift_id]);
                    if($zhongjigift_item && $gift_item) {
                        $row = new OrderGiftT();
                        $row->order_id = $order_info->id;
                        $row->group_id = 0;
                        $row->gift_id = $gift_id;
                        $row->is_free = $zhongjigift_item->free_type;
                        $row->gift_type = $zhongjigift_item->gift_type;
                        $row->send_id = 0;
                        $row->send_time = 0;
                        $row->price = $gift_item->price;
                        $row->status = 0;
                        if (!$row->save()) {
                            throw new \Exception(print_r($row->getErrors(), true));
                        }
                        if(!isset($gift_counts[$zhongjigift_item->id])) {
                            $gift_counts[$zhongjigift_item->id] = 1;
                        } else {
                            $gift_counts[$zhongjigift_item->id] += 1;
                        }
                        if($gift_counts[$zhongjigift_item->id] > $zhongjigift_item->n) {
                            $result['msg'] = '礼品数量超限，请重新选择';
                            return $result;
                        }
                    }
                }
                //礼券
                foreach($quan_ids as $gift_str) {
                    $tmp = explode('-', $gift_str);
                    $zhongjigift_item = ZhongjiGiftT::findOne(['id'=>$tmp[0]]);
                    $gift_id = $tmp[1];
                    $gift_item = GiftT::findOne(['id'=>$gift_id]);
                    if($zhongjigift_item && $gift_item) {
                        $row = new OrderGiftT();
                        $row->order_id = $order_info->id;
                        $row->group_id = 0;
                        $row->gift_id = $gift_id;
                        $row->is_free = $zhongjigift_item->free_type;
                        $row->gift_type = $zhongjigift_item->gift_type;
                        $row->send_id = 0;
                        $row->send_time = 0;
                        $row->price = $gift_item->price;
                        $row->status = 0;
                        if (!$row->save()) {
                            throw new \Exception(print_r($row->getErrors(), true));
                        }
                        if(!isset($gift_counts[$zhongjigift_item->id])) {
                            $gift_counts[$zhongjigift_item->id] = 1;
                        } else {
                            $gift_counts[$zhongjigift_item->id] += 1;
                        }
                        if($gift_counts[$zhongjigift_item->id] > $zhongjigift_item->n) {
                            $result['msg'] = '礼券数量超限，请重新选择';
                            return $result;
                        }
                    }
                }

                $result['success'] = true;

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }

    public function actionAjaxHistoryIndex()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $car_id = $request->get('car_id');
        $page = $request->get('page',1);

        $result = array();
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $query = CarLogT::find()
            ->where(['car_id'=>$car_id,'type'=>1])
            ->andWhere('op_time>='.strtotime("-6 months"))
            ->orderBy('op_time DESC');

        $total = $query->count();

        $pagination = new Pagination(['totalCount' => $total,'pageSize'=>20]);
        $pagination->setPage($page-1);

        $query = $query->offset($pagination->offset)->limit($pagination->limit);
        $items = $query->all();

        $page_info = MyLib::getAjaxPageInfo($pagination,'car_history_list');
        $html = $this->renderPartial('ajax-history-index',[
            'car_id' => $car_id,
            'items' => $items,
            'page' => $page,
            'page_info' => $page_info
        ]);
        $result['success'] = true;
        $result['msg'] = '读取成功';
        $result['html'] = $html;
        return $result;
    }
    public function actionAjaxHistoryIndexXubao()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $car_id = $request->get('car_id');
        $page = $request->get('page',1);

        $result = array();
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $query = CarLogT::find()
            ->where(['car_id'=>$car_id,'type'=>1])
//            ->andWhere('op_time>='.strtotime("-6 months"))
            ->orderBy('op_time DESC');

        $total = $query->count();

        $pagination = new Pagination(['totalCount' => $total,'pageSize'=>20]);
        $pagination->setPage($page-1);

        $query = $query->offset($pagination->offset)->limit($pagination->limit);
        $items = $query->all();

        $page_info = MyLib::getAjaxPageInfo($pagination,'car_history_list');
        $html = $this->renderPartial('ajax-history-index',[
            'car_id' => $car_id,
            'items' => $items,
            'page' => $page,
            'page_info' => $page_info
        ]);
        $result['success'] = true;
        $result['msg'] = '读取成功';
        $result['html'] = $html;
        return $result;
    }

    public function actionAjaxHistoryFinance()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $car_id = $request->get('car_id');
        $page = $request->get('page',1);

        $result = array();
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $query = OrderFinanceLogT::find()
            ->where(['car_id'=>$car_id,'type'=>1])
            ->orderBy('id DESC');

        $total = $query->count();

        $pagination = new Pagination(['totalCount' => $total,'pageSize'=>20]);
        $pagination->setPage($page-1);

        $query = $query->offset($pagination->offset)->limit($pagination->limit);
        $items = $query->all();

        $page_info = MyLib::getAjaxPageInfo($pagination,'car_history_list');
        $html = $this->renderPartial('ajax-history-index',[
            'car_id' => $car_id,
            'items' => $items,
            'page' => $page,
            'page_info' => $page_info
        ]);
        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }

//    public function actionInvalid()
//    {
//        Yii::$app->response->format = Response::FORMAT_JSON;
//        $request = Yii::$app->request;
//        $result = array();
//        $result['success'] = false;
//        $result['msg'] = '操作失败';
//
//        if($request->isPost) {
//            $car_id = $request->post('car_id');
//            $invalid_id = $request->post('invalid_id',0);
//
//            $tran = CarT::getDb()->beginTransaction();
//            try {
//                $car_info = CarT::findOne(['id'=>$car_id]);
//                if($invalid_id == 26) {
////                    $car_info->location = 6;
////                    $car_info->save();
////
////                    CarCT::deleteAll('id='.$car_info->id);
////                    $c_info = new CarET();
////                    $c_info->id = $car_info->id;
////                    $c_info->user_id = 0;
////                    $c_info->save();
////
////                    CarBT::deleteAll(['id'=>$car_info->id]);
////                    CarDT::deleteAll(['id'=>$car_info->id]);
////
////                    //删除预约
////                    AppointmentT::deleteAll('car_id='.$car_info->id);
////
////                    //删除保单
////                    $orders = OrderT::find()
////                        ->where('car_id='.$car_info->id.' and status_id<2')
////                        ->all();
////                    foreach($orders as $order_info) {
////                        OrderUserT::deleteAll('order_id='.$order_info->id);
////                        $order_info->delete();
////                    }
////                    $orders = OrderT::find()
////                        ->where('car_id='.$car_info->id.' and status_id>1')
////                        ->all();
////                    foreach($orders as $order_info) {
////                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
////                        if($order_user_info) {
////                            $order_user_info->status = 3;
////                            $order_user_info->save();
////                        }
////                    }
////
////                    $this->addLog($car_info->id,'已在其他人保公司续保车辆数据，进入E库',1);
//
//                } else {
//                    $car_info->location = 5;
//                    $car_info->save();
//
//                    CarInvalidT::deleteAll('id='.$car_info->id);
//                    $invalid_info = new CarInvalidT();
//                    $invalid_info->id = $car_info->id;
//                    $invalid_info->invalid_id = $invalid_id;
//                    $invalid_info->user_id = $this->my->id;
//                    $invalid_info->save();
//
//                    CarBT::deleteAll(['id'=>$car_info->id]);
//                    CarCT::deleteAll(['id'=>$car_info->id]);
//                    CarDT::deleteAll(['id'=>$car_info->id]);
//
//                    //删除预约
//                    AppointmentT::deleteAll('car_id='.$car_info->id);
//
//                    //删除保单
//                    $orders = OrderT::find()
//                        ->where('car_id='.$car_info->id.' and status_id<2')
//                        ->all();
//                    foreach($orders as $order_info) {
//                        OrderUserT::deleteAll('order_id='.$order_info->id);
//                        $order_info->delete();
//                    }
//                    $orders = OrderT::find()
//                        ->where('car_id='.$car_info->id.' and status_id>1')
//                        ->all();
//                    foreach($orders as $order_info) {
//                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
//                        if($order_user_info) {
//                            $order_user_info->status = 3;
//                            $order_user_info->save();
//                        }
//                    }
//
//                    $this->addLog($car_info->id,'无效车辆数据:'.$invalid_info->invalid->name,1);
//
//                }
//
//                $result['success'] = true;
//                $result['msg'] = '操作成功';
//
//                $tran->commit();
//            } catch (\Exception $e) {
//                $tran->rollBack();
//                throw $e;
//            }
//        }
//        return $result;
//    }
//    //无效数据到A库
//    public function actionInvalidA()
//    {
//        Yii::$app->response->format = Response::FORMAT_JSON;
//        $request = Yii::$app->request;
//        $result = array();
//        $result['success'] = false;
//        $result['msg'] = '操作失败';
//
//        if($request->isPost) {
////            var_dump($request->post());
////            die;
//            $car_id = $request->post('car_id');
//            $invalid_id = $request->post('invalid_id',0);
//            $ac1 = $request->post('ac1');
//            $ac2 = $request->post('ac2');
//            $ac3 = $request->post('ac3');
//
//            $tran = CarT::getDb()->beginTransaction();
//            try {
//                $car_info = CarT::findOne(['id'=>$car_id]);
//                if($invalid_id == 25 || $invalid_id == 26 || $invalid_id == 27 ) {
//                    $car_info->location = 6;
//
//                    $car_info->insurer1_date = $ac1;
//                    $car_info->insurer2_date = $ac2;
//                    $car_info->company = $ac3;
//                    $car_info->save();
//
//                    CarCT::deleteAll('id='.$car_info->id);
//                    $c_info = new CarET();
//                    $c_info->id = $car_info->id;
//                    $c_info->user_id = 0;
//                    $c_info->save();
//
//                    CarBT::deleteAll(['id'=>$car_info->id]);
//                    CarDT::deleteAll(['id'=>$car_info->id]);
//
//                    //删除预约
//                    AppointmentT::deleteAll('car_id='.$car_info->id);
//                    AppointmentHistoryT::deleteAll('car_id='.$car_info->id);
//
//                    //删除保单
//                    $orders = OrderT::find()
//                        ->where('car_id='.$car_info->id.' and status_id<2')
//                        ->all();
//                    foreach($orders as $order_info) {
//                        OrderUserT::deleteAll('order_id='.$order_info->id);
//                        $order_info->delete();
//                    }
//                    $orders = OrderT::find()
//                        ->where('car_id='.$car_info->id.' and status_id>1')
//                        ->all();
//                    foreach($orders as $order_info) {
//                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
//                        if($order_user_info) {
//                            $order_user_info->status = 3;
//                            $order_user_info->save();
//                        }
//                    }
//
//                    $this->addLog($car_info->id,'新保销售预约时,已在其他人保公司续保车辆数据或在人保公司续保，进入E库',1);
//
//                } else {
//                    $car_info->location = 5;
//                    $car_info->save();
//
//                    CarInvalidT::deleteAll('id='.$car_info->id);
//                    $invalid_info = new CarInvalidT();
//                    $invalid_info->id = $car_info->id;
//                    $invalid_info->invalid_id = $invalid_id;
//                    $invalid_info->user_id = $this->my->id;
//                    $invalid_info->save();
//
//                    CarBT::deleteAll(['id'=>$car_info->id]);
//                    CarCT::deleteAll(['id'=>$car_info->id]);
//                    CarDT::deleteAll(['id'=>$car_info->id]);
//
//                    //删除预约
//                    AppointmentT::deleteAll('car_id='.$car_info->id);
//
//                    //删除保单
//                    $orders = OrderT::find()
//                        ->where('car_id='.$car_info->id.' and status_id<2')
//                        ->all();
//                    foreach($orders as $order_info) {
//                        OrderUserT::deleteAll('order_id='.$order_info->id);
//                        $order_info->delete();
//                    }
//                    $orders = OrderT::find()
//                        ->where('car_id='.$car_info->id.' and status_id>1')
//                        ->all();
//                    foreach($orders as $order_info) {
//                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
//                        if($order_user_info) {
//                            $order_user_info->status = 3;
//                            $order_user_info->save();
//                        }
//                    }
//
//                    $this->addLog($car_info->id,'无效车辆数据:'.$invalid_info->invalid->name,1);
//
//                }
//
//                $result['success'] = true;
//                $result['msg'] = '操作成功';
//
//                $tran->commit();
//            } catch (\Exception $e) {
//                $tran->rollBack();
//                throw $e;
//            }
//        }
//        return $result;
//    }
//    //无效数据到F库
//    public function actionInvalidF()
//    {
//        Yii::$app->response->format = Response::FORMAT_JSON;
//        $request = Yii::$app->request;
//        $result = array();
//        $result['success'] = false;
//        $result['msg'] = '操作失败';
//
//        if($request->isPost) {
//            $car_id = $request->post('car_id');
//            $invalid_id = $request->post('invalid_id',0);
//            $ac1 = $request->post('ac1');
//            $ac2 = $request->post('ac2');
//            $ac3 = $request->post('ac3');
//
//            $tran = CarT::getDb()->beginTransaction();
//            try {
//                $car_info = CarT::findOne(['id'=>$car_id]);
//                if($invalid_id == 25 || $invalid_id == 26 || $invalid_id == 27 ) {
//                    $car_info->location = 7;
//                    $car_info->insurer1_date = $ac1;
//                    $car_info->insurer2_date = $ac2;
//                    $car_info->company = $ac3;
//                    $car_info->save();
//
//
//                    CarCT::deleteAll('id='.$car_info->id);
//                    $c_info = new CarFT();
//                    $c_info->id = $car_info->id;
//                    $c_info->user_id = 0;
//                    $c_info->save();
//
//                    CarBT::deleteAll(['id'=>$car_info->id]);
//                    CarDT::deleteAll(['id'=>$car_info->id]);
//
//                    //删除预约
//                    AppointmentT::deleteAll('car_id='.$car_info->id);
//                    AppointmentHistoryT::deleteAll('car_id='.$car_info->id);
//
//                    //删除保单
//                    $orders = OrderT::find()
//                        ->where('car_id='.$car_info->id.' and status_id<2')
//                        ->all();
//                    foreach($orders as $order_info) {
//                        OrderUserT::deleteAll('order_id='.$order_info->id);
//                        $order_info->delete();
//                    }
//                    $orders = OrderT::find()
//                        ->where('car_id='.$car_info->id.' and status_id>1')
//                        ->all();
//                    foreach($orders as $order_info) {
//                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
//                        if($order_user_info) {
//                            $order_user_info->status = 3;
//                            $order_user_info->save();
//                        }
//                    }
//
//                    $this->addLog($car_info->id,'续保销售预约时,已在其他人保公司续保车辆数据或在人保公司续保，进入F库',1);
//
//                } else {
//                    $car_info->location = 5;
//                    $car_info->save();
//
//                    CarInvalidT::deleteAll('id='.$car_info->id);
//                    $invalid_info = new CarInvalidT();
//                    $invalid_info->id = $car_info->id;
//                    $invalid_info->invalid_id = $invalid_id;
//                    $invalid_info->user_id = $this->my->id;
//                    $invalid_info->save();
//
//                    CarBT::deleteAll(['id'=>$car_info->id]);
//                    CarCT::deleteAll(['id'=>$car_info->id]);
//                    CarDT::deleteAll(['id'=>$car_info->id]);
//
//                    //删除预约
//                    AppointmentT::deleteAll('car_id='.$car_info->id);
//
//                    //删除保单
//                    $orders = OrderT::find()
//                        ->where('car_id='.$car_info->id.' and status_id<2')
//                        ->all();
//                    foreach($orders as $order_info) {
//                        OrderUserT::deleteAll('order_id='.$order_info->id);
//                        $order_info->delete();
//                    }
//                    $orders = OrderT::find()
//                        ->where('car_id='.$car_info->id.' and status_id>1')
//                        ->all();
//                    foreach($orders as $order_info) {
//                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
//                        if($order_user_info) {
//                            $order_user_info->status = 3;
//                            $order_user_info->save();
//                        }
//                    }
//
//                    $this->addLog($car_info->id,'无效车辆数据:'.$invalid_info->invalid->name,1);
//
//                }
//
//                $result['success'] = true;
//                $result['msg'] = '操作成功';
//
//                $tran->commit();
//            } catch (\Exception $e) {
//                $tran->rollBack();
//                throw $e;
//            }
//        }
//        return $result;
//    }

    public function actionInvalid()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $car_id = $request->post('car_id');
            $invalid_id = $request->post('invalid_id',0);

            $tran = CarT::getDb()->beginTransaction();
            try {
                $car_info = CarT::findOne(['id'=>$car_id]);
                if($invalid_id == 26) {
//                    $car_info->location = 6;
//                    $car_info->save();
//
//                    CarCT::deleteAll('id='.$car_info->id);
//                    $c_info = new CarET();
//                    $c_info->id = $car_info->id;
//                    $c_info->user_id = 0;
//                    $c_info->save();
//
//                    CarBT::deleteAll(['id'=>$car_info->id]);
//                    CarDT::deleteAll(['id'=>$car_info->id]);
//
//                    //删除预约
//                    AppointmentT::deleteAll('car_id='.$car_info->id);
//
//                    //删除保单
//                    $orders = OrderT::find()
//                        ->where('car_id='.$car_info->id.' and status_id<2')
//                        ->all();
//                    foreach($orders as $order_info) {
//                        OrderUserT::deleteAll('order_id='.$order_info->id);
//                        $order_info->delete();
//                    }
//                    $orders = OrderT::find()
//                        ->where('car_id='.$car_info->id.' and status_id>1')
//                        ->all();
//                    foreach($orders as $order_info) {
//                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
//                        if($order_user_info) {
//                            $order_user_info->status = 3;
//                            $order_user_info->save();
//                        }
//                    }
//
//                    $this->addLog($car_info->id,'已在其他人保公司续保车辆数据，进入E库',1);

                } else {
                    $car_info->location = 5;
                    $car_info->save();

                    CarF6T::deleteAll('id='.$car_info->id);
                    $invalid_info = new CarF6T();
                    $invalid_info->id = $car_info->id;
                    $invalid_info->invalid_id = $invalid_id;
                    $invalid_info->user_id = $this->my->id;
                    $invalid_info->save();

                    CarBT::deleteAll(['id'=>$car_info->id]);
                    CarCT::deleteAll(['id'=>$car_info->id]);
                    CarDT::deleteAll(['id'=>$car_info->id]);

                    //删除预约
                    AppointmentT::deleteAll('car_id='.$car_info->id);

                    //删除保单
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id<2')
                        ->all();
                    foreach($orders as $order_info) {
                        OrderUserT::deleteAll('order_id='.$order_info->id);
                        $order_info->delete();
                    }
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id>1')
                        ->all();
                    foreach($orders as $order_info) {
                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
                        if($order_user_info) {
                            $order_user_info->status = 3;
                            $order_user_info->save();
                        }
                    }

                    $this->addLog($car_info->id,'无效车辆数据:'.$invalid_info->invalid->name,1);

                }

                $result['success'] = true;
                $result['msg'] = '操作成功';

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        }
        return $result;
    }

    //无效数据到A库
    public function actionInvalidA()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
//            var_dump($request->post());
//            die;
            $car_id = $request->post('car_id');
            $invalid_id = $request->post('invalid_id',0);
            $ac1 = $request->post('ac1');
            $ac2 = $request->post('ac2');
            $ac3 = $request->post('ac3');

            $tran = CarT::getDb()->beginTransaction();
            try {
                $car_info = CarT::findOne(['id'=>$car_id]);
                if($invalid_id == 25 || $invalid_id == 26 || $invalid_id == 27 ) {
                    $car_info->location = 6;

                    $car_info->insurer1_date = $ac1;
                    $car_info->insurer2_date = $ac2;
                    $car_info->company = $ac3;
                    $car_info->save();

                    CarCT::deleteAll('id='.$car_info->id);
                    $c_info = new CarET();
                    $c_info->id = $car_info->id;
                    $c_info->user_id = 0;
                    $c_info->save();

                    CarBT::deleteAll(['id'=>$car_info->id]);
                    CarDT::deleteAll(['id'=>$car_info->id]);

                    //删除预约
                    AppointmentT::deleteAll('car_id='.$car_info->id);
                    AppointmentHistoryT::deleteAll('car_id='.$car_info->id);

                    //删除保单
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id<2')
                        ->all();
                    foreach($orders as $order_info) {
                        OrderUserT::deleteAll('order_id='.$order_info->id);
                        $order_info->delete();
                    }
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id>1')
                        ->all();
                    foreach($orders as $order_info) {
                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
                        if($order_user_info) {
                            $order_user_info->status = 3;
                            $order_user_info->save();
                        }
                    }

                    $this->addLog($car_info->id,'新保销售预约时,已在其他人保公司续保车辆数据或在人保公司续保，进入E库',1);

                } else {
                    $car_info->location = 5;
                    $car_info->save();

                    CarInvalidT::deleteAll('id='.$car_info->id);
                    $invalid_info = new CarInvalidT();
                    $invalid_info->id = $car_info->id;
                    $invalid_info->invalid_id = $invalid_id;
                    $invalid_info->user_id = $this->my->id;
                    $invalid_info->save();

                    CarBT::deleteAll(['id'=>$car_info->id]);
                    CarCT::deleteAll(['id'=>$car_info->id]);
                    CarDT::deleteAll(['id'=>$car_info->id]);

                    //删除预约
                    AppointmentT::deleteAll('car_id='.$car_info->id);

                    //删除保单
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id<2')
                        ->all();
                    foreach($orders as $order_info) {
                        OrderUserT::deleteAll('order_id='.$order_info->id);
                        $order_info->delete();
                    }
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id>1')
                        ->all();
                    foreach($orders as $order_info) {
                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
                        if($order_user_info) {
                            $order_user_info->status = 3;
                            $order_user_info->save();
                        }
                    }

                    $this->addLog($car_info->id,'无效车辆数据:'.$invalid_info->invalid->name,1);

                }

                $result['success'] = true;
                $result['msg'] = '操作成功';

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        }
        return $result;
    }
    //无效数据到管路员
    public function actionInvalidMan()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $car_id = $request->post('car_id');
            $invalid_id = $request->post('invalid_id',0);
            $ac1 = $request->post('ac1');
            $ac2 = $request->post('ac2');
//            $ac3 = $request->post('ac3');

            $tran = CarT::getDb()->beginTransaction();
            try {
                $car_info = CarT::findOne(['id'=>$car_id]);
                //修改总库的数据
                if($invalid_id == 25 || $invalid_id == 27 || $invalid_id == 26 || $invalid_id ==34 || $invalid_id ==35 || $invalid_id ==36) {
                    $car_info->insurer1_date=$ac1;
                    $car_info->insurer2_date=$ac2;
//                    $car_info->company = $ac3;
                }
                $car_info->save();

                //无效给管理员 -存储一个中间表
                $cdt= CarDT::find()->where('id='.$car_info->id)->one();

                $apto=AppointmentT::find()->where('car_id='.$car_info->id)
                    ->andWhere('user_id ='.$cdt->user_id)->orderBy('id desc')->one();

                //删除重复提交的人员
                $Invalids = InvalidRenewal::find()
                    ->where('user_id= '.$cdt->user_id)
                    ->all();

                foreach($Invalids as $info) {
                    $info->delete();
                }
                //删除保单
                $orders = OrderT::find()
                    ->where('car_id='.$car_info->id.' and status_id<2')
                    ->all();
                foreach($orders as $order_info) {
                    OrderUserT::deleteAll('order_id='.$order_info->id);
                    $order_info->delete();
                }

                $renewal= new InvalidRenewal();
                $renewal->car_id=$car_id;
                $renewal->car_no=$car_info->car_no;
                if($invalid_id == 25 || $invalid_id == 27 || $invalid_id == 26 || $invalid_id ==34 || $invalid_id ==35 || $invalid_id ==36) {
                    $renewal->insurer1_date=$ac1;
                    $renewal->insurer2_date=$ac2;
                }else{
                    $renewal->insurer1_date=$car_info->insurer1_date;
                    $renewal->insurer2_date=$car_info->insurer2_date;
                }
                $renewal->phone=$car_info->phone;
                $renewal->xdate= $apto?$apto->xdate:'';
                $renewal->invalid_id= $invalid_id;
                $renewal->num= 1;
                $renewal->user_id= $cdt->user_id;
                $renewal->save();
//                dd( $renewal->save());
                //d 库的user_id 改为0 收回状态
                $car_dinfo = CarDT::findOne(['id'=>$car_id]);
                $car_dinfo->user_id=0;
                $car_dinfo->back=1;
                $car_dinfo->iv_d=$invalid_id;
                $car_dinfo->save();
                $this->addLog($car_info->id,'续保销售预约时,无效给管理员进行管理',1);
                //删除预约
                AppointmentT::deleteAll('car_id='.$car_info->id);

                $result['success'] = true;
                $result['msg'] = '操作成功';

                $tran->commit();

            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }

        }

        return $result;

    }
    public function actionInvalidNewMan()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $car_id = $request->post('car_id');
            $invalid_id = $request->post('invalid_id',0);
            $ac1 = $request->post('ac1');
            $ac2 = $request->post('ac2');
//            $ac3 = $request->post('ac3');

            $tran = CarT::getDb()->beginTransaction();
            try {
                $car_info = CarT::findOne(['id'=>$car_id]);
//                dd($car_info);
                //修改总库的数据
                if($invalid_id == 57 || $invalid_id == 58 || $invalid_id == 59 || $invalid_id ==60 || $invalid_id ==61 ) {
                    $car_info->insurer1_date=$ac1;
                    $car_info->insurer2_date=$ac2;
//                    $car_info->company = $ac3;
                }
                $car_info->save();

                //无效给管理员 -存储一个中间表
                $cdt= CarBT::find()->where('id='.$car_info->id)->one();

                $apto=AppointmentT::find()->where('car_id='.$car_info->id)
                    ->andWhere('user_id ='.$cdt->user_id)->orderBy('id desc')->one();

                //删除重复提交的人员
                $Invalids = InvalidNew::find()
                    ->where('user_id= '.$cdt->user_id)
                    ->all();

                foreach($Invalids as $info) {
                    $info->delete();
                }
                //删除保单
                $orders = OrderT::find()
                    ->where('car_id='.$car_info->id.' and status_id<2')
                    ->all();
                foreach($orders as $order_info) {
                    OrderUserT::deleteAll('order_id='.$order_info->id);
                    $order_info->delete();
                }
                $renewal= new InvalidNew();
                $renewal->car_id=$car_id;
                $renewal->car_no=$car_info->car_no;
                if($invalid_id == 57 || $invalid_id == 58 || $invalid_id == 59 || $invalid_id ==60 || $invalid_id ==61 ) {
                    $renewal->insurer1_date=$ac1;
                    $renewal->insurer2_date=$ac2;
                }else{
                    $renewal->insurer1_date=$car_info->insurer1_date;
                    $renewal->insurer2_date=$car_info->insurer2_date;
                }
                $renewal->phone=$car_info->phone;
                $renewal->xdate= $apto?$apto->xdate:'';
                $renewal->invalid_id= $invalid_id;
                $renewal->num= 1;
                $renewal->user_id= $cdt->user_id;
                $renewal->save();
                //d 库的user_id 改为0 收回状态
                $car_dinfo = CarBT::findOne(['id'=>$car_id]);
                $car_dinfo->user_id=0;
                $car_dinfo->back=1;
                $car_dinfo->iv_d=$invalid_id;
                $car_dinfo->save();
                $this->addLog($car_info->id,'新保销售预约时,无效给管理员进行管理',1);
                //删除预约
                AppointmentT::deleteAll('car_id='.$car_info->id);

                $result['success'] = true;
                $result['msg'] = '操作成功';

                $tran->commit();

            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }

        }

        return $result;

    }

    private function getDQuery($request)
    {

        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $insurer1_begin = $request->get('insurer1_begin');
        $insurer1_end = $request->get('insurer1_end');
        $status = $request->get('status',1);
        $company = $request->get('company');
        $invalid_id = $request->get('invalid_id');

        $params = array();
        $params['car_man'] = $car_man;
        $params['phone'] = $phone;
        $params['car_no'] = $car_no;
        $params['insurer1_begin'] = $insurer1_begin;
        $params['insurer1_end'] = $insurer1_end;
        $params['status'] = $status;
        $params['company'] = $company;
        $params['invalid_id'] = $invalid_id;

        $query = CarDT::find()
            ->leftJoin(CarT::tableName(),'`car_t`.`id`=`car_d_t`.`id`')
            ->orderBy('car_d_t.updated_at desc');
        $query = $query->andWhere('back=1');

        if($car_man != '') {
            $query = $query->andWhere('car_t.car_man="'.$car_man.'"');
        }
        if($phone != '') {
            $query = $query->andWhere('car_t.phone like "'.$phone.'"');
        }
        if($car_no != '') {
            $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
        }
        if($insurer1_begin != '') {
            $query = $query->andWhere('car_t.insurer1_date>="'.$insurer1_begin.'"');
        }
        if($insurer1_end != '') {
            $query = $query->andWhere('car_t.insurer1_date<="'.$insurer1_end.'"');
        }
        if($company != '') {
            $query = $query->andWhere('company like "'.$company.'%"');
        }
        if($status == 1) {
            $query = $query->andWhere('car_d_t.user_id=0');
        }
        if($status == 2) {
            $query = $query->andWhere('car_d_t.user_id>0');
        }
        if($invalid_id >0) {
            $query = $query->andWhere('car_d_t.iv_d="'.$invalid_id.'"');
        }
        return ['query'=>$query,'params'=>$params];
    }

    //查询d库无效的数据
    public function actionInvalidXubao()
    {
        $request = Yii::$app->request;
        $page = $request->get('page',1);
        $user_id = $request->get('user_id',1);
        $data = $this->getDQuery($request);
        $query = $data['query'];
        $params = $data['params'];
        $params['page'] = $page;
        $total = $query->count();
        $pagination = new Pagination(['totalCount' => $total,'pageSize'=>20]);
        $pagination->setPage($page-1);

        $query = $query->offset($pagination->offset)->limit($pagination->limit);
//        aa($query);
        $items = $query->all();
        $page_info = MyLib::getPageInfo($pagination);
        $user_items = $this->my->getChildren();
        $failure_items = InvalidT::getTreeXubao(2);
        $params['items'] = $items;
        $params['page_info'] = $page_info;
        $params['user_id'] = $user_id;
        $params['user_items'] = $user_items;
        $params['failure_items'] = $failure_items;

        return $this->render('xubao-list',$params);
    }
    //查询无效数据的详情
    public function actionXubaoInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $page = $request->get('page',1);
        $back_params = $request->get('back_params');
        $data= InvalidRenewal::find()->where(['car_id'=>$id])->all();
        $failure_items = InvalidT::getTreeXubao(2);
        $insurer_company2_items = InsurerCompany2T::find()->all();
        return $this->render('xubao-info',[
            'data'=>$data,
            'page'=>$page,
            'id'=>$id,
            'failure_items'=>$failure_items,
            'back_params' => $back_params,
            'insurer_company2_items'=>$insurer_company2_items,
        ]);
    }
    private function getBQuery($request)
    {

        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $insurer1_begin = $request->get('insurer1_begin');
        $insurer1_end = $request->get('insurer1_end');
        $status = $request->get('status',1);
        $company = $request->get('company');
        $invalid_id = $request->get('invalid_id');

        $params = array();
        $params['car_man'] = $car_man;
        $params['phone'] = $phone;
        $params['car_no'] = $car_no;
        $params['insurer1_begin'] = $insurer1_begin;
        $params['insurer1_end'] = $insurer1_end;
        $params['status'] = $status;
        $params['company'] = $company;
        $params['invalid_id'] = $invalid_id;

        $query = CarBT::find()
            ->leftJoin(CarT::tableName(),'`car_t`.`id`=`car_b_t`.`id`')
            ->orderBy('car_b_t.updated_at desc');
        $query = $query->andWhere('back=1');

        if($car_man != '') {
            $query = $query->andWhere('car_t.car_man="'.$car_man.'"');
        }
        if($phone != '') {
            $query = $query->andWhere('car_t.phone like "'.$phone.'"');
        }
        if($car_no != '') {
            $query = $query->andWhere('car_t.car_no like "'.$car_no.'"');
        }
        if($insurer1_begin != '') {
            $query = $query->andWhere('car_t.insurer1_date>="'.$insurer1_begin.'"');
        }
        if($insurer1_end != '') {
            $query = $query->andWhere('car_t.insurer1_date<="'.$insurer1_end.'"');
        }
        if($company != '') {
            $query = $query->andWhere('company like "'.$company.'%"');
        }
        if($status == 1) {
            $query = $query->andWhere('car_b_t.user_id=0');
        }
        if($status == 2) {
            $query = $query->andWhere('car_b_t.user_id>0');
        }
        if($invalid_id >0) {
            $query = $query->andWhere('car_b_t.iv_d="'.$invalid_id.'"');
        }
        return ['query'=>$query,'params'=>$params];
    }

    //查询b库无效的数据
    public function actionInvalidXinbaoList()
    {
        $request = Yii::$app->request;
        $page = $request->get('page',1);
        $user_id = $request->get('user_id',1);
        $data = $this->getBQuery($request);
        $query = $data['query'];
        $params = $data['params'];
        $params['page'] = $page;
        $total = $query->count();
        $pagination = new Pagination(['totalCount' => $total,'pageSize'=>20]);
        $pagination->setPage($page-1);

        $query = $query->offset($pagination->offset)->limit($pagination->limit);
//        aa($query);
        $items = $query->all();
        $page_info = MyLib::getPageInfo($pagination);
        $user_items = $this->my->getChildren();
        $failure_items = InvalidT::getTreeXinbaoNew(2);
        $params['items'] = $items;
        $params['page_info'] = $page_info;
        $params['user_id'] = $user_id;
        $params['user_items'] = $user_items;
        $params['failure_items'] = $failure_items;

        return $this->render('xinbao-list',$params);
    }
    //查询无效数据的详情
    public function actionXinbaoInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id',0);
        $page = $request->get('page',1);
        $back_params = $request->get('back_params');
        $data= InvalidNew::find()->where(['car_id'=>$id])->all();
//        dd($data);
        $failure_items = InvalidT::getTreeXinbaoNew(2);
        $insurer_company2_items = InsurerCompany2T::find()->all();
        return $this->render('xinbao-info',[
            'data'=>$data,
            'page'=>$page,
            'id'=>$id,
            'failure_items'=>$failure_items,
            'back_params' => $back_params,
            'insurer_company2_items'=>$insurer_company2_items,
        ]);
    }



    //无效数据到A库

    public function actionInvalidF()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $car_id = $request->post('car_id');
            $invalid_id = $request->post('invalid_id',0);
            $ac1 = $request->post('ac1');
            $ac2 = $request->post('ac2');
//            $ac3 = $request->post('ac3');

            $tran = CarT::getDb()->beginTransaction();
            try {
                $car_info = CarT::findOne(['id'=>$car_id]);
//                dd($car_info);
                if($invalid_id == 25 || $invalid_id == 27 || $invalid_id == 26 || $invalid_id ==34 || $invalid_id ==35 || $invalid_id ==36 || $invalid_id ==44) {
                    if($invalid_id == 25 || $invalid_id == 27){
                        CarFT::deleteAll('id='.$car_info->id);
                        $c_info = new CarFT();
                        $c_info->id = $car_info->id;
                        $c_info->user_id = 0;
                        $c_info->save();
                        $car_info->location = 7;
                        $car_info->company = '其他小保险公司';

                    }elseif($invalid_id == 26 || $invalid_id ==34 || $invalid_id ==35 || $invalid_id ==36){

                        CarCT::deleteAll('id='.$car_info->id);
                        $c_info = new CarCT();
                        $c_info->id = $car_info->id;
                        $c_info->user_id = 0;



                        switch($invalid_id) {
                            case 26:
                                $car_info->company = '人保';
                                $c_info->dif = 1;
                                break;
                            case 34:
                                $car_info->company = '太平洋';
                                $c_info->dif = 2;
                                break;
                            case 35:
                                $car_info->company = '国寿财';
                                $c_info->dif = 3;
                                break;
                            case 36:
                                $car_info->company = '平安';
                                $c_info->dif = 4;
                                break;
                            default:
                                $car_info->company = '';
                        }
                        $c_info->save();
                        $car_info->location = 3;
                    }elseif($invalid_id ==44){
                        $car_info->location = 1;
                    }
                    $car_info->insurer1_date = $ac1;
                    $car_info->insurer2_date = $ac2;
//                    $car_info->company = $ac3;
                    $car_info->save();
                    CarBT::deleteAll(['id'=>$car_info->id]);
                    CarDT::deleteAll(['id'=>$car_info->id]);

                    //删除预约
                    AppointmentT::deleteAll('car_id='.$car_info->id);
                    AppointmentHistoryT::deleteAll('car_id='.$car_info->id);

                    //删除保单
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id<2')
                        ->all();
                    foreach($orders as $order_info) {
                        OrderUserT::deleteAll('order_id='.$order_info->id);
                        $order_info->delete();
                    }
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id>1')
                        ->all();
                    foreach($orders as $order_info) {
                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
                        if($order_user_info) {
                            $order_user_info->status = 3;
                            $order_user_info->save();
                        }
                    }
                    if($invalid_id == 25 || $invalid_id == 27){

                        $this->addLog($car_info->id,'续保销售预约时,已在其他人保公司续保车辆数据或在人保公司续保，进入F库',1);
                    }elseif($invalid_id == 26 || $invalid_id ==34 || $invalid_id ==35 || $invalid_id ==36){

                        $this->addLog($car_info->id,'续保销售预约时,已在其他人保公司续保车辆数据，进入C库',1);
                    }elseif($invalid_id ==44){
                        $this->addLog($car_info->id,'续保销售预约时,部门曾经续保，进入A库',1);
                    }


                } else {




                    $car_info->location = 5;
                    $car_info->save();

                    CarInvalidT::deleteAll('id='.$car_info->id);
                    $invalid_info = new CarInvalidT();
                    $invalid_info->id = $car_info->id;
                    $invalid_info->invalid_id = $invalid_id;
                    $invalid_info->user_id = $this->my->id;
                    $invalid_info->save();

                    CarBT::deleteAll(['id'=>$car_info->id]);
                    CarCT::deleteAll(['id'=>$car_info->id]);
                    CarDT::deleteAll(['id'=>$car_info->id]);

                    //删除预约
                    AppointmentT::deleteAll('car_id='.$car_info->id);

                    //删除保单
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id<2')
                        ->all();
                    foreach($orders as $order_info) {
                        OrderUserT::deleteAll('order_id='.$order_info->id);
                        $order_info->delete();
                    }
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id>1')
                        ->all();
                    foreach($orders as $order_info) {
                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
                        if($order_user_info) {
                            $order_user_info->status = 3;
                            $order_user_info->save();
                        }
                    }

                    $this->addLog($car_info->id,'无效车辆数据:'.$invalid_info->invalid->name,1);

                }

                $result['success'] = true;
                $result['msg'] = '操作成功';

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        }
        return $result;
    }



    public function actionInvalidOldWuxiao()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $car_id = $request->post('car_id');
            $invalid_id = $request->post('invalid_id',0);
            $ac1 = $request->post('ac1');
            $ac2 = $request->post('ac2');
//            $ac3 = $request->post('ac3');

            $tran = CarT::getDb()->beginTransaction();
            try {
                $car_info = CarT::findOne(['id'=>$car_id]);
//                dd($car_info);
                if($invalid_id == 25 || $invalid_id == 27 || $invalid_id == 26 || $invalid_id ==34 || $invalid_id ==35 || $invalid_id ==36 || $invalid_id ==44) {
                    if($invalid_id == 25 || $invalid_id == 27){
                        CarF5T::deleteAll('id='.$car_info->id);
                        $c_info = new CarF5T();
                        $c_info->id = $car_info->id;
                        $c_info->user_id = 0;
                        $c_info->save();
                        $car_info->location = 12;
                        $car_info->company = '其他小保险公司';

                    }elseif($invalid_id == 26 || $invalid_id ==34 || $invalid_id ==35 || $invalid_id ==36){

                        CarF4T::deleteAll('id='.$car_info->id);
                        $c_info = new CarF4T();
                        $c_info->id = $car_info->id;
                        $c_info->user_id = 0;



                        switch($invalid_id) {
                            case 26:
                                $car_info->company = '人保';
                                break;
                            case 34:
                                $car_info->company = '太平洋';
                                $c_info->dif = 2;
                                break;
                            case 35:
                                $car_info->company = '国寿财';
                                break;
                            case 36:
                                $car_info->company = '平安';
                                break;
                            default:
                                $car_info->company = '';
                        }
                        $c_info->save();
                        $car_info->location = 11;
                    }elseif($invalid_id ==44){
                        $car_info->location = 1;
                    }
                    $car_info->insurer1_date = $ac1;
                    $car_info->insurer2_date = $ac2;
//                    $car_info->company = $ac3;
                    $car_info->save();
                    CarBT::deleteAll(['id'=>$car_info->id]);
                    CarDT::deleteAll(['id'=>$car_info->id]);

                    //删除预约
                    AppointmentT::deleteAll('car_id='.$car_info->id);
                    AppointmentHistoryT::deleteAll('car_id='.$car_info->id);

                    //删除保单
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id<2')
                        ->all();
                    foreach($orders as $order_info) {
                        OrderUserT::deleteAll('order_id='.$order_info->id);
                        $order_info->delete();
                    }
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id>1')
                        ->all();
                    foreach($orders as $order_info) {
                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
                        if($order_user_info) {
                            $order_user_info->status = 3;
                            $order_user_info->save();
                        }
                    }
                    if($invalid_id == 25 || $invalid_id == 27){

                        $this->addLog($car_info->id,'续保销售预约时,进入F5续保其他小公司无效库',1);
                    }elseif($invalid_id == 26 || $invalid_id ==34 || $invalid_id ==35 || $invalid_id ==36){

                        $this->addLog($car_info->id,'续保销售预约时,进入F4续保四大公司无效库',1);
                    }elseif($invalid_id ==44){
                        $this->addLog($car_info->id,'续保销售预约时,部门曾经续保，进入A库',1);
                    }



                } else {




                    $car_info->location = 13;
                    $car_info->save();

                    CarF6T::deleteAll('id='.$car_info->id);
                    $invalid_info = new CarF6T();
                    $invalid_info->id = $car_info->id;
                    $invalid_info->invalid_id = $invalid_id;
                    $invalid_info->user_id = $this->my->id;
                    $invalid_info->save();

                    CarBT::deleteAll(['id'=>$car_info->id]);
                    CarCT::deleteAll(['id'=>$car_info->id]);
                    CarDT::deleteAll(['id'=>$car_info->id]);

                    //删除预约
                    AppointmentT::deleteAll('car_id='.$car_info->id);

                    //删除保单
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id<2')
                        ->all();
                    foreach($orders as $order_info) {
                        OrderUserT::deleteAll('order_id='.$order_info->id);
                        $order_info->delete();
                    }
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id>1')
                        ->all();
                    foreach($orders as $order_info) {
                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
                        if($order_user_info) {
                            $order_user_info->status = 3;
                            $order_user_info->save();
                        }
                    }

                    $this->addLog($car_info->id,'无效车辆数据:'.$invalid_info->invalid->name,1);

                }

                $result['success'] = true;
                $result['msg'] = '操作成功';

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        }
        return $result;
    }
    public function actionInvalidXinbao()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $car_id = $request->post('car_id');
            $invalid_id = $request->post('invalid_id',0);
            $ac1 = $request->post('ac1');
            $ac2 = $request->post('ac2');
//            $ac3 = $request->post('ac3');

            $tran = CarT::getDb()->beginTransaction();
            try {
                $car_info = CarT::findOne(['id'=>$car_id]);
//                dd($car_info);
                if($invalid_id == 57 || $invalid_id == 58 || $invalid_id == 59 || $invalid_id ==60 || $invalid_id ==61) {
                    if($invalid_id == 61){
                        CarFT::deleteAll('id='.$car_info->id);
                        $c_info = new CarFT();
                        $c_info->id = $car_info->id;
                        $c_info->user_id = 0;
                        $c_info->save();
                        $car_info->location = 7;
                        $car_info->company = '其他小保险公司';

                    }elseif($invalid_id == 57 || $invalid_id == 58 || $invalid_id == 59 || $invalid_id ==60){

                        CarCT::deleteAll('id='.$car_info->id);
                        $c_info = new CarCT();
                        $c_info->id = $car_info->id;
                        $c_info->user_id = 0;

                        switch($invalid_id) {
                            case 57:
                                $car_info->company = '人保';
                                $c_info->dif = 1;
                                break;
                            case 58:
                                $car_info->company = '平安';
                                $c_info->dif = 4;
                                break;
                            case 59:
                                $car_info->company = '太平洋';
                                $c_info->dif = 2;
                                break;
                            case 60:
                                $car_info->company = '国寿财';
                                $c_info->dif = 3;
                                break;
                            default:
                                $car_info->company = '';
                        }
                        $c_info->save();
                        $car_info->location = 3;
                    }
                    $car_info->insurer1_date = $ac1;
                    $car_info->insurer2_date = $ac2;
//                    $car_info->company = $ac3;
                    $car_info->save();
                    CarBT::deleteAll(['id'=>$car_info->id]);
                    CarDT::deleteAll(['id'=>$car_info->id]);

                    //删除预约
                    AppointmentT::deleteAll('car_id='.$car_info->id);
                    AppointmentHistoryT::deleteAll('car_id='.$car_info->id);

                    //删除保单
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id<2')
                        ->all();
                    foreach($orders as $order_info) {
                        OrderUserT::deleteAll('order_id='.$order_info->id);
                        $order_info->delete();
                    }
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id>1')
                        ->all();
                    foreach($orders as $order_info) {
                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
                        if($order_user_info) {
                            $order_user_info->status = 3;
                            $order_user_info->save();
                        }
                    }
                    if($invalid_id == 61){

                        $this->addLog($car_info->id,'续保销售预约时,已在其他人保公司续保车辆数据或在人保公司续保，进入F库',1);
                    }elseif($invalid_id == 57 || $invalid_id == 58 || $invalid_id == 59 || $invalid_id ==60){

                        $this->addLog($car_info->id,'续保销售预约时,已在其他人保公司续保车辆数据，进入C库',1);
                    }



                } else {




                    $car_info->location = 5;
                    $car_info->save();

                    CarInvalidT::deleteAll('id='.$car_info->id);
                    $invalid_info = new CarInvalidT();
                    $invalid_info->id = $car_info->id;
                    $invalid_info->invalid_id = $invalid_id;
                    $invalid_info->user_id = $this->my->id;
                    $invalid_info->save();

                    CarBT::deleteAll(['id'=>$car_info->id]);
                    CarCT::deleteAll(['id'=>$car_info->id]);
                    CarDT::deleteAll(['id'=>$car_info->id]);

                    //删除预约
                    AppointmentT::deleteAll('car_id='.$car_info->id);

                    //删除保单
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id<2')
                        ->all();
                    foreach($orders as $order_info) {
                        OrderUserT::deleteAll('order_id='.$order_info->id);
                        $order_info->delete();
                    }
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id>1')
                        ->all();
                    foreach($orders as $order_info) {
                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
                        if($order_user_info) {
                            $order_user_info->status = 3;
                            $order_user_info->save();
                        }
                    }

                    $this->addLog($car_info->id,'无效车辆数据:'.$invalid_info->invalid->name,1);

                }

                $result['success'] = true;
                $result['msg'] = '操作成功';

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        }
        return $result;
    }
    public function actionInvalidNewWuxiao()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $car_id = $request->post('car_id');
            $invalid_id = $request->post('invalid_id',0);
            $ac1 = $request->post('ac1');
            $ac2 = $request->post('ac2');
//            $ac3 = $request->post('ac3');

            $tran = CarT::getDb()->beginTransaction();
            try {
                $car_info = CarT::findOne(['id'=>$car_id]);
//                dd($car_info);
                if($invalid_id == 57 || $invalid_id == 58 || $invalid_id == 59 || $invalid_id ==60 || $invalid_id ==61) {
                    if($invalid_id == 61){
                        CarF2T::deleteAll('id='.$car_info->id);
                        $c_info = new CarF2T();
                        $c_info->id = $car_info->id;
                        $c_info->user_id = 0;
                        $c_info->save();
                        $car_info->location = 9;
                        $car_info->company = '其他小保险公司';

                    }elseif($invalid_id == 57 || $invalid_id == 58 || $invalid_id == 59 || $invalid_id ==60){

                        CarF1T::deleteAll('id='.$car_info->id);
                        $c_info = new CarF1T();
                        $c_info->id = $car_info->id;
                        $c_info->user_id = 0;

                        switch($invalid_id) {
                            case 57:
                                $car_info->company = '人保';
                                break;
                            case 58:
                                $car_info->company = '平安';
                                break;
                            case 59:
                                $car_info->company = '太平洋';
                                break;
                            case 60:
                                $car_info->company = '国寿财';
                                break;
                            default:
                                $car_info->company = '';
                        }
                        $c_info->save();
                        $car_info->location = 8;
                    }
                    $car_info->insurer1_date = $ac1;
                    $car_info->insurer2_date = $ac2;
//                    $car_info->company = $ac3;
                    $car_info->save();
                    CarBT::deleteAll(['id'=>$car_info->id]);
                    CarDT::deleteAll(['id'=>$car_info->id]);

                    //删除预约
                    AppointmentT::deleteAll('car_id='.$car_info->id);
                    AppointmentHistoryT::deleteAll('car_id='.$car_info->id);

                    //删除保单
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id<2')
                        ->all();
                    foreach($orders as $order_info) {
                        OrderUserT::deleteAll('order_id='.$order_info->id);
                        $order_info->delete();
                    }
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id>1')
                        ->all();
                    foreach($orders as $order_info) {
                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
                        if($order_user_info) {
                            $order_user_info->status = 3;
                            $order_user_info->save();
                        }
                    }
                    if($invalid_id == 61){

                        $this->addLog($car_info->id,'新保销售预约时,已在新保其他小公司，进入F2库',1);
                    }elseif($invalid_id == 57 || $invalid_id == 58 || $invalid_id == 59 || $invalid_id ==60){

                        $this->addLog($car_info->id,'新保销售预约时,已在新保四大公司，进入F1库',1);
                    }



                } else {



//dd($invalid_id);
                    $car_info->location = 10;
                    $car_info->save();
                    CarF3T::deleteAll('id='.$car_info->id);
                    $invalid_info = new CarF3T();
                    $invalid_info->id = $car_info->id;
                    $invalid_info->invalid_id = $invalid_id;
                    $invalid_info->user_id = $this->my->id;
                    $invalid_info->save();

                    CarBT::deleteAll(['id'=>$car_info->id]);
                    CarCT::deleteAll(['id'=>$car_info->id]);
                    CarDT::deleteAll(['id'=>$car_info->id]);

                    //删除预约
                    AppointmentT::deleteAll('car_id='.$car_info->id);

                    //删除保单
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id<2')
                        ->all();
                    foreach($orders as $order_info) {
                        OrderUserT::deleteAll('order_id='.$order_info->id);
                        $order_info->delete();
                    }
                    $orders = OrderT::find()
                        ->where('car_id='.$car_info->id.' and status_id>1')
                        ->all();
                    foreach($orders as $order_info) {
                        $order_user_info = OrderUserT::findOne(['order_id'=>$order_info->id,'status'=>0]);
                        if($order_user_info) {
                            $order_user_info->status = 3;
                            $order_user_info->save();
                        }
                    }

                    $this->addLog($car_info->id,'无效车辆数据:'.$invalid_info->invalid->name,1);

                }

                $result['success'] = true;
                $result['msg'] = '操作成功';

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                throw $e;
            }
        }
        return $result;
    }

    public function actionSearch() {
        return $this->render('search');
    }

    public function actionSearchJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $car_model = $request->get('car_model');
        $register_date = $request->get('register_date');
        $insurer_date = $request->get('insurer_date');
        $id_man = $request->get('id_man');
        $op = $request->get('op',1);
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $query = CarT::find()
            ->leftJoin('order_t','`order_t`.`car_id`=`car_t`.`id`');

        if($op==0) {
            $query = $query->andWhere('car_t.id=-1');
        }
        if($car_man != '') {
            $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
        }
        if($phone != '') {
            $linkman_items = LinkmanT::find()
                ->where('phone like "'.$phone.'"')
                ->all();
            $car_ids = array();
            foreach($linkman_items as $linkman_info) {
                $car_ids[] = $linkman_info->car_id;
            }
            $car_ids_str = join(',',$car_ids);
            if($car_ids_str == '')
                $car_ids_str = '0';

            $query = $query->andWhere('(car_t.phone like "'.$phone.'" or car_t.id in ('.$car_ids_str.'))');
        }
        if($car_no != '') {
            $query = $query->andWhere('car_t.car_no like "'.$car_no.'%"');
        }
        if($car_model != '') {
            $query = $query->andWhere('car_t.car_model="'.$car_model.'"');
        }
        if($register_date != '') {
            $query = $query->andWhere('car_t.register_date='.$register_date);
        }
        if($insurer_date != '') {
            $query = $query->andWhere('car_t.insurer1_date="'.$insurer_date.'" or car_t.insurer2_date="'.$insurer_date.'"');
        }
        if($id_man != '') {
            $query = $query->andWhere('order_t.id_man="'.$id_man.'"');
        }

        $total = $query->count();
        $query = $query->offset($offset)->limit($limit);
        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['show_name'] = $item->lib&&$item->lib->user?$item->lib->user->getShowName():'';
            $row['location_txt'] = $item->location?$item->getLocation():'';
            $data['rows'][] = $row;
        }
        return $data;
    }

    public function actionNonSearch()
    {
        $request = Yii::$app->request;
        $car_man = $request->get('car_man');
        $phone = $request->get('phone');
        $car_no = $request->get('car_no');
        $car_model = $request->get('car_model');
        $register_date = $request->get('register_date');
        $insurer_date = $request->get('insurer_date');
        $id_man = $request->get('id_man');
        $op = $request->get('op',1);
        $page = $request->get('page',1);
        if($page < 1) $page = 1;

        $query = CarT::find()
            ->leftJoin('order_t','`order_t`.`car_id`=`car_t`.`id`');

        if($op==0) {
            $query = $query->andWhere('car_t.id=-1');
        }
        if($car_man != '') {
            $query = $query->andWhere('car_t.car_man like "'.$car_man.'"');
        }
        if($phone != '') {
            $linkman_items = LinkmanT::find()
                ->where('phone like "'.$phone.'"')
                ->all();
            $car_ids = array();
            foreach($linkman_items as $linkman_info) {
                $car_ids[] = $linkman_info->car_id;
            }
            $car_ids_str = join(',',$car_ids);
            if($car_ids_str == '')
                $car_ids_str = '0';

            $query = $query->andWhere('(car_t.phone like "'.$phone.'" or car_t.id in ('.$car_ids_str.'))');
        }
        if($car_no != '') {
            $query = $query->andWhere('car_t.car_no like "'.$car_no.'%"');
        }
        if($car_model != '') {
            $query = $query->andWhere('car_t.car_model="'.$car_model.'"');
        }
        if($register_date != '') {
            $query = $query->andWhere('car_t.register_date='.$register_date);
        }
        if($insurer_date != '') {
            $query = $query->andWhere('car_t.insurer1_date="'.$insurer_date.'" or car_t.insurer2_date="'.$insurer_date.'"');
        }
        if($id_man != '') {
            $query = $query->andWhere('order_t.id_man="'.$id_man.'"');
        }
        $total = $query->count();

        $pagination = new Pagination(['totalCount' => $total,'pageSize'=>20]);
        $pagination->setPage($page-1);

        $query = $query->offset($pagination->offset)->limit($pagination->limit);
        $items = $query->all();

        $page_info = MyLib::getPageInfo($pagination);

        return $this->render('non-search',[
            'items' => $items,
            'car_man' => $car_man,
            'phone' => $phone,
            'car_no' => $car_no,
            'car_model' => $car_model,
            'register_date' => $register_date,
            'insurer_date' => $insurer_date,
            'id_man' => $id_man,
            'page' => $page,
            'page_info' => $page_info
        ]);
    }

    public function actionSmsSend()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $MessageContent = $request->post('msg');
        $UserNumber = $request->post('tel');
        $company_id = $request->post('company_id');

        if($company_id == 0){
            $result['msg'] = '保险公司不能为空';
            return $result;
        }
        if($UserNumber == '' || $UserNumber == 0){
            $result['msg'] = '手机手机号不能为空';
            return $result;
        }
        if($MessageContent == ''){
            $result['msg'] = '短信内容不能为空';
            return $result;
        }
        $MessageContent = str_replace("\n","",$MessageContent);
        $MessageContent = str_replace("\r","",$MessageContent);
        $MessageContent = str_replace("\f","",$MessageContent);
        $MessageContent = str_replace("\t","",$MessageContent);

        $url = 'http://user.banmacar.com/api/sms/single-send';
        $params['token'] = '8a668d6c94166df201337dbb272f66cf';
        $params['mobile'] = $UserNumber;
        $params['content'] = $MessageContent;
        $post_url = http_build_query($params);

        $msg = MyLib::Post($post_url,$url);
//        $msg = mb_convert_encoding($msg,'UTF8','GBK');
//        parse_str($msg,$obj);
        $obj = json_decode($msg,true);
        $result = array();
//        $result['success'] = true;
        if($obj['code'] == 200) {
            $result['msg'] = $obj['data'];
        }else{
            $result['msg'] = $obj['msg'];
        }
        return $result;
    }

    public function actionSmsMake()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '生成失败';

        $order_id = $request->post('order_id');
        $company_id = $request->post('company_id');
//        $company2_name = InsurerCompany2T::findOne($company2_id)->name;
        $company_name ='';
        if($company_id == 1){
            $company_name = '人保车险';
        }elseif ($company_id ==8){
            $company_name = '平安车险';

        }elseif ($company_id == 4){
            $company_name = '太平洋车险';
        }elseif ($company_id ==7){
            $company_name = '人寿车险';
        }

        $company ='';
        if($company_id == 1){
            $company = '人保';
        }elseif ($company_id == 8){
            $company = '平安';

        }elseif ($company_id == 4){
            $company = '太平洋';
        }elseif ($company_id == 7){
            $company = '太平洋';
        }

//        var_dump($order_id);
//        die;
        $order_info = OrderT::findOne(['id'=>$order_id]);
        $car_info = $order_info->car;

        $total1 = $request->post('total1');
        $total2 = $request->post('total2');

        $total1_dis = $request->post('total1_dis');
        $total1_clear = $request->post('total1_clear');

        $total3 = $request->post('total3');
        $total_all = $request->post('total_all');
        $total_real = $request->post('total_real');
        $types = $request->post('types');
        $nopays = $request->post('nopays');

        $insurer_type_items = InsurerTypeT::find()->all();

        $tmp_total = $total_real;
        $msg = '【'.$company_name.'】尊敬的'.$car_info->car_no.'客户您好：'.$company.$this->my->name.'为您报价：';
        $msg .= '交强、';
        if($total3 > 0) {
            $msg .= '车船税、';
//            $tmp_total += $total3;
        }
//        $msg .= '商业'.$total1.'元';
//        $msg .= '总计'.($total_all).'元，';
//        $msg .= '实收'.($total_real).'元；';
        //$msg .= '[';
        $msg1 = '';
        $bj = '';
        $has_chesun = 0;
        foreach($insurer_type_items as $item) {
            if($item->id == 10 || $item->id == 11) continue;
            if($types[$item->id] != '' && $types[$item->id] != '否' && $types[$item->id] != '无') {
                if($item->name == '车损'){
                    $has_chesun = 1;
                }
                if($item->name == '无法找到第三方特约险'){
                    $msg1 .= '无法找到第三方';
                }else{
                    $msg1 .= $item->name;
                }
                if($types[$item->id] != '是')
                    if($item->name != '车损'){
                        $msg1 .= $types[$item->id];
                    }
                $msg1 .= '、';
                if(isset($nopays[$item->id]) && ($nopays[$item->id] == 1))
                    $bj .= $item->code;
            }
        }

        if($msg1 != ''){
            if($bj != ''){
                $msg1 .= '不计免赔';
                $msg1 = $msg1.'，';
            }else{
                $msg1 = rtrim($msg1,'、');
                $msg1 = $msg1.'，';
            }
        }

        $msg .= $msg1;
        $msg .= '保费实收'.($tmp_total).'元；';
        $msg .= '祝您生活愉快。';



        $result['success'] = true;
        $result['msg'] = $msg;
        return $result;
    }

    public function actionLinkmanAdd()
    {
        $request = Yii::$app->request;
        $car_id = $request->get('car_id',0);
        return $this->render('linkman-add',[
            'car_id' => $car_id
        ]);
    }

    public function actionLinkmanSave()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if($request->isPost) {
            $car_id = $request->post('car_id',0);
            $name = $request->post('name');
            $phone = $request->post('phone');
            $id_number = $request->post('id_number');
            $id_type = $request->post('id_type');
            $type = $request->post('type');

            if($name == '' || $phone == '') {
                $result['msg'] = '请输入姓名和联系电话!';
                return $result;
            }

            $row = null;
            $linkman_info = new LinkmanT();
            $linkman_info->car_id = $car_id;
            $linkman_info->name = $name;
            $linkman_info->phone = $phone;
            $linkman_info->type = $type;
            $linkman_info->id_type = $id_type;
            $linkman_info->id_number = $id_number;
            if(!$linkman_info->save()) {
                $result['msg'] = print_r($linkman_info->getErrors(),true);
            } else {
                $result['success'] = true;
                $result['msg'] = '保存成功';
            }
        }
        return $result;
    }

    public function actionAjaxLinkmanIndex()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $car_id = $request->get('car_id');

        $result = array();
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $query = LinkmanT::find()
            ->where(['car_id'=>$car_id])
            ->orderBy('id ASC');

        $items = $query->all();

        $html = $this->renderPartial('ajax-linkman-index',[
            'items' => $items
        ]);
        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }

    public function actionHistory() {
        $request = Yii::$app->request;
        $car_id = $request->get('car_id');

        return $this->render('history',[
            'car_id' => $car_id
        ]);
    }

    public function actionHistoryJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $car_id = $request->get('car_id');
        $offset = $request->get('offset', 0);
        $limit = $request->get('limit', 10);

        $query = CarLogT::find()
            ->where(['car_id'=>$car_id,'type'=>1])
            ->andWhere('op_time>='.strtotime("-6 months"))
            ->orderBy('op_time DESC');
//echo $query->createCommand()->rawSql;
        $total = $query->count();

        $query = $query->offset($offset)->limit($limit);
        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['op_time'] = date('Y-m-d H:i:s', $item->op_time);
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionOrderHistoryJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $car_id = $request->get('car_id');
        $offset = $request->get('offset', 0);
        $limit = $request->get('limit', 10);

        $query = OrderT::find()
            ->where(['car_id'=>$car_id])
            ->andWhere('status_id>1')
            ->orderBy('id DESC');
        $total = $query->count();

        $query = $query->offset($offset)->limit($limit);
        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['username'] = $item->user->getShowName();
            $row['status'] = $item->status->name;
            $data['rows'][] = $row;
        }

        return $data;
    }

    public function actionOrderAdd() {
        $request = Yii::$app->request;
        $car_id = $request->get('car_id');

        $car_info = CarT::findOne(['id'=>$car_id]);
        $order_info = $car_info->getOrders()->orderBy('id DESC')->one();
        if(!$order_info) {
            $user_id = 0;
            if($car_info->location == 2) {
                $b_info = CarBT::findOne(['id'=>$car_info->id]);
                $user_id = $b_info->user_id;
            }
            if($car_info->location == 3) {
                $c_info = CarCT::findOne(['id'=>$car_info->id]);
                $user_id = $c_info->user_id;
            }
            if($car_info->location == 4) {
                $d_info = CarDT::findOne(['id'=>$car_info->id]);
                $user_id = $d_info->user_id;
            }
            $order_info = new OrderT();
            $order_info->car_id = $car_info->id;
            $order_info->car_no = $car_info->car_no;
            $order_info->engine_no = $car_info->engine_no;
            $order_info->car_frame_no = $car_info->car_frame_no;
            $order_info->car_man = $car_info->car_man;
            $order_info->user_id = $user_id;
            $order_info->status_id = 1;
            $order_info->id_man = $car_info->car_man;
            $order_info->link_man = $car_info->car_man;
            $order_info->link_phone = $car_info->phone;
            $order_info->save();
        }
        $insurer_type_items = InsurerTypeT::find()->all();
        $insurer_company_items = InsurerCompanyT::find()->all();
        $car_use_items = CarUseT::find()->all();
        $insurer_company2_items = InsurerCompany2T::find()->all();
        $pay_type_items = PayTypeT::find()->all();
        $success_items = InvalidT::getTree(1);
        $city_items = CityT::find()->all();
        $district_items = DistrictT::find()->all();

        return $this->render('order-add',[
            'car_id' => $car_id,
            'car_info' => $car_info,
            'order_info' => $order_info,
            'insurer_type_items' => $insurer_type_items,
            'insurer_company_items' => $insurer_company_items,
            'insurer_company2_items' => $insurer_company2_items,
            'car_use_items' => $car_use_items,
            'pay_type_items' => $pay_type_items,
            'success_items' => $success_items,
            'city_items' => $city_items,
            'district_items' => $district_items
        ]);
    }

    public function actionInvalidCar() {
        $request = Yii::$app->request;
        $car_id = $request->get('car_id');

        $invalid_items = InvalidT::getTree();

        return $this->render('invalid-car', [
            'car_id' => $car_id,
            'invalid_items' => $invalid_items
        ]);
    }

    public function actionInvalidSave() {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $car_id = $request->post('car_id');
        $invalid_id = $request->post('invalid_id');

        if($invalid_id == 0) {
            $result['msg'] = '请选择无效理由';
            return $result;
        }

        $tran = CarT::getDb()->beginTransaction();
        try {
            $car_info = CarT::findOne(['id'=>$car_id]);
            $car_info->location = 5;
            if(!$car_info->save(false)) {
                throw new Exception(print_r($car_info->getFirstErrors(),true));
            }

            $invalid_info = CarInvalidT::findOne(['id'=>$car_info->id]);
            if(!$invalid_info) {
                $invalid_info = new CarInvalidT(false);
                $invalid_info->id = $car_info->id;
                $invalid_info->user_id = $this->my->id;
                $invalid_info->invalid_id = $invalid_id;
                if(!$invalid_info->save(false)) {
                    throw new Exception(print_r($invalid_info->getFirstErrors(),true));
                }
            }
            CarCT::deleteAll(['id'=>$car_info->id]);
            CarBT::deleteAll(['id'=>$car_info->id]);
            CarDT::deleteAll(['id'=>$car_info->id]);
            AppointmentT::deleteAll('car_id='.$car_info->id);

            //删除保单 还没有正本生成的保单可以直接删除,正本生成后,需要退单操作
            //删除操作人员
            $orders = OrderT::find()
                ->where('car_id='.$car_info->id.' and status_id<5')
                ->all();
            foreach($orders as $order_info) {
                OrderUserT::deleteAll('order_id='.$order_info->id);
                //删除保单
                $order_info->delete();
            }

            $this->addLog($car_info->id,'从业务员无效车辆信息',1);

            $result['success'] = true;
            $result['msg'] = '操作成功';

            $tran->commit();
        } catch (\Exception $e) {
            $tran->rollBack();
            $result['msg'] = $e->getMessage();
        }
        return $result;
    }
}
