<?php

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\AppointmentHistoryT;
use common\models\AppointmentT;
use common\models\FiltrationT;
use common\models\BrandT;
use common\models\CarBT;
use common\models\CarCT;
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\CardinfoT;
use common\models\CarDT;
use common\models\CarInvalidT;
use common\models\CarMistakeT;
use common\models\CarLogT;
use common\models\CarT;
use common\models\CarTypeT;
use common\models\CarUseT;
use common\models\CleanT;
use common\models\CleanTongji;
use common\models\CleanFenpei;
use common\models\DisplacementT;
use common\models\InvalidT;
use common\models\OrderT;
use common\models\OrderUserT;
use common\models\PriceT;
use common\models\RightT;
use common\models\SeriesT;
use common\models\UserT;
use common\models\InvalidNew;
use Yii;
use yii\data\Pagination;
use yii\db\Exception;
use yii\web\Response;
use yii\db\Expression;

class DatabaseController extends BaseController
{
    public $enableCsrfValidation = false;
    public $layout = 'blue-main';
    //A库query
    //获取搜索条件
    private function getAQuery($request)
    {
        if($request->isPost) {
            $car_man = $request->post('car_man');
            $phone = $request->post('phone');
            $car_no = $request->post('car_no');
            $engine_no = $request->post('engine_no');
            $car_frame_no = $request->post('car_frame_no');
            $register_begin = $request->post('register_begin');
            $register_end = $request->post('register_end');
            $insurer1_begin = $request->post('insurer1_begin');
            $insurer1_end = $request->post('insurer1_end');
            $insurer1_month = $request->post('insurer_month_begin');
            $insurer1_day = $request->post('insurer_day_begin');
            $insurer1_month1 = $request->post('insurer_month_end');
            $insurer1_day1 = $request->post('insurer_day_end');
            $b_lib = $request->post('b_lib');
            $c_lib = $request->post('c_lib');
            $d_lib = $request->post('d_lib');
            $e_lib = $request->post('e_lib');
            $invalid_lib = $request->post('invalid_lib');
            $unsel_lib = $request->post('unsel_lib');
            $has_phone = $request->post('has_phone');
            $company = $request->post('company');
            $user1 = $request->post('user1');
            $no_insurerdate = $request->post('no_insurerdate');
            $clean_right = $request->post('clean_right');
            $biaozhu = $request->post('biaozhu');
            $car_use_id = $request->post('car_use_id');
        } else {

            $car_man = $request->get('car_man');
            $phone = $request->get('phone');
            $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');
            $insurer1_begin = $request->get('insurer1_begin');
            $insurer1_end = $request->get('insurer1_end');
            $insurer1_month = $request->get('insurer_month_begin');
            $insurer1_day = $request->get('insurer_day_begin');
            $insurer1_month1 = $request->get('insurer_month_end');
            $insurer1_day1 = $request->get('insurer_day_end');
            $b_lib = $request->get('b_lib');
            $c_lib = $request->get('c_lib');
            $d_lib = $request->get('d_lib');
            $e_lib = $request->get('e_lib');
            $invalid_lib = $request->get('invalid_lib');
            $unsel_lib = $request->get('unsel_lib');
            $has_phone = $request->get('has_phone');
            $company = $request->get('company');
            $user1 = $request->get('user1');
            $no_insurerdate = $request->get('no_insurerdate');
            $clean_right = $request->get('clean_right');
            $biaozhu = $request->get('biaozhu');
            $car_use_id = $request->get('car_use_id');
        }
        $params = array();
        $params['car_man'] = $car_man;
        $params['phone'] = $phone;
        $params['car_no'] = $car_no;
        $params['engine_no'] = $engine_no;
        $params['car_frame_no'] = $car_frame_no;
        $params['register_begin'] = $register_begin;
        $params['register_end'] = $register_end;
        $params['insurer1_begin'] = $insurer1_begin;
        $params['insurer1_end'] = $insurer1_end;
        $params['insurer1_month'] = $insurer1_month;
        $params['insurer1_day'] = $insurer1_day;
        $params['insurer1_month1'] = $insurer1_month1;
        $params['insurer1_day1'] = $insurer1_day1;
        $params['b_lib'] = $b_lib;
        $params['c_lib'] = $c_lib;
        $params['d_lib'] = $d_lib;
        $params['e_lib'] = $e_lib;
        $params['invalid_lib'] = $invalid_lib;
        $params['unsel_lib'] = $unsel_lib;
        $params['has_phone'] = $has_phone;
        $params['company'] = $company;
        $params['user1'] = $user1;
        $params['no_insurerdate'] = $no_insurerdate;
        $params['clean_right'] = $clean_right;
        $params['biaozhu'] = $biaozhu;
        $params['car_use_id'] = $car_use_id;

        $query = CarT::find();

        $libs = array();
        if($b_lib == 1) {
            $libs[] = 2;
        }
        if($c_lib == 1) {
            $libs[] = 3;
        }
        if($d_lib == 1) {
            $libs[] = 4;
        }
        if($e_lib == 1) {
            $libs[] = 6;
        }
        if($invalid_lib == 1) {
            $libs[] = 5;
        }
        if($unsel_lib == 1) {
            $libs[] = 1;
        }
        if(count($libs) > 0)
            $query->andWhere(['in','location',$libs]);

        if($car_man != '') {
            $query->andWhere('car_man like "'.$car_man.'"');
        }
        if($phone != '') {
            $query->andWhere('car_man_phone=:phone or id_man_phone=:phone',[':phone'=>$phone]);
        }
        if($car_no != '') {
            $query->andWhere('car_no like "'.$car_no.'%"');
        }
        if($engine_no != '') {
            $query->andWhere('engine_no="'.$engine_no.'"');
        }
        if($car_frame_no != '') {
            $query->andWhere('car_frame_no="'.$car_frame_no.'"');
        }
        if($register_begin != '') {
            $query->andWhere('register_date>="'.$register_begin.'"');
        }
        if($register_end != '') {
            $query->andWhere('register_date<="'.$register_end.'"');
        }
        if($insurer1_begin != '') {
            $query->andWhere('insurer1_date>="'.$insurer1_begin.'"');
        }
        if($insurer1_end != '') {
            $query->andWhere('insurer1_date<="'.$insurer1_end.'"');
        }
        if($insurer1_month != '' && $insurer1_day == '') {
            $query = $query->andWhere('month(car_t.insurer1_date)>="'.$insurer1_month.'"');
        } else if ($insurer1_month == '' && $insurer1_day != '') {
            $query = $query->andWhere('day(car_t.insurer1_date)>="'.$insurer1_day.'"');
        } else if ($insurer1_month != '' && $insurer1_day != '') {
            $query = $query->andWhere('DATE_FORMAT(car_t.insurer1_date,"%m-%d") >= "' . substr('0' . $insurer1_month, -2) . '-' . substr('0' . $insurer1_day, -2) . '"');
        }
        if($insurer1_month1 != '' && $insurer1_day1 == '') {
            $query = $query->andWhere('month(car_t.insurer1_date) <="'.$insurer1_month1.'"');
        } else if ($insurer1_month1 == '' && $insurer1_day1 != '') {
            $query = $query->andWhere('day(car_t.insurer1_date) <="'.$insurer1_day1.'"');
        } else if ($insurer1_month1 != '' && $insurer1_day1 != '') {
            $query = $query->andWhere('DATE_FORMAT(car_t.insurer1_date,"%m-%d") <= "' . substr('0' . $insurer1_month1, -2) . '-' . substr('0' . $insurer1_day1, -2) . '"');
        }
        if($clean_right != '') {
            $query->andWhere('car_t.clean_right="'.$clean_right.'"');
        }
        if($biaozhu != '') {
            $query->andWhere('car_t.biaozhu="'.$biaozhu.'"');
        }

        if($has_phone == 1) {
            $query->andWhere('car_man_phone<>""');
        }
        if($no_insurerdate == 1) {
            $query->andWhere('insurer1_date="" or insurer1_date is null or insurer1_date="0000-00-00"');
        }
        if($company != '') {
            $query->andWhere('company like "'.$company.'%"');
        }
        if($user1 != '') {
            $query->andWhere('op_user1 like "'.$user1.'%"');
        }
        if($car_use_id > 0) {
            $query->andWhere('car_use_id='.$car_use_id);
        }
        return ['query'=>$query,'params'=>$params];
    }
    //A库列表页
    public function actionAIndex() {
        $invalid_items = InvalidT::getTree();
        $car_use_items = CarUseT::find()->all();
        return $this->render('a-index',[
            'invalid_items' => $invalid_items,
            'car_use_items' => $car_use_items
        ]);
    }
    //A库列表数据
    public function actionAIndexJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $data = $this->getAQuery($request);

        $query = $data['query'];
//        $query->andWhere('location=1');

        $total = $query->count();

        $query->orderBy('id desc');
        $query = $query->offset($offset)->limit($limit);
        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $row = $item->toArray();
            $row['factory_model'] = MyLib::substr_cut($item->factory_model, 8);
            $row['car_man'] = MyLib::substr_cut($item->car_man, 8);
            $row['location_name'] = $item->getLocation();
            $data['rows'][] = $row;
        }
        return $data;
    }
    //钩选A库到B库
    public function actionAB()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $ids = explode(',',$request->post('ids'));
            if(count($ids) == 0) {
                $result['msg'] = '请先钩选车辆';
                return $result;
            }

            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($ids as $id) {
                    $car_info = CarT::findOne(['id'=>$id]);
                    if($car_info->location == 1) {
                        $car_info->location = 2;
                        $car_info->is_xubao = 0;
                        if(!$car_info->save(false)) {
                            throw new Exception(print_r($car_info->getFirstErrors(),true));
                        }

                        $b_info = CarBT::findOne(['id'=>$car_info->id]);
                        if(!$b_info) {
                            $b_info = new CarBT(false);
                            $b_info->id = $car_info->id;
                            $b_info->user_id = 0;
                            if(!$b_info->save(false)) {
                                throw new Exception(print_r($b_info->getFirstErrors(),true));
                            }
                        } else {
                            $b_info->user_id = 0;
                            if(!$b_info->save(false)) {
                                throw new Exception(print_r($b_info->getFirstErrors(),true));
                            }
                            $this->addLog($car_info->id,'从B库回收成未分配状态',1);
                        }
                        $this->addLog($car_info->id,'从A库分配到B库',1);
                    }
                }

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

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }
    //批量A库到B库
    public function actionABAll()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        $data = $this->getAQuery($request);

        $query = $data['query'];
//        $query->andWhere('location=1');

        $tran = CarT::getDb()->beginTransaction();
        try {
            foreach($query->each(1000) as $car_info) {
                if($car_info->location == 1) {
                    $car_info->location = 2;
                    $car_info->is_xubao = 0;
                    if(!$car_info->save(false)) {
                        throw new Exception(print_r($car_info->getFirstErrors(),true));
                    }

                    $b_info = CarBT::findOne(['id'=>$car_info->id]);
                    if(!$b_info) {
                        $b_info = new CarBT(false);
                        $b_info->id = $car_info->id;
                        $b_info->user_id = 0;
                        if(!$b_info->save(false)) {
                            throw new Exception(print_r($b_info->getFirstErrors(),true));
                        }
                    } else {
                        $b_info->user_id = 0;
                        if(!$b_info->save(false)) {
                            throw new Exception(print_r($b_info->getFirstErrors(),true));
                        }
                        $this->addLog($car_info->id,'从B库回收成未分配状态',1);
                    }
                    $this->addLog($car_info->id,'从A库分配到B库',1);
                }
            }

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

            $tran->commit();
        } catch (\Exception $e) {
            $tran->rollBack();
            $result['msg'] = $e->getMessage();
        }
        return $result;
    }
    //钩选A库到C库
    public function actionAC()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $ids = explode(',', $request->post('ids'));
            if (count($ids) == 0) {
                $result['msg'] = '请先钩选车辆';
                return $result;
            }

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

                        $c_info = CarCT::findOne(['id'=>$car_info->id]);
                        if(!$c_info) {
                            $c_info = new CarCT(false);
                            $c_info->id = $car_info->id;
                            $c_info->user_id = 0;
                            if(!$c_info->save(false)) {
                                throw new Exception(print_r($c_info->getFirstErrors(),true));
                            }
                        } else {
                            $c_info->user_id = 0;
                            if(!$c_info->save(false)) {
                                throw new Exception(print_r($c_info->getFirstErrors(),true));
                            }
                            $this->addLog($car_info->id,'从C库回收成未分配状态',1);
                        }
                        $this->addLog($car_info->id,'从A库分配到C库',1);
                    }
                }

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

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

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

        if($request->isPost) {
            $ids = explode(',',$request->post('ids'));
            $invalid_id = $request->post('invalid_id',0);
            if($invalid_id == 0) {
                $result['msg'] = '请选择无效理由';
                return $result;
            }
            if($ids[0] == '') {
                $result['msg'] = '请先钩选车辆';
                return $result;
            }

            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($ids as $id) {
                    $car_info = CarT::findOne(['id'=>$id]);
                    if($car_info->location == 1) {
                        $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));
                            }
                        }
                        $this->addLog($car_info->id,'从A库移动到无效库',1);
                    }
                }

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

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

    //B库
    //获取搜索条件
    private function getBQuery($request)
    {
        if($request->isPost) {
            $car_man = $request->post('car_man');
            $phone = $request->post('phone');
            $car_no = $request->post('car_no');
            $register_begin = $request->post('register_begin');
            $register_end = $request->post('register_end');
            $insurer1_begin = $request->post('insurer1_begin');
            $insurer1_end = $request->post('insurer1_end');
            $insurer1_month = $request->post('insurer1_date');
            $insurer1_day = $request->post('insurer1_day');
            $insurer1_month1 = $request->post('insurer1_date1');
            $insurer1_day1 = $request->post('insurer1_day1');
            $username = $request->post('username');
            $status = $request->post('status');
            $sort_key = $request->post('sort_key');
            $sort_value = $request->post('sort_value');
            $company = $request->post('company');
            $clean_right = $request->post('clean_right');

        } else {
            $car_man = $request->get('car_man');
            $phone = $request->get('phone');
            $car_no = $request->get('car_no');
            $register_begin = $request->get('register_begin');
            $register_end = $request->get('register_end');
            $insurer1_begin = $request->get('insurer1_begin');
            $insurer1_end = $request->get('insurer1_end');
            $insurer1_month = $request->get('insurer1_date');
            $insurer1_day = $request->get('insurer1_day');
            $insurer1_month1 = $request->get('insurer1_date1');
            $insurer1_day1 = $request->get('insurer1_day1');
            $username = $request->get('username');
            $status = $request->get('status');
            $sort_key = $request->get('sort_key');
            $sort_value = $request->get('sort_value');
            $company = $request->get('company');
            $clean_right = $request->get('clean_right');
        }
        $query = CarBT::find()
            ->leftJoin(CarT::tableName(),'`car_t`.`id`=`car_b_t`.`id`');

        if($car_man != '') {
            $query->andWhere('car_t.car_man like "'.$car_man.'"');
        }
        if($phone != '') {
            $query->andWhere('car_t.car_man_phone=:phone or car_t.id_man_phone=:phone',[':phone'=>$phone]);
        }
        if($car_no != '') {
            if($car_no == '非京'){
                $query->andWhere('car_no not like "京%"');
            }else{
                $query->andWhere('car_no like "'.$car_no.'%"');
            }
        }
        if($register_begin != '') {
            $query->andWhere('car_t.register_date>="'.$register_begin.'"');
        }
        if($register_end != '') {
            $query->andWhere('car_t.register_date<="'.$register_end.'"');
        }
        if($insurer1_begin != '') {
            $query->andWhere('car_t.insurer1_date>="'.$insurer1_begin.'"');
        }
        if($insurer1_end != '') {
            $query->andWhere('car_t.insurer1_date<="'.$insurer1_end.'"');
        }
        if($status == 1) {
            $query->andWhere('car_b_t.user_id=0');
        }
        if($status == 2) {
            $query->andWhere('car_b_t.user_id>0');
        }
        if($username != '') {
            $user_info = UserT::findOne(['username'=>$username]);
            if($user_info) {
                $query->andWhere('car_b_t.user_id='.$user_info->id);
            }
        }
        if($company != '') {
            $query->andWhere('company like "'.$company.'%"');
        }
        $query = $query->orderBy($sort_key.' '.$sort_value.', car_b_t.id '.$sort_value);
        return ['query'=>$query];
    }
    //B库列表页
    public function actionBIndex()
    {
        $user_items = $this->my->getChildren();
        $invalid_items = InvalidT::getTree();
        return $this->render('b-index',[
            'user_items' => $user_items,
            'invalid_items' => $invalid_items
        ]);
    }
    //B库列表数据
    public function actionBIndexJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $data = $this->getBQuery($request);

        $query = $data['query'];
//        $query->andWhere('location=1');

        $total = $query->count();

        $query->orderBy('id desc');
        $query = $query->offset($offset)->limit($limit);
//        echo $query->createCommand()->rawSql;
        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $car_info = $item->car;
            if(!$car_info) continue;
            $row = $car_info->toArray();
            $row['factory_model'] = MyLib::substr_cut($car_info->factory_model, 8);
            $row['car_man'] = MyLib::substr_cut($car_info->car_man, 8);
            $row['op_user'] = $item->user?$item->user->getShowName():'';
            $data['rows'][] = $row;
        }
        return $data;
    }
    //勾选B库分配
    public function actionBAssign()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $ids = explode(',',$request->post('ids'));
            $user_id = $request->post('user_id',0);
            //针对数据处理的数据
            if($user_id == 0) {
                $result['msg'] = '请先选择分配给哪个业务员';
                return $result;
            }
            if($ids[0] == '') {
                $result['msg'] = '请先钩选车辆';
                return $result;
            }
            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($ids as $id) {
                    $b_info = CarBT::findOne(['id'=>$id]);
                    if($b_info->user_id > 0) {
                        continue;
                    }
                    $b_info->user_id = $user_id;
                    if(!$b_info->save()) {
                        throw new \Exception(print_r($b_info->getErrors(),true));
                    }

                    //添加保单
                    $order_row = new OrderT();
                    $order_row->car_id = $b_info->id;
                    $order_row->car_no = $b_info->car->car_no;
                    $order_row->engine_no = $b_info->car->engine_no;
                    $order_row->car_frame_no = $b_info->car->car_frame_no;
                    $order_row->car_man = $b_info->car->car_man;
                    $order_row->car_man_number = $b_info->car->car_man_number;
                    $order_row->car_man_phone = $b_info->car->car_man_phone;
                    $order_row->user_id = $user_id;
                    $order_row->status_id = 1;
                    $order_row->id_man = $b_info->car->car_man;
                    $order_row->id_man_number = $b_info->car->id_man_number;
                    $order_row->link_man = $b_info->car->car_man;
                    $order_row->link_man_phone = $b_info->car->car_man_phone;
                    $order_row->link_man_number = $b_info->car->id_man_number;
                    if(!$order_row->save()) {
                        throw new \Exception(print_r($order_row->getErrors(),true));
                    }

                    //添加保单操作员
                    $order_user_info = new OrderUserT();
                    $order_user_info->user_id = $user_id;
                    $order_user_info->order_id = $order_row->id;
                    $order_user_info->type_id = 1;
                    $order_user_info->status = 0;
                    if(!$order_user_info->save()) {
                        throw new \Exception(print_r($order_user_info->getErrors(),true));
                    }

                    //添加预约
                    AppointmentT::deleteAll('car_id='.$b_info->id);
                    $row = new AppointmentT();
                    $row->car_id = $b_info->id;
                    $row->user_id = $user_id;
                    $row->pdate = date('Y-m-d');
                    $row->ptype = 0;
                    $row->ptime = '09:00';
                    $row->remark = '首次分配';
                    $row->is_first = 1;
                    $row->xdate = date('Y-m-d');
                    $row->xtime = '09:00';
                    $row->xbao = 2;
                    if(!$row->save()) {
                        throw new \Exception(print_r($row->getErrors(),true));
                    }

                    //添加历史预约
                    $h_row = new AppointmentHistoryT();
                    $h_row->car_id = $b_info->id;
                    $h_row->user_id = $user_id;
                    $h_row->pdate = date('Y-m-d');
                    $h_row->ptype = 0;
                    $h_row->ptime = '09:00';
                    $h_row->remark = '首次分配';
                    $h_row->xdate = date('Y-m-d');
                    $h_row->xtime = '09:00';
                    $h_row->xbao = 2;
                    if(!$h_row->save()) {
                        throw new \Exception(print_r($h_row->getErrors(),true));
                    }

                    $this->addLog($b_info->id,'从B库分配数据给业务员:'.$b_info->user->getShowName(),1);
                }
                $result['success'] = true;
                $result['msg'] = '操作成功';

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }
    //勾选B库回收
    public function actionBReturn()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $ids = explode(',',$request->post('ids'));
            if($ids[0] == '') {
                $result['msg'] = '请先钩选需要操作的车辆';
                return $result;
            }
            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($ids as $id) {
                    $b_info = CarBT::findOne(['id'=>$id]);
                    $this->addLog($b_info->id,'从B库业务手中回收数据',1);

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

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

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }
    //批量B库分配
    public function actionBAllAssign()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $status = $request->post('status');
            $assign_users = explode(',',$request->post('assign_users'));
            $assign_count = $request->post('assign_count',0);
            $assign_user_ids = array();
            foreach($assign_users as $assign_user) {
                $user_info = UserT::findOne(['username'=>$assign_user,'is_delete'=>0]);
                if($user_info)
                    $assign_user_ids[] = $user_info->id;
            }
            if(count($assign_user_ids) == 0) {
                $result['msg'] = '请输入业务员工号,以英文逗号间隔';
                return $result;
            }
            if($assign_count == 0) {
                $result['msg'] = '请输入每个业务员分配记录数';
                return $result;
            }

            $data = $this->getBQuery($request);
            $query = $data['query'];
//            var_dump($query);
//            echo $query->createCommand()->rawSql;
//            echo $query->count();
//            exit;
            $tran = CarT::getDb()->beginTransaction();
            try {
                $page = 0;
                $total_pages = count($assign_user_ids);
                $index = 0;
                foreach($query->each(100) as $b_info) {
                    if($index >= ($page+1) * $assign_count) $page += 1;
                    if($page == $total_pages) break;
                    if($b_info->user_id > 0) continue;
                    $b_info->user_id = $assign_user_ids[$page];
                    if(!$b_info->save()) {
                        throw new \Exception(print_r($b_info->getErrors(),true));
                    }

                    $car_info = $b_info->car;
                    $car_info->op_user1 = $b_info->user->getShowName();
                    if(!$car_info->save(false)) {
                        throw new \Exception(print_r($car_info->getErrors(), true));
                    }

                    //添加保单
                    $order_row = new OrderT();
                    $order_row->car_id = $b_info->id;
                    $order_row->car_no = $b_info->car->car_no;
                    $order_row->engine_no = $b_info->car->engine_no;
                    $order_row->car_frame_no = $b_info->car->car_frame_no;
                    $order_row->car_man = $b_info->car->car_man;
                    $order_row->user_id = $b_info->user_id;
                    $order_row->status_id = 1;
                    $order_row->id_man = $b_info->car->car_man;
                    $order_row->link_man = $b_info->car->car_man;
                    $order_row->link_man_phone = $b_info->car->car_man_phone;
                    $order_row->link_man_number = $b_info->car->id_man_number;
                    $order_row->return_status_id = 0;
                    $order_row->return_remark = '';
                    if(!$order_row->save()) {
                        throw new \Exception(print_r($order_row->getErrors(),true));
                    }

                    //添加预约
                    AppointmentT::deleteAll('car_id='.$b_info->id);
                    $row = new AppointmentT();
                    $row->car_id = $b_info->id;
                    $row->user_id = $b_info->user_id;
                    $row->pdate = date('Y-m-d');
                    $row->ptime = '09:00';
                    $row->ptype = 0;
                    $row->remark = '首次分配';
                    $row->is_first = 1;
                    $row->xdate = date('Y-m-d');
                    $row->xtime = '09:00';
                    $row->xbao = 2;
                    if(!$row->save()) {
                        throw new \Exception(print_r($row->getErrors(),true));
                    }

                    //添加历史预约
                    $h_row = new AppointmentHistoryT();
                    $h_row->car_id = $b_info->id;
                    $h_row->user_id = $b_info->user_id;
                    $h_row->pdate = date('Y-m-d');
                    $h_row->ptime = '09:00';
                    $h_row->ptype = 0;
                    $h_row->remark = '首次分配';
                    $h_row->xdate = date('Y-m-d');
                    $h_row->xtime = '09:00';
                    $h_row->xbao = 2;
                    if(!$h_row->save()) {
                        throw new \Exception(print_r($h_row->getErrors(),true));
                    }

                    $this->addLog($b_info->id,'从B库分配数据给业务员:'.$b_info->user->getShowName(),1);
                    $index++;
                }
                $result['success'] = true;
                $result['msg'] = '操作成功';

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }
    //批量B库回收
    public function actionBReturnAllA()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {

            $status = $request->post('status');
            $register_begin = $request->post('register_begin');
            $register_end = $request->post('register_end');
            $insurer1_begin = $request->post('insurer1_begin');
            $insurer1_end = $request->post('insurer1_end');

            $query = CarBT::find()
                ->leftJoin('car_t','`car_t`.`id`=`car_b_t`.`id`');

            if($register_begin != '') {
                $query->andWhere('car_t.register_date>="'.$register_begin.'"');
            }
            if($register_end != '') {
                $query->andWhere('car_t.register_date<="'.$register_end.'"');
            }
            if($insurer1_begin != '') {
                $query->andWhere('car_t.insurer1_date>="'.$insurer1_begin.'"');
            }
            if($insurer1_end != '') {
                $query->andWhere('car_t.insurer1_end<="'.$insurer1_end.'"');
            }
            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($query->each(1000) as $item) {
                    //删除预约
                    AppointmentT::deleteAll('car_id='.$item->id);

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

                    $item->user_id = 0;
                    $item->save();
//            FiltrationT
                    //删除预约拨打
//                    FiltrationT::deleteAll('car_id='.$c_info->id);
                    $this->addLog($item->id,'从B库业务员手中批量回收数据',1);
                }

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

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }
    //钩选B库到无效库
    public function actionBInvalid()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $ids = explode(',',$request->post('ids'));
            $invalid_id = $request->post('invalid_id',0);
            if($invalid_id == 0) {
                $result['msg'] = '请选择无效理由';
                return $result;
            }
            if($ids[0] == '') {
                $result['msg'] = '请先钩选车辆';
                return $result;
            }

            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($ids as $id) {
                    $car_info = CarT::findOne(['id'=>$id]);
                    if($car_info->location == 2) {
                        $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));
                            }
                        }

                        $b_info = CarBT::findOne(['id'=>$id]);
                        if($b_info) {
                            if($b_info->user_id > 0) {
                                //删除预约
                                AppointmentT::deleteAll('car_id='.$b_info->id);

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

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

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

    //C库
    //C库列表页
    private function getCQuery($request)
    {
        if($request->isPost) {
            $car_man = $request->post('car_man');
            $phone = $request->post('phone');
            $car_no = $request->post('car_no');
            $print_begin = $request->post('print_begin');
            $print_end = $request->post('print_end');
            $insurer1_begin = $request->post('insurer1_begin');
            $insurer1_end = $request->post('insurer1_end');
            $insurer1_month = $request->post('insurer_month_begin');
            $insurer1_day = $request->post('insurer_day_begin');
            $insurer1_month1 = $request->post('insurer_month_end');
            $insurer1_day1 = $request->post('insurer_day_end');

            $status = $request->post('status');
            $username = $request->post('username');
            $sort_key = $request->post('sort_key');
            $sort_value = $request->post('sort_value');
            $old_user = $request->post('old_user');
            $company = $request->post('company');
            $user1 = $request->post('user1');
            $clean_right = $request->post('clean_right');
        } else {
            $car_man = $request->get('car_man');
            $phone = $request->get('phone');
            $car_no = $request->get('car_no');
            $print_begin = $request->get('print_begin');
            $print_end = $request->get('print_end');
            $insurer1_begin = $request->get('insurer1_begin');
            $insurer1_end = $request->get('insurer1_end');
            $insurer1_month = $request->get('insurer_month_begin');
            $insurer1_day = $request->get('insurer_day_begin');
            $insurer1_month1 = $request->get('insurer_month_end');
            $insurer1_day1 = $request->get('insurer_day_end');

            $status = $request->get('status');
            $username = $request->get('username');
            $sort_key = $request->get('sort_key');
            $sort_value = $request->get('sort_value');
            $old_user = $request->get('old_user');
            $company = $request->get('company');
            $user1 = $request->get('user1');
            $clean_right = $request->get('clean_right');
        }
        $query = CarCT::find()
            ->leftJoin(CarT::tableName(),'`car_t`.`id`=`car_c_t`.`id`');

        if($car_man != '') {
            $query->andWhere('car_t.car_man like "'.$car_man.'"');
        }
        if($phone != '') {
            $query->andWhere('car_t.car_man_phone=:phone or car_t.id_man_phone=:phone',[':phone'=>$phone]);
        }
        if($car_no != '') {
            $query->andWhere('car_t.car_no like "'.$car_no.'"');
        }
        if($print_begin != '') {
            $query->andWhere('car_t.print_date>="'.$print_begin.'"');
        }
        if($print_end != '') {
            $query->andWhere('car_t.print_date<="'.$print_end.'"');
        }
        if($insurer1_begin != '') {
            $query->andWhere('car_t.insurer1_date>="'.$insurer1_begin.'"');
        }
        if($insurer1_end != '') {
            $query->andWhere('car_t.insurer1_date<="'.$insurer1_end.'"');
        }
        if($insurer1_month != '' && $insurer1_day == '') {
            $query = $query->andWhere('month(car_t.insurer1_date)>="'.$insurer1_month.'"');
        } else if ($insurer1_month == '' && $insurer1_day != '') {
            $query = $query->andWhere('day(car_t.insurer1_date)>="'.$insurer1_day.'"');
        } else if ($insurer1_month != '' && $insurer1_day != '') {
            $query = $query->andWhere('DATE_FORMAT(car_t.insurer1_date,"%m-%d") >= "' . substr('0' . $insurer1_month, -2) . '-' . substr('0' . $insurer1_day, -2) . '"');
        }
        if($insurer1_month1 != '' && $insurer1_day1 == '') {
            $query = $query->andWhere('month(car_t.insurer1_date) <="'.$insurer1_month1.'"');
        } else if ($insurer1_month1 == '' && $insurer1_day1 != '') {
            $query = $query->andWhere('day(car_t.insurer1_date) <="'.$insurer1_day1.'"');
        } else if ($insurer1_month1 != '' && $insurer1_day1 != '') {
            $query = $query->andWhere('DATE_FORMAT(car_t.insurer1_date,"%m-%d") <= "' . substr('0' . $insurer1_month1, -2) . '-' . substr('0' . $insurer1_day1, -2) . '"');
        }

        if($status == 1) {
            $query->andWhere('car_c_t.user_id=0');
        }
        if($status == 2) {
            $query->andWhere('car_c_t.user_id>0');
        }
        if($username != '') {
            $user_info = UserT::findOne(['username'=>$username]);
            if($user_info) {
                $query->andWhere('car_c_t.user_id='.$user_info->id);
            }
        }
        if($old_user != '') {
            $query->andWhere('car_t.old_user="'.$old_user.'"');
        }
        if($company != '') {
            $query->andWhere('company like"'.$company.'%"');
        }
        if($user1 != '') {
            $query->andWhere('op_user1 like "'.$user1.'%"');
        }
        if($clean_right != '') {
            $query->andWhere('car_t.clean_right="'.$clean_right.'"');
        }
        $query->orderBy($sort_key.' '.$sort_value.', car_c_t.id '.$sort_value);
        return ['query'=>$query];
    }
    public function actionCIndex()
    {
        $user_items = $this->my->getChildren();
        $invalid_items = InvalidT::getTree();
        return $this->render('c-index',[
            'user_items' => $user_items,
            'invalid_items' => $invalid_items
        ]);
    }
    public function actionCIndexJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $data = $this->getCQuery($request);
        $query = $data['query'];
//        $query->andWhere('location=1');

        $total = $query->count();

        $query->orderBy('id desc');
        $query = $query->offset($offset)->limit($limit);
        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $car_info = $item->car;
            if(!$car_info) continue;
            $row = $car_info->toArray();
            $row['factory_model'] = MyLib::substr_cut($car_info->factory_model, 8);
            $row['car_man'] = MyLib::substr_cut($car_info->car_man, 8);
            $row['op_user'] = $item->user?$item->user->getShowName():'';
            $data['rows'][] = $row;
        }
        return $data;
    }
    public function actionCAssign()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $ids = explode(',',$request->post('ids'));
            $user_id = $request->post('user_id',0);
            //针对数据处理的数据
            if($user_id == 0) {
                $result['msg'] = '请先选择分配给哪个业务员';
                return $result;
            }
            if($ids[0] == '') {
                $result['msg'] = '请先钩选车辆';
                return $result;
            }
            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($ids as $id) {
                    $c_info = CarCT::findOne(['id'=>$id]);
                    if($c_info->user_id > 0) {
                        continue;
                    }
                    $c_info->user_id = $user_id;
                    if(!$c_info->save()) {
                        throw new \Exception(print_r($c_info->getErrors(),true));
                    }

                    //添加保单
                    $order_row = new OrderT();
                    $order_row->car_id = $c_info->id;
                    $order_row->car_no = $c_info->car->car_no;
                    $order_row->engine_no = $c_info->car->engine_no;
                    $order_row->car_frame_no = $c_info->car->car_frame_no;
                    $order_row->car_man = $c_info->car->car_man;
                    $order_row->car_man_number = $c_info->car->car_man_number;
                    $order_row->car_man_phone = $c_info->car->car_man_phone;
                    $order_row->user_id = $user_id;
                    $order_row->status_id = 1;
                    $order_row->id_man = $c_info->car->car_man;
                    $order_row->id_man_number = $c_info->car->id_man_number;
                    $order_row->link_man = $c_info->car->car_man;
                    $order_row->link_man_phone = $c_info->car->car_man_phone;
                    $order_row->link_man_number = $c_info->car->id_man_number;
                    if(!$order_row->save()) {
                        throw new \Exception(print_r($order_row->getErrors(),true));
                    }

                    //添加保单操作员
                    $order_user_info = new OrderUserT();
                    $order_user_info->user_id = $user_id;
                    $order_user_info->order_id = $order_row->id;
                    $order_user_info->type_id = 1;
                    $order_user_info->status = 0;
                    if(!$order_user_info->save()) {
                        throw new \Exception(print_r($order_user_info->getErrors(),true));
                    }

                    //添加预约
                    AppointmentT::deleteAll('car_id='.$c_info->id);
                    $row = new AppointmentT();
                    $row->car_id = $c_info->id;
                    $row->user_id = $user_id;
                    $row->pdate = date('Y-m-d');
                    $row->ptype = 0;
                    $row->ptime = '09:00';
                    $row->remark = '首次分配';
                    $row->is_first = 1;
                    $row->xdate = date('Y-m-d');
                    $row->xtime = '09:00';
                    $row->xbao = 2;
                    if(!$row->save()) {
                        throw new \Exception(print_r($row->getErrors(),true));
                    }

                    //添加历史预约
                    $h_row = new AppointmentHistoryT();
                    $h_row->car_id = $c_info->id;
                    $h_row->user_id = $user_id;
                    $h_row->pdate = date('Y-m-d');
                    $h_row->ptype = 0;
                    $h_row->ptime = '09:00';
                    $h_row->remark = '首次分配';
                    $h_row->xdate = date('Y-m-d');
                    $h_row->xtime = '09:00';
                    $h_row->xbao = 2;
                    if(!$h_row->save()) {
                        throw new \Exception(print_r($h_row->getErrors(),true));
                    }

                    $this->addLog($c_info->id,'从C库分配数据给业务员:'.$c_info->user->getShowName(),1);
                }
                $result['success'] = true;
                $result['msg'] = '操作成功';

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

        if($request->isPost) {
            $ids = explode(',',$request->post('ids'));

            if($ids[0] == '') {
                $result['msg'] = '请先钩选车辆';
                return $result;
            }
            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($ids as $id) {
                    $c_info = CarCT::findOne(['id'=>$id]);
                    if($c_info->user_id > 0)
                        $this->addLog($c_info->id,'从业务员:'.$c_info->user->getShowName().'回收数据',1);
                    //删除预约
                    AppointmentT::deleteAll('user_id='.$c_info->user_id.' and car_id='.$c_info->id);
                    $orders = OrderT::find()
                        ->where('car_id='.$c_info->id.' and status_id<5')
                        ->all();
                    foreach($orders as $order_info) {
                        OrderUserT::deleteAll('order_id='.$order_info->id);
                        //删除保单
                        $order_info->delete();
                    }

                    $car_info = $c_info->car;
                    $car_info->user_id = 0;
                    if(!$car_info->save()) {
                        throw new \Exception(print_r($car_info->getErrors(),true));
                    }

                    $c_info->user_id = 0;
                    if(!$c_info->save()) {
                        throw new \Exception(print_r($c_info->getErrors(),true));
                    }
                }
                $result['success'] = true;
                $result['msg'] = '操作成功';

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

        if($request->isPost) {
            $status = $request->post('status');
            $assign_users = explode(',',$request->post('assign_users'));
            $assign_count = $request->post('assign_count',0);
            $assign_user_ids = array();
            foreach($assign_users as $assign_user) {
                $user_info = UserT::findOne(['username'=>$assign_user,'is_delete'=>0]);
                if($user_info)
                    $assign_user_ids[] = $user_info->id;
            }
            if(count($assign_user_ids) == 0) {
                $result['msg'] = '请输入业务员工号,以英文逗号间隔';
                return $result;
            }
            if($assign_count == 0) {
                $result['msg'] = '请输入每个业务员分配记录数';
                return $result;
            }

            $data = $this->getCQuery($request);
            $query = $data['query'];
//            var_dump($query);
//            echo $query->createCommand()->rawSql;
//            echo $query->count();
//            exit;
            $tran = CarT::getDb()->beginTransaction();
            try {
                $page = 0;
                $total_pages = count($assign_user_ids);
                $index = 0;
                foreach($query->each(100) as $c_info) {
                    if($index >= ($page+1) * $assign_count) $page += 1;
                    if($page == $total_pages) break;
                    if($c_info->user_id > 0) continue;
                    $c_info->user_id = $assign_user_ids[$page];
                    if(!$c_info->save()) {
                        throw new \Exception(print_r($c_info->getErrors(),true));
                    }

                    $car_info = $c_info->car;
                    $car_info->op_user1 = $c_info->user->getShowName();
                    if(!$car_info->save(false)) {
                        throw new \Exception(print_r($car_info->getErrors(), true));
                    }

                    //添加保单
                    $order_row = new OrderT();
                    $order_row->car_id = $c_info->id;
                    $order_row->car_no = $c_info->car->car_no;
                    $order_row->engine_no = $c_info->car->engine_no;
                    $order_row->car_frame_no = $c_info->car->car_frame_no;
                    $order_row->car_man = $c_info->car->car_man;
                    $order_row->car_man_number = $c_info->car->car_man_number;
                    $order_row->car_man_phone = $c_info->car->car_man_phone;
                    $order_row->user_id = $c_info->user_id;
                    $order_row->status_id = 1;
                    $order_row->id_man = $c_info->car->car_man;
                    $order_row->id_man_number = $c_info->car->id_man_number;
                    $order_row->link_man = $c_info->car->car_man;
                    $order_row->link_man_phone = $c_info->car->car_man_phone;
                    $order_row->link_man_number = $c_info->car->id_man_number;
                    if(!$order_row->save()) {
                        throw new \Exception(print_r($order_row->getErrors(),true));
                    }

                    //添加保单操作员
                    $order_user_info = new OrderUserT();
                    $order_user_info->user_id = $c_info->user_id;
                    $order_user_info->order_id = $order_row->id;
                    $order_user_info->type_id = 1;
                    $order_user_info->status = 0;
                    if(!$order_user_info->save()) {
                        throw new \Exception(print_r($order_user_info->getErrors(),true));
                    }

                    //添加预约
                    AppointmentT::deleteAll('car_id='.$c_info->id);
                    $row = new AppointmentT();
                    $row->car_id = $c_info->id;
                    $row->user_id = $c_info->user_id;
                    $row->pdate = date('Y-m-d');
                    $row->ptype = 0;
                    $row->ptime = '09:00';
                    $row->remark = '首次分配';
                    $row->is_first = 1;
                    $row->xdate = date('Y-m-d');
                    $row->xtime = '09:00';
                    $row->xbao = 2;
                    if(!$row->save()) {
                        throw new \Exception(print_r($row->getErrors(),true));
                    }

                    //添加历史预约
                    $h_row = new AppointmentHistoryT();
                    $h_row->car_id = $c_info->id;
                    $h_row->user_id = $c_info->user_id;
                    $h_row->pdate = date('Y-m-d');
                    $h_row->ptype = 0;
                    $h_row->ptime = '09:00';
                    $h_row->remark = '首次分配';
                    $h_row->xdate = date('Y-m-d');
                    $h_row->xtime = '09:00';
                    $h_row->xbao = 2;
                    if(!$h_row->save()) {
                        throw new \Exception(print_r($h_row->getErrors(),true));
                    }

                    $this->addLog($c_info->id,'从C库分配数据给业务员:'.$c_info->user->getShowName(),1);
                    $index++;
                }
                $result['success'] = true;
                $result['msg'] = '操作成功';

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

        if($request->isPost) {

            $status = $request->post('status');
            $register_begin = $request->post('register_begin');
            $register_end = $request->post('register_end');
            $insurer1_begin = $request->post('insurer1_begin');
            $insurer1_end = $request->post('insurer1_end');

            $query = CarCT::find()
                ->leftJoin('car_t','`car_t`.`id`=`car_c_t`.`id`');

            if($register_begin != '') {
                $query->andWhere('car_t.register_date>="'.$register_begin.'"');
            }
            if($register_end != '') {
                $query->andWhere('car_t.register_date<="'.$register_end.'"');
            }
            if($insurer1_begin != '') {
                $query->andWhere('car_t.insurer1_date>="'.$insurer1_begin.'"');
            }
            if($insurer1_end != '') {
                $query->andWhere('car_t.insurer1_end<="'.$insurer1_end.'"');
            }
            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($query->each(1000) as $item) {
                    //删除预约
                    AppointmentT::deleteAll('car_id='.$item->id);

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

                    $item->user_id = 0;
                    if(!$item->save()) {
                        throw new \Exception(print_r($item->getErrors(), true));
                    }
//            FiltrationT
                    //删除预约拨打
//                    FiltrationT::deleteAll('car_id='.$c_info->id);
                    $this->addLog($item->id,'从C库业务员手中批量回收数据',1);
                }

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

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

        if($request->isPost) {
            $ids = explode(',',$request->post('ids'));
            if(count($ids) == 0) {
                $result['msg'] = '请先钩选车辆';
                return $result;
            }

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

                        CarCT::deleteAll(['id'=>$car_info->id]);
                        $d_info = CarDT::findOne(['id'=>$car_info->id]);
                        if(!$d_info) {
                            $d_info = new CarDT(false);
                            $d_info->id = $car_info->id;
                            $d_info->user_id = 0;
                            if(!$d_info->save(false)) {
                                throw new Exception(print_r($d_info->getFirstErrors(),true));
                            }
                        } else {
                            $d_info->user_id = 0;
                            if(!$d_info->save(false)) {
                                throw new Exception(print_r($d_info->getFirstErrors(),true));
                            }
                            $this->addLog($car_info->id,'从D库回收成未分配状态',1);
                        }
                        $this->addLog($car_info->id,'从C库分配到D库',1);
                    }
                }

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

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

        if($request->isPost) {
            $data = $this->getCQuery($request);
            $query = $data['query'];
            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($query->each(100) as $c_info) {
                    $car_info = $c_info->car;
                    if($car_info->location == 3) {
                        $car_info->location = 4;
                        if(!$car_info->save(false)) {
                            throw new Exception(print_r($car_info->getFirstErrors(),true));
                        }

                        CarCT::deleteAll(['id'=>$car_info->id]);
                        $d_info = CarDT::findOne(['id'=>$car_info->id]);
                        if(!$d_info) {
                            $d_info = new CarDT(false);
                            $d_info->id = $car_info->id;
                            $d_info->user_id = 0;
                            if(!$d_info->save(false)) {
                                throw new Exception(print_r($d_info->getFirstErrors(),true));
                            }
                        } else {
                            $d_info->user_id = 0;
                            if(!$d_info->save(false)) {
                                throw new Exception(print_r($d_info->getFirstErrors(),true));
                            }
                            $this->addLog($car_info->id,'从D库回收成未分配状态',1);
                        }
                        $this->addLog($car_info->id,'从C库分配到D库',1);
                    }
                }
                $result['success'] = true;
                $result['msg'] = '操作成功';

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }
    //钩选C库到无效库
    public function actionCInvalid()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $ids = explode(',',$request->post('ids'));
            $invalid_id = $request->post('invalid_id',0);
            if($invalid_id == 0) {
                $result['msg'] = '请选择无效理由';
                return $result;
            }
            if($ids[0] == '') {
                $result['msg'] = '请先钩选车辆';
                return $result;
            }

            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($ids as $id) {
                    $car_info = CarT::findOne(['id'=>$id]);
                    if($car_info->location == 3) {
                        $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));
                            }
                        }

                        $c_info = CarCT::findOne(['id'=>$id]);
                        if($c_info) {
                            if($c_info->user_id > 0) {
                                //删除预约
                                AppointmentT::deleteAll('car_id='.$c_info->id);

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

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

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

    //D库
    //D库列表页
    private function getDQuery($request)
    {
        if($request->isPost) {
            $car_man = $request->post('car_man');
            $phone = $request->post('phone');
            $car_no = $request->post('car_no');
            $insurer1_begin = $request->post('insurer1_begin');
            $insurer1_end = $request->post('insurer1_end');
            $insurer1_month = $request->post('insurer_month_begin');
            $insurer1_day = $request->post('insurer_day_begin');
            $insurer1_month1 = $request->post('insurer_month_end');
            $insurer1_day1 = $request->post('insurer_day_end');
            $status = $request->post('status');
            $username = $request->post('username');
            $sort_key = $request->post('sort_key');
            $sort_value = $request->post('sort_value');
            $old_user = $request->post('old_user');
            $user1 = $request->post('user1');
            $user2 = $request->post('user2');
            $company = $request->post('company');
        } else {
            $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');
            $insurer1_month = $request->get('insurer_month_begin');
            $insurer1_day = $request->get('insurer_day_begin');
            $insurer1_month1 = $request->get('insurer_month_end');
            $insurer1_day1 = $request->get('insurer_day_end');
            $status = $request->get('status');
            $username = $request->get('username');
            $sort_key = $request->get('sort_key');
            $sort_value = $request->get('sort_value');
            $old_user = $request->get('old_user');
            $user1 = $request->get('user1');
            $user2 = $request->get('user2');
            $company = $request->get('company');
        }
        $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['insurer1_month'] = $insurer1_month;
        $params['insurer1_day'] = $insurer1_day;
        $params['insurer1_month1'] = $insurer1_month1;
        $params['insurer1_day1'] = $insurer1_day1;
        $params['status'] = $status;
        $params['username'] = $username;
        $params['sort_key'] = $sort_key;
        $params['sort_value'] = $sort_value;
        $params['old_user'] = $old_user;
        $params['user1'] = $user1;
        $params['user2'] = $user2;
        $params['company'] = $company;

        $query = CarDT::find()
            ->leftJoin(CarT::tableName(),'`car_t`.`id`=`car_d_t`.`id`');
        if($car_man != '') {
            $query->andWhere('car_t.car_man="'.$car_man.'"');
        }
        if($phone != '') {
            $query->andWhere('car_t.car_man_phone=:phone or car_t.id_man_phone=:phone',[':phone'=>$phone]);
        }
        if($car_no != '') {
            $query->andWhere('car_t.car_no like "'.$car_no.'"');
        }
        if($insurer1_begin != '') {
            $query->andWhere('car_t.insurer1_date>="'.$insurer1_begin.'"');
        }
        if($insurer1_end != '') {
            $query->andWhere('car_t.insurer1_date<="'.$insurer1_end.'"');
        }
        if($insurer1_month != '' && $insurer1_day == '') {
            $query = $query->andWhere('month(car_t.insurer1_date)>="'.$insurer1_month.'"');
        } else if ($insurer1_month == '' && $insurer1_day != '') {
            $query = $query->andWhere('day(car_t.insurer1_date)>="'.$insurer1_day.'"');
        } else if ($insurer1_month != '' && $insurer1_day != '') {
            $query = $query->andWhere('DATE_FORMAT(car_t.insurer1_date,"%m-%d") >= "' . substr('0' . $insurer1_month, -2) . '-' . substr('0' . $insurer1_day, -2) . '"');
        }
        if($insurer1_month1 != '' && $insurer1_day1 == '') {
            $query = $query->andWhere('month(car_t.insurer1_date) <="'.$insurer1_month1.'"');
        } else if ($insurer1_month1 == '' && $insurer1_day1 != '') {
            $query = $query->andWhere('day(car_t.insurer1_date) <="'.$insurer1_day1.'"');
        } else if ($insurer1_month1 != '' && $insurer1_day1 != '') {
            $query = $query->andWhere('DATE_FORMAT(car_t.insurer1_date,"%m-%d") <= "' . substr('0' . $insurer1_month1, -2) . '-' . substr('0' . $insurer1_day1, -2) . '"');
        }
        if($status == 1) {
            $query->andWhere('car_d_t.user_id=0');
        }
        if($status == 2) {
            $query = $query->andWhere('car_d_t.user_id>0');
        }
        if($username != '') {
            $user_info = UserT::findOne(['username'=>$username]);
            if($user_info) {
                $query->andWhere('car_d_t.user_id='.$user_info->id);
            }
        }
        if($old_user != '') {
            $query->andWhere('car_t.old_user like "'.$old_user.'%"');
        }
        if($user1 != '') {
            $query->andWhere('car_t.op_user1 like "'.$user1.'%"');
        }
        if($user2 != '') {
            $query->andWhere('car_t.op_user3 like "'.$user2.'%"');
        }
        if($company != '') {
            $query->andWhere('company like "'.$company.'%"');
        }
        $query->orderBy($sort_key.' '.$sort_value.',car_d_t.id '.$sort_value);
        return ['query'=>$query,'params'=>$params];
    }
    public function actionDIndex()
    {
        $user_items = $this->my->getChildren();
        $invalid_items = InvalidT::getTree();
        return $this->render('d-index',[
            'user_items' => $user_items,
            'invalid_items' => $invalid_items
        ]);
    }
    public function actionDIndexJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $data = $this->getDQuery($request);
        $query = $data['query'];
//        $query->andWhere('location=1');
        $total = $query->count();

        $query->orderBy('id desc');
        $query = $query->offset($offset)->limit($limit);
        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $car_info = $item->car;
            if(!$car_info) continue;
            $row = $car_info->toArray();
            $row['factory_model'] = MyLib::substr_cut($car_info->factory_model, 8);
            $row['car_man'] = MyLib::substr_cut($car_info->car_man, 8);
            $row['op_user'] = $item->user?$item->user->getShowName():'';
            $data['rows'][] = $row;
        }
        return $data;
    }
    public function actionDAssign()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $ids = explode(',',$request->post('ids'));
            $user_id = $request->post('user_id',0);
            //针对数据处理的数据
            if($user_id == 0) {
                $result['msg'] = '请先选择分配给哪个业务员';
                return $result;
            }
            if($ids[0] == '') {
                $result['msg'] = '请先钩选车辆';
                return $result;
            }
            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($ids as $id) {
                    $d_info = CarDT::findOne(['id'=>$id]);
                    if($d_info->user_id > 0) {
                        continue;
                    }
                    $d_info->user_id = $user_id;
                    if(!$d_info->save()) {
                        throw new \Exception(print_r($d_info->getErrors(),true));
                    }

                    //添加保单
                    $order_row = new OrderT();
                    $order_row->car_id = $d_info->id;
                    $order_row->car_no = $d_info->car->car_no;
                    $order_row->engine_no = $d_info->car->engine_no;
                    $order_row->car_frame_no = $d_info->car->car_frame_no;
                    $order_row->car_man = $d_info->car->car_man;
                    $order_row->car_man_number = $d_info->car->car_man_number;
                    $order_row->car_man_phone = $d_info->car->car_man_phone;
                    $order_row->user_id = $user_id;
                    $order_row->status_id = 1;
                    $order_row->id_man = $d_info->car->car_man;
                    $order_row->id_man_number = $d_info->car->id_man_number;
                    $order_row->link_man = $d_info->car->car_man;
                    $order_row->link_man_phone = $d_info->car->car_man_phone;
                    $order_row->link_man_number = $d_info->car->id_man_number;
                    if(!$order_row->save()) {
                        throw new \Exception(print_r($order_row->getErrors(),true));
                    }

                    //添加预约
                    AppointmentT::deleteAll('car_id='.$d_info->id);
                    $row = new AppointmentT();
                    $row->car_id = $d_info->id;
                    $row->user_id = $user_id;
                    $row->pdate = date('Y-m-d');
                    $row->ptype = 0;
                    $row->ptime = '09:00';
                    $row->remark = '首次分配';
                    $row->is_first = 1;
                    $row->xdate = date('Y-m-d');
                    $row->xtime = '09:00';
                    $row->xbao = 2;
                    if(!$row->save()) {
                        throw new \Exception(print_r($row->getErrors(),true));
                    }

                    //添加历史预约
                    $h_row = new AppointmentHistoryT();
                    $h_row->car_id = $d_info->id;
                    $h_row->user_id = $user_id;
                    $h_row->pdate = date('Y-m-d');
                    $h_row->ptype = 0;
                    $h_row->ptime = '09:00';
                    $h_row->remark = '首次分配';
                    $h_row->xdate = date('Y-m-d');
                    $h_row->xtime = '09:00';
                    $h_row->xbao = 2;
                    if(!$h_row->save()) {
                        throw new \Exception(print_r($h_row->getErrors(),true));
                    }

                    $this->addLog($d_info->id,'从D库分配数据给业务员:'.$d_info->user->getShowName(),1);
                }
                $result['success'] = true;
                $result['msg'] = '操作成功';

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

        if($request->isPost) {
            $ids = explode(',',$request->post('ids'));

            if($ids[0] == '') {
                $result['msg'] = '请先钩选车辆';
                return $result;
            }
            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($ids as $id) {
                    $d_info = CarDT::findOne(['id'=>$id]);
                    if($d_info->user_id > 0)
                        $this->addLog($d_info->id,'从业务员:'.$d_info->user->getShowName().'回收跟踪数据',1);
                    //删除预约
                    AppointmentT::deleteAll('user_id='.$d_info->user_id.' and car_id='.$d_info->id);
                    $orders = OrderT::find()
                        ->where('car_id='.$d_info->id.' and status_id<5')
                        ->all();
                    foreach($orders as $order_info) {
                        OrderUserT::deleteAll('order_id='.$order_info->id);
                        //删除保单
                        $order_info->delete();
                    }

                    $car_info = $d_info->car;
                    $car_info->user_id = 0;
                    if(!$car_info->save()) {
                        throw new \Exception(print_r($car_info->getErrors(),true));
                    }

                    $d_info->user_id = 0;
                    if(!$d_info->save()) {
                        throw new \Exception(print_r($d_info->getErrors(),true));
                    }
                }
                $result['success'] = true;
                $result['msg'] = '操作成功';

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

        if($request->isPost) {
            $assign_users = explode(',',$request->post('assign_users'));
            $assign_count = $request->post('assign_count',0);
            $assign_user_ids = array();
            foreach($assign_users as $assign_user) {
                $user_info = UserT::findOne(['username'=>$assign_user]);
                if($user_info)
                    $assign_user_ids[] = $user_info->id;
            }
            if(count($assign_user_ids) == 0) {
                $result['msg'] = '请输入业务员工号,以英文逗号间隔';
                return $result;
            }
            if($assign_count == 0) {
                $result['msg'] = '请输入每个业务员分配记录数';
                return $result;
            }

            $data = $this->getDQuery($request);
            $query = $data['query'];
            $tran = CarT::getDb()->beginTransaction();

            try {
                $page = 0;
                $total_pages = count($assign_user_ids);
                $index = 0;
                foreach($query->each(100) as $d_info) {
                    if($index >= ($page+1) * $assign_count) $page += 1;
                    if($page == $total_pages) break;
                    if($d_info->user_id > 0) continue;

                    $d_info->user_id = $assign_user_ids[$page];
                    if(!$d_info->save()) {
                        throw new \Exception(print_r($d_info->getErrors(),true));
                    }

                    $car_info = $d_info->car;
                    $car_info->op_user3 = $d_info->user->getShowName();
                    if(!$car_info->save()) {
                        throw new \Exception(print_r($car_info->getErrors(),true));
                    }

                    //添加保单
                    $order_row = new OrderT();
                    $order_row->car_id = $d_info->id;
                    $order_row->car_no = $d_info->car->car_no;
                    $order_row->engine_no = $d_info->car->engine_no;
                    $order_row->car_frame_no = $d_info->car->car_frame_no;
                    $order_row->car_man = $d_info->car->car_man;
                    $order_row->car_man_number = $d_info->car->car_man_number;
                    $order_row->car_man_phone = $d_info->car->car_man_phone;
                    $order_row->user_id = $d_info->user_id;
                    $order_row->status_id = 1;
                    $order_row->id_man = $d_info->car->car_man;
                    $order_row->id_man_number = $d_info->car->id_man_number;
                    $order_row->link_man = $d_info->car->car_man;
                    $order_row->link_man_phone = $d_info->car->car_man_phone;
                    $order_row->link_man_number = $d_info->car->id_man_number;
                    if(!$order_row->save()) {
                        throw new \Exception(print_r($order_row->getErrors(),true));
                    }

                    //添加保单操作员
                    $order_user_info = new OrderUserT();
                    $order_user_info->user_id = $d_info->user_id;
                    $order_user_info->order_id = $order_row->id;
                    $order_user_info->type_id = 1;
                    $order_user_info->status = 0;
                    if(!$order_user_info->save()) {
                        throw new \Exception(print_r($order_user_info->getErrors(),true));
                    }

                    //添加预约
                    AppointmentT::deleteAll('car_id='.$d_info->id);
                    $row = new AppointmentT();
                    $row->car_id = $d_info->id;
                    $row->user_id = $d_info->user_id;
                    $row->pdate = date('Y-m-d');
                    $row->ptype = 0;
                    $row->ptime = '09:00';
                    $row->remark = '首次分配';
                    $row->is_first = 1;
                    $row->xdate = date('Y-m-d');
                    $row->xtime = '09:00';
                    $row->xbao = 2;
                    if(!$row->save()) {
                        throw new \Exception(print_r($row->getErrors(),true));
                    }

                    //添加历史预约
                    $h_row = new AppointmentHistoryT();
                    $h_row->car_id = $d_info->id;
                    $h_row->user_id = $d_info->user_id;
                    $h_row->pdate = date('Y-m-d');
                    $h_row->ptype = 0;
                    $h_row->ptime = '09:00';
                    $h_row->remark = '首次分配';
                    $h_row->xdate = date('Y-m-d');
                    $h_row->xtime = '09:00';
                    $h_row->xbao = 2;
                    if(!$h_row->save()) {
                        throw new \Exception(print_r($h_row->getErrors(),true));
                    }

                    $this->addLog($d_info->id,'从D库分配数据给业务员:'.$d_info->user->getShowName(),1);
                    $index++;
                }
                $result['success'] = true;
                $result['msg'] = '操作成功';

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

        if($request->isPost) {

            $status = $request->post('status');
            $register_begin = $request->post('register_begin');
            $register_end = $request->post('register_end');
            $insurer1_begin = $request->post('insurer1_begin');
            $insurer1_end = $request->post('insurer1_end');

            $query = CarDT::find()
                ->leftJoin('car_t','`car_t`.`id`=`car_d_t`.`id`');

            if($register_begin != '') {
                $query->andWhere('car_t.register_date>="'.$register_begin.'"');
            }
            if($register_end != '') {
                $query->andWhere('car_t.register_date<="'.$register_end.'"');
            }
            if($insurer1_begin != '') {
                $query->andWhere('car_t.insurer1_date>="'.$insurer1_begin.'"');
            }
            if($insurer1_end != '') {
                $query->andWhere('car_t.insurer1_end<="'.$insurer1_end.'"');
            }
            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($query->each(1000) as $item) {
                    //删除预约
                    AppointmentT::deleteAll('car_id='.$item->id);

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

                    $item->user_id = 0;
                    if(!$item->save()) {
                        throw new \Exception(print_r($item->getErrors(), true));
                    }
//            FiltrationT
                    //删除预约拨打
//                    FiltrationT::deleteAll('car_id='.$c_info->id);
                    $this->addLog($item->id,'从D库业务员手中批量回收数据',1);
                }

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

                $tran->commit();
            } catch (\Exception $e) {
                $tran->rollBack();
                $result['msg'] = $e->getMessage();
            }
        }
        return $result;
    }
    //钩选D库到无效库
    public function actionDInvalid()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $ids = explode(',',$request->post('ids'));
            $invalid_id = $request->post('invalid_id',0);
            if($invalid_id == 0) {
                $result['msg'] = '请选择无效理由';
                return $result;
            }
            if($ids[0] == '') {
                $result['msg'] = '请先钩选车辆';
                return $result;
            }

            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($ids as $id) {
                    $car_info = CarT::findOne(['id'=>$id]);
                    if($car_info->location == 4) {
                        $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));
                            }
                        }

                        $d_info = CarDT::findOne(['id'=>$id]);
                        if($d_info) {
                            if($d_info->user_id > 0) {
                                //删除预约
                                AppointmentT::deleteAll('car_id='.$d_info->id);

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

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

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

    //无效库列表页
    private function getInvalidQuery($request)
    {
        if($request->isPost) {
            $car_man = $request->post('car_man');
            $phone = $request->post('phone');
            $car_no = $request->post('car_no');
            $register_begin = $request->post('register_begin');
            $register_end = $request->post('register_end');
            $insurer1_begin = $request->post('insurer1_begin');
            $insurer1_end = $request->post('insurer1_end');
            $invalid_id = $request->post('invalid_id');
            $username = $request->post('username');
            $user1 = $request->post('user1');
            $sort_key = $request->post('sort_key');
            $sort_value = $request->post('sort_value');
        } else {
            $car_man = $request->get('car_man');
            $phone = $request->get('phone');
            $car_no = $request->get('car_no');
            $register_begin = $request->get('register_begin');
            $register_end = $request->get('register_end');
            $insurer1_begin = $request->get('insurer1_begin');
            $insurer1_end = $request->get('insurer1_end');
            $invalid_id = $request->get('invalid_id');
            $username = $request->get('username');
            $user1 = $request->get('user1');
            $sort_key = $request->get('sort_key');
            $sort_value = $request->get('sort_value');
        }
        $params = array();
        $params['car_man'] = $car_man;
        $params['phone'] = $phone;
        $params['car_no'] = $car_no;
        $params['register_begin'] = $register_begin;
        $params['register_end'] = $register_end;
        $params['insurer1_begin'] = $insurer1_begin;
        $params['insurer1_end'] = $insurer1_end;
        $params['invalid_id'] = $invalid_id;
        $params['username'] = $username;
        $params['user1'] = $user1;
        $params['sort_key'] = $sort_key;
        $params['sort_value'] = $sort_value;

        $query = CarInvalidT::find()
            ->leftJoin(CarT::tableName(),'`car_t`.`id`=`car_invalid_t`.`id`');

        if($car_man != '') {
            $query->andWhere('car_t.car_man="'.$car_man.'"');
        }
        if($phone != '') {
            $query->andWhere('car_t.car_man_phone=:phone or car_t.id_man_phone=:phone',[':phone'=>$phone]);
        }
        if($car_no != '') {
            $query->andWhere('car_t.car_no="'.$car_no.'"');
        }
        if($register_begin != '') {
            $query->andWhere('car_t.register_date>="'.$register_begin.'"');
        }
        if($register_end != '') {
            $query->andWhere('car_t.register_date<="'.$register_end.'"');
        }
        if($insurer1_begin != '') {
            $query->andWhere('car_t.insurer1_date>="'.$insurer1_begin.'"');
        }
        if($insurer1_end != '') {
            $query->andWhere('car_t.insurer1_date<="'.$insurer1_end.'"');
        }
        if($invalid_id > 0) {
            $query->andWhere('car_invalid_t.invalid_id='.$invalid_id);
        }
        if($user1 != '') {
            $query->andWhere('car_t.op_user1 like "'.$user1.'%"');
        }
        if($username != '') {
            $user_info = UserT::findOne(['username'=>$username]);
            if($user_info) {
                $query->andWhere('car_invalid_t.user_id='.$user_info->id);
            }
        }
        $query->orderBy($sort_key.' '.$sort_value.',car_invalid_t.id '.$sort_value);
//        echo $query->createCommand()->rawSql;
        return ['query'=>$query,'params'=>$params];
    }
    public function actionInvalidIndex()
    {
        $invalid_items = InvalidT::getTree();
        return $this->render('invalid-index',[
            'invalid_items'=>$invalid_items
        ]);
    }
    public function actionInvalidIndexJson()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $offset = $request->get('offset',0);
        $limit = $request->get('limit', 10);

        $data = $this->getInvalidQuery($request);
        $query = $data['query'];
//        $query->andWhere('location=1');
        $total = $query->count();

        $query->orderBy('id desc');
        $query = $query->offset($offset)->limit($limit);
        $items = $query->all();

        $data = [];
        $data['total'] = $total;
        $data['rows'] = [];
        foreach($items as $item) {
            $car_info = $item->car;
            if(!$car_info) continue;
            $row = $car_info->toArray();
            $row['factory_model'] = MyLib::substr_cut($car_info->factory_model, 8);
            $row['car_man'] = MyLib::substr_cut($car_info->car_man, 8);
            $row['op_user'] = $item->user?$item->user->getShowName():'';
            $row['invalid_info'] = $item->invalid->getPath();
            $row['invalid_time'] = $item->created_at;
            $data['rows'][] = $row;
        }
        return $data;
    }
    public function actionInvalidA()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $result = array();
        $result['success'] = false;
        $result['msg'] = '操作失败';

        if($request->isPost) {
            $ids = explode(',',$request->post('ids'));

            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($ids as $id) {
                    $car_info = CarT::findOne(['id'=>$id]);
                    $car_info->location = 1;
                    if(!$car_info->save()) {
                        throw new \Exception(print_r($car_info->getErrors(), true));
                    }

                    CarInvalidT::deleteAll('id='.$id);
                    AppointmentHistoryT::deleteAll('car_id='.$id);
                    $this->addLog($car_info->id,'从无效数据中恢复数据',1);
                }
                $result['success'] = true;
                $result['msg'] = '操作成功';

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

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

//            if($invalid_id == 0) {
//                $result['msg'] = '请先选择无效理由';
//                return $result;
//            }
            $data = $this->getInvalidQuery($request);
            $query = $data['query'];

            $tran = CarT::getDb()->beginTransaction();
            try {
                foreach($query->each(1000) as $item) {
                    $car_info = $item->car;
                    $car_info->location = 1;
                    if(!$car_info->save()) {
                        throw new \Exception(print_r($car_info->getErrors(), true));
                    }
                    AppointmentHistoryT::deleteAll('car_id='.$item->id);
                    $item->delete();
                    $this->addLog($item->id,'从无效数据中恢复数据',1);
                }

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

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