<?php
/**
 * Created by PhpStorm.
 * User: liuyingjie
 * Date: 2017/8/2
 * Time: 13:38
 */

namespace frontend\controllers;

use common\components\Upload;
use common\libs\MyLib;
use common\models\CarFinanceT;
use common\models\CarLogT;
use common\models\CarT;
use common\models\DirectionT;
use common\models\FixCarImg;
use common\models\FixCarItemT;
use common\models\FixCarReport;
use common\models\FixCarTuoche;
use common\models\FixItemT;
use common\models\FixCarCategory;
use common\models\InsurerCompanyT;
use common\models\Message;
use common\models\MetalPlatePart;
use common\models\MiddleDamageLevel;
use common\models\MiddleFixCarT;
use common\models\MiddleScaleHour;
use common\models\RangeT;
use common\models\RoleT;
use common\models\StoreRoom;
use common\models\UserT;
use Yii;
use common\models\FixCarT;
use yii\data\Pagination;
use yii\db\Exception;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\web\Response;

class BusinessOrderController extends FixCarBaseController
{
    public function behaviors()
    {
        return [
            [
                'class' => 'yii\filters\ContentNegotiator',
                'only' => ['save', 'delete','order-save','driver-save','front-desk-check-save',
                    'front-setting-loss-exploration-save','setting-loss-exploration-add','fix-item-remove','remove-report',
                    'front-desk-save','front-desk-info-item-save','ajax-metal-plate-list','metal-plate-save','ajax-bottom-work-list','bottom-work-save',
                    'ajax-paint-work-list','paint-work-save','ajax-metal-plate-install-list','metal-plate-install-save','ajax-electromechanical-list','electromechanical-save',
                    'ajax-car-wash-list','car-wash-save','ajax-last-check-list','last-check-save','fix-user-sibling','fix-car-save','ajax-item-list','ajax-item-list-bak',
                    'fix-item-finish','ajax-fix-user','ajax-job-foreman','get-damage-level','get-metal-plate','get-self-free','get-price-by-shop','rm-img','web-uploader','look-image','refresh-item-list'],
                'formats' => [
                      'application/json' => Response::FORMAT_JSON,
                  ]
            ],
//            [
//                'class'=>'yii\filters\HttpCache',
//                'only' => ['setting-loss-exploration-list','index','order-info','check-list','check-info','driver-list','driver-info','front-desk-check-list',
//                    'front-desk-check-info','setting-loss-exploration-list','setting-loss-exploration-info',
//                    'front-desk-list','front-desk-info','metal-plate-list','metal-plate-info','bottom-work-list','bottom-work-info',
//                    'paint-work-list','paint-work-info','metal-plate-install-list','metal-plate-install-info',
//                    'electromechanical-list','electromechanical-info','car-wash-list','car-wash-info','last-check-list','last-check-info'],
//                'cacheControlHeader'=> null,
//                'etagSeed' => function () {
//                     $q = new \yii\db\Query();
//                     $model = $q->from('fix_car_t');
//                     $model1 = $q->from('fix_car_item_t');
//                     $model2 = $q->from('fix_car_img');
//                     return $model->max('updated_at').$model->max('id').$model->count().
//                         $model1->max('updated_at').$model1->max('id').$model1->count().
//                         $model2->max('updated_at').$model2->max('id').$model2->count();
//                },
//            ],
//            'pageCache' => [
//                'class' => 'yii\filters\PageCache',
//                'only' => ['setting-loss-exploration-list','index','order-info','check-list','check-info','driver-list','driver-info','front-desk-check-list',
//                    'front-desk-check-info','setting-loss-exploration-list','setting-loss-exploration-info',
//                    'front-desk-list','front-desk-info','metal-plate-list','metal-plate-info','bottom-work-list','bottom-work-info',
//                    'paint-work-list','paint-work-info','metal-plate-install-list','metal-plate-install-info',
//                    'electromechanical-list','electromechanical-info','car-wash-list','car-wash-info','last-check-list','last-check-info'],
//                'duration' => 0,
//                'varByParam'=>Yii::$app->request->queryString,
//                'dependency' => [
//                  'class' => 'yii\caching\DbDependency',
//                  'sql' => "SELECT * FROM (SELECT MAX('updated_at'),MAX('id'),COUNT(*) FROM fix_car_t) AS t1 UNION ALL".
//                      " SELECT * FROM (SELECT MAX('updated_at'),MAX('id'),COUNT(*) FROM fix_car_item_t) AS t2 UNION ALL".
//                      " SELECT * FROM (SELECT MAX('updated_at'),MAX('id'),COUNT(*) FROM fix_car_img) AS t3",
//                ],
//                'variations' => [
//                  Yii::$app->language,
//                ]
//          ],
        ];
    }

    private function getList($request, &$session, $type = '')
    {
        $page = $request->get('page', 1);

        $query = FixCarT::find()->select('id,car_no,id_man,link_man,link_phone,submit_date,user_id,status,brand_id,series_id,address,accident_type,responsibility,updated_at');
        $query = $query->where('status <=' . self::MAX_STATUS);

        $render = [];
        $this->getQuery($request, $query, $render);

        $sql = $query->createCommand()->rawSql;
        $total = $query->count();
        $session->remove('driver_list');
        $session->set('driver_list', $sql);

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

        $query = $query->offset($pagination->offset)->orderBy('created_at DESC')->limit($pagination->limit);
        $items = $query->all();

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

        $render['items'] = $items;
        $render['page_info'] = $page_info;
        $render['page'] = $page;
        if ('' !== $type) $render['type_name'] = $type;
        return $render;
    }
    private function getList1($request, &$session, $type = '')
    {
        $page = $request->get('page', 1);

        $query = MiddleFixCarT::find();
        $is_join = false; //控制是否关联查询
        switch($type){
            case self::METAL_PLATE://钣金
                $is_join = true;
                $query = $query->joinWith('items','LEFT')->where('middle_fix_car_t.type=1 AND fix_car_item_t.metal_plate_install=0 AND fix_car_item_t.fix_group=7 AND middle_fix_car_t.status=6 AND fix_car_item_t.fix_user='.$this->my->id.' AND fix_car_item_t.lock_id='.$this->my->id);
            break;
            case self::METAL_PLATE_INSTALL://钣金安装
                $is_join = true;
                $query = $query->joinWith('items','LEFT')->where('middle_fix_car_t.type=1 AND fix_car_item_t.fix_status=1 AND fix_car_item_t.fix_group=7 AND middle_fix_car_t.status=9 AND fix_car_item_t.fix_user='.$this->my->id.' AND fix_car_item_t.lock_id='.$this->my->id);
            break;
            case self::BOTTOM_WORK://底子工
                $is_join = true;
                $query = $query->joinWith('items','LEFT')->where('middle_fix_car_t.type=1 AND middle_fix_car_t.status=7 AND fix_car_item_t.fix_user='.$this->my->id.' AND fix_car_item_t.lock_id='.$this->my->id.' AND fix_car_item_t.fix_group=13');
            break;
            case self::PAINT_WORK://喷漆工
                $is_join = true;
                $query = $query->joinWith('items','LEFT')->where('middle_fix_car_t.type=1 AND middle_fix_car_t.status=8 AND fix_car_item_t.fix_user='.$this->my->id.' AND fix_car_item_t.lock_id='.$this->my->id.' AND fix_car_item_t.fix_group=8');
            break;
            case self::CAR_WASH://美容装饰
                $is_join = true;
                $query = $query->joinWith('items','LEFT')->joinWith('fix')->where('middle_fix_car_t.type=1 AND middle_fix_car_t.status=13 AND fix_car_item_t.fix_user='.$this->my->id.' AND fix_car_item_t.lock_id='.$this->my->id.' AND fix_car_item_t.fix_group=12 AND fix_car_t.status_1=1 AND fix_car_t.status_2=1');
            break;
            case self::ELECTROMECHANICAL://机电
                $is_join = true;
                $query = $query->joinWith('items','LEFT')->andWhere('middle_fix_car_t.type=2 AND middle_fix_car_t.status=11 AND fix_car_item_t.fix_user='.$this->my->id.' AND fix_car_item_t.lock_id='.$this->my->id.' AND fix_car_item_t.fix_group BETWEEN 10 AND 11');
                break;
            case self::LAST_CHECK://总检
                $is_join = false;
                $query = $query->where('status=14');
            break;
        }
        $render = [];
        $is_join ? $this->getQuery1($request, $query, $render) : $this->getQuery($request, $query, $render);

        $sql = $query->createCommand()->rawSql;
        $total = $query->count();
        $session->remove('metal_plate_list');
        $session->set('metal_plate_list', $sql);

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

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

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

        $render['items'] = $items;
        $render['page_info'] = $page_info;
        $render['page'] = $page;
        if ('' !== $type) $render['type_name'] = $type;
        return $render;
    }
    /**
     *------------------------------------------------------------
     *  查询条件
     * @param object $request ; 引用 $query,$render
     * @return void
     * @author liuyingjie
     *------------------------------------------------------------
     */
    private function getQuery($request, &$query, &$render)
    {
        $op = $request->get('op');
        $car_no = $request->get('car_no', '');
        $status = $request->get('status');
        $id_man = $request->get('id_man', '');
        $id_phone = $request->get('id_phone', '');
        $link_man = $request->get('link_man', '');
        $link_phone = $request->get('link_phone', '');
        $sort_key = $request->get('sort_key', '');
        $sort_value = $request->get('sort_value', '');
        $start_time = $request->get('start_time') ? $request->get('start_time') . ' 00:00:00' : '';
        $end_time = $request->get('end_time') ? $request->get('end_time') . ' 24:00:00' : '';

        if ('0' === $op) $query = $query->andWhere('id=-1');
        if ('' !== $car_no) $query = $query->andWhere(['like', 'car_no', $car_no]);
        if ($status >= 0) $query = $query->andWhere('status = \'' . $status.'\'');
        if ('' !== $id_man) $query = $query->andWhere(['like', 'id_man', $id_man]);
        if ('' !== $id_phone) $query = $query->andWhere(['like', 'id_man_phone', $id_phone]);
        if ('' !== $link_man) $query = $query->andWhere(['like', 'link_man', $link_man]);
        if ('' !== $link_phone) $query = $query->andWhere(['like', 'link_phone', $link_phone]);
        if ('' !== $start_time && '' !== $end_time) $query = $query->andWhere('created_at >= \'' . $start_time . '\' AND  created_at <=\'' . $end_time . '\'');
        if ('' !== $start_time && '' === $end_time) $query = $query->andWhere('created_at >= \'' . $start_time . '\'');
        if ('' !== $end_time && '' === $start_time) $query = $query->andWhere('created_at <= \'' . $end_time . '\'');
        if ('' !== $sort_key) $query = $query->orderBy($sort_key . ' ' . $sort_value . ' , id ASC');

        $render['car_no'] = $car_no;
        $render['status'] = $status;
        $render['id_man'] = $id_man;
        $render['id_phone'] = $id_phone;
        $render['link_man'] = $link_man;
        $render['link_phone'] = $link_phone;
        $render['sort_key'] = $sort_key;
        $render['sort_value'] = $sort_value;
        $render['start_time'] = substr($start_time, 0, 10);
        $render['end_time'] = substr($end_time, 0, 10);
    }
    private function getQuery1($request, &$query, &$render)
    {
        $op = $request->get('op');
        $car_no = $request->get('car_no', '');
        $status = $request->get('status', '');
        $id_man = $request->get('id_man', '');
        $id_phone = $request->get('id_phone', '');
        $link_man = $request->get('link_man', '');
        $link_phone = $request->get('link_phone', '');
        $sort_key = $request->get('sort_key', '');
        $sort_value = $request->get('sort_value', '');
        $start_time = $request->get('start_time') ? $request->get('start_time') . ' 00:00:00' : '';
        $end_time = $request->get('end_time') ? $request->get('end_time') . ' 24:00:00' : '';

        if ('0' === $op) $query = $query->joinWith('fix')->andWhere('fix_car_t.id=-1');
        if ('' !== $car_no) $query = $query->joinWith('fix')->andWhere(['like', 'fix_car_t.car_no', $car_no]);
        if ('' !== $status) $query = $query->joinWith('fix')->andWhere('fix_car_t.status = ' . $status);
        if ('' !== $id_man) $query = $query->joinWith('fix')->andWhere(['like', 'fix_car_t.id_man', $id_man]);
        if ('' !== $id_phone) $query = $query->joinWith('fix')->andWhere(['like', 'fix_car_t.id_man_phone', $id_phone]);
        if ('' !== $link_man) $query = $query->joinWith('fix')->andWhere(['like', 'fix_car_t.link_man', $link_man]);
        if ('' !== $link_phone) $query = $query->joinWith('fix')->andWhere(['like', 'fix_car_t.link_phone', $link_phone]);
        if ('' !== $start_time && '' !== $end_time) $query = $query->joinWith('fix')->andWhere('fix_car_t.created_at >= \'' . $start_time . '\' AND  fix_car_t.created_at <=\'' . $end_time . '\'');
        if ('' !== $start_time && '' === $end_time) $query = $query->joinWith('fix')->andWhere('fix_car_t.created_at >= \'' . $start_time . '\'');
        if ('' !== $end_time && '' === $start_time) $query = $query->joinWith('fix')->andWhere('fix_car_t.created_at <= \'' . $end_time . '\'');
        if ('' !== $sort_key) $query = $query->joinWith('fix')->orderBy('fix_car_t.'.$sort_key . ' ' . $sort_value . ' , fix_car_t.id ASC');

        $render['car_no'] = $car_no;
        $render['status'] = $status;
        $render['id_man'] = $id_man;
        $render['id_phone'] = $id_phone;
        $render['link_man'] = $link_man;
        $render['link_phone'] = $link_phone;
        $render['sort_key'] = $sort_key;
        $render['sort_value'] = $sort_value;
        $render['start_time'] = substr($start_time, 0, 10);
        $render['end_time'] = substr($end_time, 0, 10);
    }

    /**
     *------------------------------------------------------------
     *  业务提单
     * @param fix_car_t status = 0
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionIndex()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;
        return $this->render('index', $this->getList($request, $session));
    }

    /**
     *------------------------------------------------------------
     *  搜索页
     * @param
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionSearch()
    {

        return $this->render('search');
    }

    /**
     *------------------------------------------------------------
     * 判断是否登记
     * @param varchar car_no engine_no car_frame_no car_man car_phone
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionSearchResult()
    {
        $request = Yii::$app->request;
        $car_no = $request->get('car_no');
        $engine_no = $request->get('engine_no');
        $car_frame_no = $request->get('car_frame_no');
        $car_man = $request->get('car_man');
        $car_phone = $request->get('car_phone');

        if($fix_car = FixCarT::find()->where('car_no=\''.$car_no.'\' AND out_factory_date IS NULL')->one()){
            return '【车牌号:'.$fix_car->car_no.';未出厂】<br>【提单者:'.$fix_car->user->getShowName().'】<br>【提单日期:'.$fix_car->submit_date.'】<br>【维修进度:'.$fix_car->getStatus().'】<br><a href="javascript:void(0)" onclick="history.go(-1)">返回</a>';
        }
        $query = CarT::find();
        if ($car_no !== '') $query = $query->andWhere('car_no like "' . $car_no . '"');
        if ($engine_no !== '') $query = $query->andWhere('engine_no like "' . $engine_no . '"');
        if ($car_frame_no !== '') $query = $query->andWhere('car_frame_no like "' . $car_frame_no . '"');
        if ($car_man !== '') $query = $query->andWhere('car_man like "' . $car_man . '"');
        if ($car_phone !== '') $query = $query->andWhere('phone like "' . $car_phone . '"');

        $items = $query->all();

        return $this->render('search-result', [
            'items' => $items
        ]);
    }

    /**
     *------------------------------------------------------------
     *  删除
     * @param int id
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionDelete()
    {
        $request = Yii::$app->request;

        $result = [];
        $result['success'] = true;
        $result['msg'] = '删除失败!';

        if (!$request->isAjax) return $result;

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

        $tran = Yii::$app->db->beginTransaction();
        try {
            $fix_car = FixCarT::findOne($id);
            if (!$fix_car->delete()) throw new Exception('');

            CarLogT::deleteAll('car_id = :car_id AND type = :type', [':car_id' => $fix_car->car_id, ':type' => 2]);

            $result['success'] = true;
            $result['msg'] = '删除成功!';

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

    public function actionOrderInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $car_id = $request->get('car_id', 0);
        $status = $request->get('status', 0);
        $type = $request->get('type', 0);

        $info = $id > 0 ? FixCarT::findOne(['id' => $id, 'status' => $status]) : new FixCarT();
        //总库(car_t) 移至 维修(car_fix_t)
        if ($car_id > 0 && $id < 1) {
            $car_info = CarT::find()
                ->where(['id' => $car_id])
                ->orderBy('register_date DESC')
                ->one();
            $info->car_id = $car_info->id;
            $info->car_no = $car_info->car_no;
            $info->engine_no = $car_info->engine_no;
            $info->car_frame_no = $car_info->car_frame_no;
            $info->id_man = $car_info->id_man;
            $info->id_man_phone = $car_info->car_man_phone;
            $info->link_man = $car_info->car_man;
            $info->link_man_phone = $car_info->car_man_phone;
            $info->company = $car_info->company;
            $info->brand_id = $car_info->brand_id;
            $info->series_id = $car_info->series_id;
            $info->displacement_id = $car_info->displacement_id;
            $info->car_year = $car_info->car_year;
            $info->status = $status;
        }

        return $this->render('order-info', [
            'info' => $info,
            'direction_items' => $this->getDirection(),
            'range_items' => $this->getRange(),
            'log_items' => $this->getCarLog(intval($info->car_id)),
            'driver_items' => $this->getDrivers(),
            'brand_items' => $this->getBrands(),
            'series_items' => $this->getSeries(intval($info->brand_id)),
            'displacement_items' => $this->getDisplacement(intval($info->series_id)),
            'type' => $type,
        ]);
    }
    public function actionOrderSave(){
        $request = Yii::$app->request;
        $id = $request->post('id', 0);
        $car_id = $request->post('car_id');
        $series_id = $request->post('series_id');
        $displacement_id = $request->post('displacement_id');
        $sys_remark = $request->post('sys_remark', '');
        if (!$request->isAjax) return Message::getMessage();

        $tran = FixCarT::getDb()->beginTransaction();
        try {
            //更新或新增
            $row = $id > 0 ? FixCarT::findOne($id) : new FixCarT();
            $old_status = $row->isNewRecord ? 0 : $row->status;
            //场景选择
            $row->scenario = $row->getModelScenario();
            //批量赋值
            $row->attributes = $request->post();
            $row->series_id = $series_id ? $series_id :null;
            $row->displacement_id = $displacement_id ? $displacement_id :null;
            $row->remark = $sys_remark;
            if (!$row->validate()) {
                $errors = array_values($row->errors);
                return Message::getMessage(false,$errors[0]);
            }
            //新增
            if ($row->isNewRecord && $car_id > 0) {
                $row->submit_date = date('Y-m-d H:i:s');
                $row->user_id = $this->my->id;
                $row->car_id = $car_id;
            }
            if (!$row->save()) throw new Exception('');

            if ($old_status >= 0 && $row->status != $old_status) {
                $log_info = new CarLogT();
                $log_info->car_id = $car_id;
                $log_info->op_time = time();
                $log_info->op_man = $this->my->getShowName();
                $log_info->group_name = $this->my->group ? $this->my->group->getPath() : '';
                $log_info->type = 2;
                $log_info->remark = $row->getStatusMark($row->status);
                $log_info->info = $sys_remark;
                if (!$log_info->save()) throw new Exception('');
            }

            $tran->commit();

            $fix_id = $row->isNewRecord ? Yii::$app->db->getLastInsertID() : $row->id;
            return Message::getMessage(true,'保存成功!',$fix_id);
        } catch (Exception $e) {
            $tran->rollBack();
            return Message::getMessage(false,$e->getMessage());
        }
    }

    /*******************************************************提单审核*****************************************************/

    /**
     *------------------------------------------------------------
     *  提单审核
     * @param fix_car_t status = 1 提单审核
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionCheckList()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        return $this->render('check-list', $this->getList($request, $session));
    }

    /**
     *------------------------------------------------------------
     *  提单审核详情
     * @param
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionCheckInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $type = $request->get('type', 0);
        $gift_enable = $request->get('gift_enable', 0);

        $info = FixCarT::findOne(['id' => $id]); //编辑
//        //礼品
//        $gift_items = CarGiftT::find()
//            ->where('car_id='.$car_info->id)
//            ->orderBy('strategy_id DESC')
//            ->all();
        return $this->render('check-info', [
            'info' => $info,
//            'gift_items' => $gift_items,
            'direction_items' => $this->getDirection(),
            'range_items' => $this->getRange(),
            'log_items' => $this->getCarLog(intval($info->car_id)),
            'driver_items' =>  $this->getDrivers(),
            'brand_items' =>  $this->getBrands(),
            'series_items' => $this->getSeries(intval($info->brand_id)),
            'displacement_items' => $this->getDisplacement(intval($info->series_id)),
            'type' => $type,
            'gift_enable' => $gift_enable
        ]);
    }
    public function actionCheckSave(){
        $request = Yii::$app->request;

        if (!$request->isAjax) return Message::getMessage();
        $tran = FixCarT::getDb()->beginTransaction();
        try {
            $id = $request->post('id', 0);
            $car_id = $request->post('car_id');
            $driver_id = $request->post('driver_id');
            $sys_remark = $request->post('sys_remark', '');
            if($id < 1) return Message::getMessage();

            //更新或新增
            $row = FixCarT::findOne($id);
            $old_status = $row->isNewRecord ? 0 : $row->status;
            //场景选择
            $row->scenario = $row->getModelScenario();
            //批量赋值
            $row->attributes = $request->post();
            $row->remark = $sys_remark;
            $row->driver_id = $driver_id;
            if (!$row->validate()) {
                $errors = array_values($row->errors);
                return Message::getMessage(false,$errors[0]);
            }

            if ($old_status >= 0 && $row->status != $old_status) {
                $log_info = new CarLogT();
                $log_info->car_id = $car_id;
                $log_info->op_time = time();
                $log_info->op_man = $this->my->getShowName();
                $log_info->group_name = $this->my->group ? $this->my->group->getPath() : '';
                $log_info->type = 2;

                //提单审核 提交
                //上门接车 && (自费维修 || 保险理赔),都进入司机接车
                if ((2 == $row->status) && ('上门接车' == $row->receive_type)) {
                    $row->status = 2;
                } //客户自送 && 自费维修,则直接进入前台审核
                elseif (2 == $row->status && ('客户自送' == $row->receive_type)) {
                    $row->status = 3;
                }
                $log_info->remark = $row->getStatusMark($row->status);
                $log_info->info = $sys_remark;

                if (!$log_info->save()) throw new Exception('记录日志失败!');
            }

            if (!$row->save()) throw new Exception('维修信息修改失败!');

            $tran->commit();
            return Message::getMessage(true,'保存成功!',$row->id);
        } catch (Exception $e) {
            $tran->rollBack();
            return Message::getMessage(false,$e->getMessage());
        }
        return $result;
    }
    /***************************************************** end ********************************************************/

    /***************************************************司机接车*******************************************************/
    /**
     *------------------------------------------------------------
     *  司机接车
     * @param string car_no(车牌号)
     * @param int status = 2 待接车
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionDriverList()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        return $this->render('driver-list', $this->getList($request, $session));
    }

    /**
     *------------------------------------------------------------
     *  司机接车详情
     * @param
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionDriverInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $type = $request->get('type', 0);
        $gift_enable = $request->get('gift_enable', 0);

        $info = $render['info'] = FixCarT::findOne(['id' => $id]);

        return $this->render('driver-info', [
            'info' => $info,
            'direction_items' => $this->getDirection(),
            'range_items' =>  $this->getRange(),
            'log_items' => $this->getCarLog(intval($info->car_id)),
            'driver_items' => $this->getDrivers(),
            'brand_items' => $this->getBrands(),
            'series_items' => $this->getSeries(intval($info->brand_id)),
            'displacement_items' => $this->getDisplacement(intval($info->series_id)),
            'type' => $type,
            'gift_enable' => $gift_enable,
        ]);
    }

    /**
     *------------------------------------------------------------
     *  司机接车新增、保存
     * @param
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionDriverSave()
    {
        $request = Yii::$app->request;
        $small_type_id = $request->post('small_type_id');
        $name = $request->post('name');
        $count = $request->post('count', 1);
        $remark = $request->post('remark', '');
        $price = $request->post('price', 0);
        $fix_id = $request->post('fix_id');
        $pay_type = $request->post('pay_type');
        $id = $request->post('id', 0);
        $level = $request->post('level', 0);
        $insurance_price = $request->post('insurance_price', 0);

        $result = [];
        $result['success'] = false;
        $result['msg'] = '操作失败!';

        if (!$request->isAjax) return $result;

        $fix_item = ($id > 0 && 5 != $small_type_id) ? FixItemT::findOne($id) : new FixItemT();
        switch ($small_type_id) {
            case 1: //更换清单
            case 2: //维修清单
            case 3: //辅料清单
            case 4: //待定清单
            case 6: //美容装饰
                $fix_item->name = $name;
                $fix_item->count = $count;
                $fix_item->fix_remark = $remark;
                $fix_item->price = $price;
                $fix_item->small_type_id = $small_type_id;
                $fix_item->fix_id = $fix_id;
                $fix_item->pay_type = $pay_type;
                $fix_item->damage_level = $level;
                $fix_item->insurance_price = $insurance_price;
                if ($fix_item->save()) {
                    $result['success'] = true;
                    $result['msg'] = '操作成功!';
                }
                break;
            case 5: //汽车保养
                FixItemT::deleteAll('fix_id=' . $fix_id . ' AND small_type_id=5');
                foreach ($name as $k => $val) {
                    $type = strstr($val, '_');
                    $keep_in_good_id = rtrim(strstr($val, '_', true), '_');

                    if ('_0' == $type) {
                        $insert[$k]['name'] = '机油';
                        $insert[$k]['car_keep_in_good_id'] = $keep_in_good_id;

                    } elseif ('_1' == $type) {
                        $insert[$k]['name'] = '机油滤芯';
                        $insert[$k]['car_keep_in_good_id'] = $keep_in_good_id;
                    } elseif ('_2' == $type) {
                        $insert[$k]['name'] = '空气滤芯';
                        $insert[$k]['car_keep_in_good_id'] = $keep_in_good_id;
                    } elseif ('_3' == $type) {
                        $insert[$k]['name'] = '空调滤芯';
                        $insert[$k]['car_keep_in_good_id'] = $keep_in_good_id;
                    } elseif ('_4' == $type) {
                        $insert[$k]['name'] = '汽油滤芯';
                        $insert[$k]['car_keep_in_good_id'] = $keep_in_good_id;
                    }

                    $insert[$k]['price'] = $price;
                    $insert[$k]['count'] = $count;
                    $insert[$k]['fix_id'] = $fix_id;
                    $insert[$k]['small_type_id'] = $small_type_id;
                    $insert[$k]['pay_type'] = 2;
                }
                Yii::$app->db->createCommand()->batchInsert(FixItemT::tableName(), ['name', 'car_keep_in_good_id', 'price', 'count', 'fix_id', 'small_type_id', 'pay_type'], $insert)->execute();
                $result['success'] = true;
                $result['msg'] = '操作成功!';
                break;
        }
        return $result;
    }
    /************************************************* end ***********************************************************/

    /***************************************************前台审核*******************************************************/
    /**
     *------------------------------------------------------------
     * 前台审核列表页
     * @param int status = 3
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionFrontDeskCheckList()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        return $this->render('front-desk-check-list', $this->getList($request, $session));
    }

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

        $info = FixCarT::findOne(['id' => $id]);

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

        //报案号
        $reports = ($reports_res = FixCarReport::findAll(['fix_id'=>$id])) ? $reports_res : [];
        $report_nos = Json::encode($reports);

        return $this->render('front-desk-check-info', [
            'info' => $info,
//            'gift_items' => $gift_items,
            'direction_items' => $this->getDirection(),
            'range_items' =>  $this->getRange(),
            'log_items' =>$this->getCarLog(intval($info->car_id)),
            'driver_items' =>  $this->getDrivers(),
            'brand_items' => $this->getBrands(),
            'series_items' => $this->getSeries(intval($info->brand_id)),
            'displacement_items' => $this->getDisplacement(intval($info->series_id)),
            'type' => $type,
            'reports'=>$reports,
            'gift_enable' => $gift_enable,
        ]);
    }

    /**
     *------------------------------------------------------------
     *  前台审核添加保存
     * @param
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionFrontDeskCheckSave()
    {
        $request = Yii::$app->request;

        if (!$request->isAjax) return Message::getMessage();

        $tran = FixCarT::getDb()->beginTransaction();
        try {
            $id = $request->post('id', 0);
            $driver_id = $request->post('driver_id');
            $follow_car_items = $request->post('follow_car_items');
            $sys_remark = $request->post('sys_remark', '');

            if($id < 1 || empty($sys_remark)) return Message::getMessage();

            $row = FixCarT::findOne(['id' => $id]);
            $old_status = $row->status;

            //场景选择
            $row->scenario = $row->getModelScenario();

            //批量赋值
            $row->attributes = $request->post();
            $row->remark = $sys_remark;
            $row->driver_id = $driver_id ? $driver_id :null;

            //如果有随车物品,则拼接为字符串
            if (!empty($follow_car_items)) $row->follow_car_items = implode($follow_car_items, ',');

            if (!$row->validate()) {
                $errors = array_values($row->errors);
                $result['msg'] = $errors[0];
                return $result;
            }

            //判断结算方式,如果非保险理赔则跳过查勘定损,直接进入前台派工
            if(intval($row->status) === 4 && FixCarItemT::find()->where(['fix_id'=>$row->id,'pay_type'=>1])->count() < 1) $row->status = 5;

            //保险理赔 && fix_id = $row->id && 未维修 && 未进入总检 && 未确认 && 钣金安装未确认
            $fix_item = FixCarItemT::find()->where(['fix_id'=>$row->id,'fix_status'=>0,'status'=>0,'confirm_at'=>'0000-00-00 00:00:00','get_time'=>'0000-00-00 00:00:00','metal_plate_install'=>0])->select('pay_type')->asArray()->all();
            $fix_item = array_unique(array_column($fix_item,'pay_type'));
            if(empty($fix_item)){
//                return Message::getMessage(false,'清单不可为空!');
            }else{
                $row->status = in_array(1,$fix_item) ? 4 : 5;
            }

            //操作记录
            if ($old_status >= 0 && $row->status != $old_status) {
                $log_info = new CarLogT();
                $log_info->car_id = $row->car_id;
                $log_info->op_time = time();
                $log_info->op_man = $this->my->getShowName();
                $log_info->group_name = $this->my->group ? $this->my->group->getPath() : '';
                $log_info->type = 2;
                $log_info->remark = $row->getStatusMark($row->status);
                $log_info->info = $sys_remark;

                if (!$log_info->save()) throw new Exception('a');
            }

            if (!$row->save()) throw new Exception('b');

            $result['success'] = true;
            $result['msg'] = '保存成功';
            $result['fix_id'] = $row->id;

            $tran->commit();
        } catch (Exception $e) {
            var_dump($e->getMessage());
            $tran->rollBack();
        }
        return $result;
    }
    /***************************************************** end *******************************************************/

    /*****************************************************查勘定损******************************************************/
    /**
     *------------------------------------------------------------
     *  查勘定损
     * @param string car_no 车牌号
     * @param int status = 4 待查勘定损
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionSettingLossExplorationList()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        return $this->render('setting-loss-exploration-list', $this->getList($request, $session));
    }

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

        $info = FixCarT::findOne($id);
        //报案号
        $reports = ($reports_res = FixCarReport::findAll(['fix_id'=>$id])) ? $reports_res : [];
        $report_nos = Json::encode($reports);
        return $this->render('setting-loss-exploration-info', [
            'info' => $info,
            'direction_items' => $this->getDirection(),
            'range_items' =>  $this->getRange(),
            'log_items' => $this->getCarLog(intval($info->car_id)),
            'driver_items' => $this->getDrivers(),
            'brand_items' =>  $this->getBrands(),
            'series_items' => $this->getSeries(intval($info->brand_id)),
            'displacement_items' => $this->getDisplacement(intval($info->series_id)),
            'type' => $type,
            'gift_enable' => $gift_enable,
            'reports'=>$reports,
            'report_nos'=>$report_nos,
            'insurer_companies'=>InsurerCompanyT::find()->all(),
            'tuoche'=>FixCarTuoche::find()->all()
        ]);
    }

    /**
     *------------------------------------------------------------
     *  查勘定损 车辆信息添加
     * @param
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionSettingLossExplorationAdd()
    {
        $request = Yii::$app->request;
        $id = $request->post('id', 0);
        $follow_car_items = $request->post('follow_car_items');
        $car_id = $request->post('car_id');
        $driver_id = $request->post('driver_id');
        $sys_remark = $request->post('sys_remark', '');

        if (!$request->isAjax || $id < 1) return Message::getMessage();

        $tran = FixCarT::getDb()->beginTransaction();
        try {
            $row = FixCarT::findOne($id);
            $old_status = $row->status;
            //场景选择
            $row->scenario = $row->getModelScenario();
            //批量赋值
            $row->attributes = $request->post();
            $row->remark = $sys_remark;
            $row->driver_id = $driver_id ? $driver_id : null;

            //如果有随车物品,则拼接为字符串
            if (!empty($follow_car_items)) $row->follow_car_items = implode($follow_car_items, ',');

            if (!$row->validate()) {
                $errors = array_values($row->errors);
                return Message::getMessage(false,$errors[0]);
            }
            if (!$row->save()) throw new Exception('');

            //添加报案号
            $report_no = array_unique($request->post('report_no'));
            $report_id = $request->post('report_id');

            foreach($report_no as $k=>$v){
                $report = (isset($report_id[$k]) && $report_res = FixCarReport::findOne(['id'=>$report_id[$k]])) ? $report_res : new FixCarReport();

                $report->report_no = strtoupper($v);
                $report->baoan_man = $request->post('baoan_man')[$k];
                $report->baoan_time = $request->post('baoan_time')[$k];
                $report->chuxian_time = $request->post('chuxian_time')[$k];
                $report->baoan_address = $request->post('baoan_address')[$k];
                $report->shigu_info = $request->post('shigu_info')[$k];
                $report->lipei_company = $request->post('lipei_company')[$k];
                $report->zhuche_money =$request->post('zhuche_money')[$k];
                $report->sanzhe_money = $request->post('sanzhe_money')[$k];
                $report->wusun_money = $request->post('wusun_money')[$k];
                $report->tuoche = $request->post('tuoche')[$k];
                $report->tuoche_money = $request->post('tuoche_money')[$k];
                $report->dingsun_hour_money = $request->post('dingsun_hour_money')[$k];
                $report->dingsun_huanjian_money = $request->post('dingsun_huanjian_money')[$k];
                $report->peifu_bili = $request->post('peifu_bili')[$k];
                $report->peifu_money = $request->post('peifu_money')[$k];
                $report->kehu_money = $request->post('kehu_money')[$k];
                $report->fix_id = $row->isNewRecord ? Yii::$app->db->getLastInsertID() : $id;

                if(!$report->validate()){
                    $errors = array_values($report->errors);
                    return Message::getMessage($errors[0]);
                }

                if(!$report->save()) throw new Exception('报案号添加失败!');
            }

            //操作记录
            if ($old_status >= 0 && $row->status != $old_status) {
                $log_info = new CarLogT();
                $log_info->car_id = $car_id;
                $log_info->op_time = time();
                $log_info->op_man = $this->my->getShowName();
                $log_info->group_name = $this->my->group ? $this->my->group->getPath() : '';
                $log_info->type = 2;
                $log_info->remark = $row->getStatusMark($row->status);
                $log_info->info = $sys_remark;

                if (!$log_info->save()) throw new Exception('');
            }


            //图片上传
            $base64 = $request->post('result', '');
            $base64_arr = !empty($base64) ? explode('^#@#$,', $base64) : array();

            if (count($base64_arr) > 0) {
//                if (FixCarImg::find()->where('id=' . $id . ' AND type=' . $old_status)->count() >= 6) {
//                    $result['msg'] = '最多允许上传6张图片';
//                    return $result;
//                }
                //批量插入
                $table_name = FixCarImg::tableName();
                $field = ['fix_id', 'name', 'type'];
                $insert_data = [];
                foreach ($base64_arr as $base64_body) {
                    if (false === ($img = Upload::upload($base64_body))) continue;
                    array_push($insert_data, ['fix_id' => $id, 'name' => $img, 'type' => $old_status]);
                }
                if (!Yii::$app->db->createCommand()->batchInsert($table_name, $field, $insert_data)->execute()) throw new Exception('');
            }
            $result['success'] = true;
            $result['msg'] = '保存成功';
            $result['fix_id'] = $row->id;

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

    /**
     *------------------------------------------------------------
     *  清单删除
     * @param int id  fix_item_t表主键
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionFixItemRemove()
    {
        $request = Yii::$app->request;

        $result = [];
        $result['success'] = false;
        $result['msg'] = '删除失败!';

        if (!$request->isAjax) return $result;

        $id = $request->post('id', 0);
        $fix = FixItemT::findOne($id);
        if ($fix->delete()) {
            $result['success'] = true;
            $result['msg'] = '删除成功!';
            $result['fix_id'] = $fix->fix_id;
        }
        return $result;

    }

    /**
     *------------------------------------------------------------
     *  删除报案号
     * @param
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionRemoveReport(){
        $request = Yii::$app->request;

        $result = [];
        $result['success'] = false;
        $result['msg'] = '操作失败!';

        if(!$request->isAjax) return $result;

        $arr = $request->post('rem_arr');
        $ids = implode(',',$arr);
        if(FixCarReport::deleteAll('id IN ('.$ids.')')){
            $result['success'] = true;
            $result['msg'] = '操作成功!';
            $result['content'] = $arr;
        }

        return $result;
    }
    /*****************************************************  end  ******************************************************/


    /*********************************************前台派工*************************************************************/
    /**
     *------------------------------------------------------------
     *  前台派工
     * @param int status = 5
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionFrontDeskList()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        return $this->render('front-desk-list', $this->getList($request, $session));
    }

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

        $info = FixCarT::findOne(['id' => $id]);

        //报案号
        $reports = ($reports_res = FixCarReport::findAll(['fix_id'=>$id])) ? $reports_res : [];
        $report_nos = Json::encode($reports);

        return $this->render('front-desk-info', [
            'info' => $info,
            'direction_items' => $this->getDirection(),
            'range_items' => $this->getRange(),
            'log_items' => $this->getCarLog(intval($info->car_id)),
            'driver_items' => $this->getDrivers(),
            'brand_items' => $this->getBrands(),
            'series_items' => $this->getSeries(intval($info->brand_id)),
            'displacement_items' => $this->getDisplacement(intval($info->series_id)),
            'type' => $type,
            'gift_enable' => $gift_enable,
            'reports'=>$reports,
            'report_nos'=>$report_nos
        ]);
    }

    /**
     *------------------------------------------------------------
     *  前台派工提交操作
     * @param
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionFrontDeskSave()
    {
        $request = Yii::$app->request;

        if (!$request->isAjax) return Message::getMessage();

        $id = $request->post('id', 0);
        $follow_car_items = $request->post('follow_car_items');
        $sys_remark = $request->post('sys_remark', '');
        $status = $request->post('status');
        if ($id <= 0) return Message::getMessage();

        $tran = Yii::$app->db->beginTransaction();
        try{

            //没有添加任何清单,禁止进入下一个环节
            $items = FixCarItemT::find()->select('fix_group')->where(['fix_id' => $id, 'status' => 0, 'fix_status' => 0, 'fix_user' => 0, 'lock_id' => 0])->groupBy('fix_group')->asArray()->all();
            if (empty($items)) return Message::getMessage(false,'没有添加任何清单!');

            $groups = array_column($items,'fix_group');

            //更新
            $row = $id > 0 ? FixCarT::findOne($id) : NULL;
            $old_status = $row->status;
            $row->scenario = 'front-desk';
            $row->attributes = $request->post();
            $row->remark = $sys_remark;
            $row->status = $status;

            //如果没有添加任何机电项目,则标记机电项目为已完成
            if(!in_array(10,$groups) && !in_array(11,$groups)){
                $row->status_2 = 1;
            }
            //如果没有添加任何钣金项目,则标记钣金项目为已完成
            if(!in_array(7,$groups) && !in_array(13,$groups) && !in_array(14,$groups)){
                $row->status_1 = 1;
            }

            //如果有随车物品,则拼接为字符串
            if (!empty($follow_car_items)) $row->follow_car_items = implode($follow_car_items, ',');
            if (!$row->validate()) {
                $errors = array_values($row->errors);
                return Message::getMessage(false,$errors[0]);
            }
            if(!$row->save()) throw new Exception('fix_car_t更新失败!');

            //同步到财务
            $fix_car_item_t = FixCarItemT::find()->where('fix_id='.$id)->groupBy('report_id')->all();
            $item_data = [];
            foreach($fix_car_item_t as $item){
                array_push($item_data,['fix_id'=>$id,'car_no'=>$row->car_no,'id_man'=>$row->id_man,'engine_no'=>$row->engine_no,'baoanhao'=>$item->report_id ? $item->report->report_no : '']);
            }
            if (!Yii::$app->db->createCommand()->batchInsert(CarFinanceT::tableName(), ['fix_id','car_no','id_man','engine_no','baoanhao'], $item_data)->execute()) throw new Exception('a');

            //记录日志
            if ($old_status >= 0 && $row->status != $old_status) {
                $log_info = new CarLogT();
                $log_info->car_id = $id;
                $log_info->op_time = time();
                $log_info->op_man = $this->my->getShowName();
                $log_info->group_name = $this->my->group ? $this->my->group->getPath() : '';
                $log_info->type = 2;
                $log_info->remark = $row->getStatusMark($row->status);
                $log_info->info = $sys_remark;
                if (!$log_info->save()) throw new Exception('b');
            }

            $tran->commit();
            return Message::getMessage(true,'操作成功!');
        }catch(Exception $e){
            $tran->rollBack();
            return Message::getMessage(false,$e->getMessage());
        }
    }

    /**
     *------------------------------------------------------------
     *  前台派工清单添加
     * @param
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionFrontDeskInfoItemSave()
    {
        $request = Yii::$app->request;
        $small_type_id = $request->post('small_type_id');
        $name = $request->post('name');
        $count = $request->post('count', 1);
        $remark = $request->post('remark', '');
        $price = $request->post('price', 0);
        $fix_id = $request->post('fix_id');
        $pay_type = $request->post('pay_type');
        $type = $request->post('type', 0);
        $fix_user = $request->post('fix_user', 0);
        $id = $request->post('id', 0);
        $level = $request->post('level', 0);
        $insurance_price = $request->post('insurance_price', 0);

        $result = [];
        $result['success'] = false;
        $result['msg'] = '操作失败!';

        if (!$request->isAjax) return $result;

        // 当id 大于 0 并且 维修类型不为 汽车保养 则更新 ; 否则添加
        $fix_item = ($id > 0 && 5 != $small_type_id) ? FixItemT::findOne($id) : new FixItemT();

        switch ($small_type_id) {
            case 1: //更换清单
            case 2: //维修清单
            case 3: //辅料清单
            case 4: //待定清单
            case 6: //美容装饰
                $fix_item->name = $name;
                $fix_item->count = $count;
                $fix_item->fix_remark = $remark;
                $fix_item->price = $price;
                $fix_item->small_type_id = $small_type_id;
                $fix_item->fix_id = $fix_id;
                $fix_item->pay_type = $pay_type;
                $fix_item->type = $type;
                $fix_item->fix_user = $fix_user;
                $fix_item->damage_level = $level;
                $fix_item->insurance_price = $insurance_price;
                $fix_item->save();
                $result['success'] = true;
                $result['msg'] = '操作成功!';
                break;
            case 5: //汽车保养
                FixItemT::deleteAll('fix_id=' . $fix_id . ' AND small_type_id=5');
                foreach ($name as $k => $val) {
                    $type = strstr($val, '_');
                    $keep_in_good_id = rtrim(strstr($val, '_', true), '_');

                    if ('_0' == $type) {
                        $insert[$k]['name'] = '机油';
                        $insert[$k]['car_keep_in_good_id'] = $keep_in_good_id;

                    } elseif ('_1' == $type) {
                        $insert[$k]['name'] = '机油滤芯';
                        $insert[$k]['car_keep_in_good_id'] = $keep_in_good_id;
                    } elseif ('_2' == $type) {
                        $insert[$k]['name'] = '空气滤芯';
                        $insert[$k]['car_keep_in_good_id'] = $keep_in_good_id;
                    } elseif ('_3' == $type) {
                        $insert[$k]['name'] = '空调滤芯';
                        $insert[$k]['car_keep_in_good_id'] = $keep_in_good_id;
                    } elseif ('_4' == $type) {
                        $insert[$k]['name'] = '汽油滤芯';
                        $insert[$k]['car_keep_in_good_id'] = $keep_in_good_id;
                    }

                    $insert[$k]['price'] = $price;
                    $insert[$k]['count'] = $count;
                    $insert[$k]['fix_id'] = $fix_id;
                    $insert[$k]['small_type_id'] = $small_type_id;
                    $insert[$k]['pay_type'] = 2;
                }
                Yii::$app->db->createCommand()->batchInsert(FixItemT::tableName(), ['name', 'car_keep_in_good_id', 'price', 'count', 'fix_id', 'small_type_id', 'pay_type'], $insert)->execute();
                $result['success'] = true;
                $result['msg'] = '操作成功!';
                break;
        }
        return $result;
    }
    /**************************************************** end *********************************************************/

    /*************************************************  钣金 **********************************************************/
    /**
     *------------------------------------------------------------
     *  钣金列表
     * @param string where status = 5 AND id IN(fix_id)
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionMetalPlateList()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        return $this->render('metal-plate-list',$this->getList1($request,$session,self::METAL_PLATE));
    }

    public function actionMetalPlateInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $type = $request->get('type', 0);
        $gift_enable = $request->get('gift_enable', 0);
        $info = FixCarT::findOne(['id' => $id]);

        return $this->render('metal-plate-info', [
            'info' => $info,
//            'gift_items' => $gift_items,
            'direction_items' => $this->getDirection(),
            'range_items' => $this->getRange(),
            'log_items' => $this->getCarLog(intval($info->car_id)),
            'driver_items' =>  $this->getDrivers(),
            'brand_items' => $this->getBrands(),
            'series_items' => $this->getSeries(intval($info->brand_id)),
            'displacement_items' => $this->getDisplacement(intval($info->series_id)),
            'type' => $type,
            'gift_enable' => $gift_enable,
            'role' => self::METAL_PLATE,
        ]);
    }
    public function actionAjaxMetalPlateList(){
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $fix_id = $request->get('fix_id', 0);                       //fix_item表_t fix_id

        //fix_group = 7(钣金项目) 并且 status = 0 未总检
        $items = ($res = FixCarItemT::find()->where('fix_id='.$fix_id.' AND fix_user='.$this->my->id.' AND lock_id='.$this->my->id.' AND fix_group=7 AND status=0')->orWhere('fix_id='.$fix_id.' AND type=3')->all()) ? $res : [];
        $items = ArrayHelper::index(ArrayHelper::toArray($items),null,'type');
        $html = $this->renderPartial('ajax-metal-plate-list', [
            'items' => $items,
        ]);

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

    /**
     *------------------------------------------------------------
     *  钣金提交
     * @param
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionMetalPlateSave(){
        $request = Yii::$app->request;

        $id = $request->post('id', 0);
        $car_id = $request->post('car_id',0);
        $new_car_price = $request->post('new_car_price',0);
        $new_car_price = $this->handleNewCarPrice($new_car_price);
        $item_id = $request->post('item_id','');
        $status = $request->post('status',0);

        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if (!$request->isAjax || $id <= 0 || $car_id <= 0 || $new_car_price <= 0 || empty($item_id) || $status <= 0) return $result;

        $tran = FixCarT::getDb()->beginTransaction();
        try {
            $follow_car_items = $request->post('follow_car_items');
            $sys_remark = $request->post('sys_remark', '');

            $row = FixCarT::findOne(['id' => $id]);
            $old_status = $row->status;


            //场景选择
            $row->scenario = $row->getModelScenario();

            //批量赋值
            $row->attributes = $request->post();
            $row->remark = $sys_remark;

            //如果有随车物品,则拼接为字符串
            if (!empty($follow_car_items)) $row->follow_car_items = implode($follow_car_items, ',');

            //判断是否有喷漆
            $has_paint = false;
            if(!FixCarItemT::find()->where(['fix_id'=>$row->id,'fix_group'=>8,'status'=>0,'fix_status'=>0])->all()) $has_paint = true;

            if (!$row->validate()) {
                $errors = array_values($row->errors);
                $result['msg'] = $errors[0];
                return $result;
            }

            if ($old_status >= 0 && $row->status != $old_status) {
                $log_info = new CarLogT();
                $log_info->car_id = $car_id;
                $log_info->op_time = time();
                $log_info->op_man = $this->my->getShowName();
                $log_info->group_name = $this->my->group ? $this->my->group->getPath() : '';
                $log_info->type = 2;

                $log_info->remark = $row->getStatusMark($row->status);
                $log_info->info = $sys_remark;

                if (!$log_info->save()) throw new Exception('');
            }
            if (!$row->save()) throw new Exception('');

            //图片上传
            $base64 = $request->post('result', '');
            $base64_arr = !empty($base64) ? explode('^#@#$,', $base64) : array();

            if (count($base64_arr) > 0) {
                //批量插入
                $table_name = FixCarImg::tableName();
                $field = ['fix_id', 'name', 'type'];
                $insert_data = [];
                foreach ($base64_arr as $base64_body) {
                    if (false === ($img = Upload::upload($base64_body))) continue;
                    array_push($insert_data, ['fix_id' => $id, 'name' => $img, 'type' => $old_status]);
                }
                if (!Yii::$app->db->createCommand()->batchInsert($table_name, $field, $insert_data)->execute()) throw new Exception('');
            }

            $middle = MiddleFixCarT::findOne(['fix_id'=>$id,'type'=>1,'status'=>6]);
            $middle->status = $has_paint ? 9 : 7;
            if(!$middle->save()) throw new Exception('');

            $result['success'] = true;
            $result['msg'] = '保存成功';
            $result['fix_id'] = $row->id;

            $tran->commit();
        } catch (Exception $e) {
            $tran->rollBack();
        }
        return $result;
    }
    /***************************************************  end  *******************************************************/

    /****************************************************底子工********************************************************/
    public function actionBottomWorkList()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        return $this->render('bottom-work-list', $this->getList1($request,$session,self::BOTTOM_WORK));
    }

    public function actionBottomWorkInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $type = $request->get('type', 0);
        $gift_enable = $request->get('gift_enable', 0);
        $info = FixCarT::findOne(['id' => $id]);

        return $this->render('bottom-work-info', [
            'info' => $info,
//            'gift_items' => $gift_items,
            'direction_items' => $this->getDirection(),
            'range_items' => $this->getRange(),
            'log_items' => $this->getCarLog(intval($info->car_id)),
            'driver_items' => $this->getDrivers(),
            'brand_items' => $this->getBrands(),
            'series_items' =>  $this->getSeries(intval($info->brand_id)),
            'displacement_items' => $this->getDisplacement(intval($info->series_id)),
            'type' => $type,
            'gift_enable' => $gift_enable,
            'role' => self::BOTTOM_WORK,
        ]);
    }
    public function actionAjaxBottomWorkList(){
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $fix_id = $request->get('fix_id', 0);                       //fix_item表_t fix_id

        //fix_group = 7(钣金项目) 并且 status = 0 未总检
        $items = ($res = FixCarItemT::find()->where(['fix_id'=>$fix_id,'fix_user'=>$this->my->id,'lock_id'=>$this->my->id,'fix_group'=>13,'status'=>0])->orWhere(['fix_id'=>$fix_id,'type'=>3])->all()) ? $res : [];
        $items = ArrayHelper::index(ArrayHelper::toArray($items),null,'type');
        $html = $this->renderPartial('ajax-bottom-work-list', [
            'items' => $items,
        ]);

        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }
    public function actionBottomWorkSave(){
        $request = Yii::$app->request;

        $id = $request->post('id', 0);
        $car_id = $request->post('car_id',0);
        $new_car_price = $request->post('new_car_price',0);
        $new_car_price = $this->handleNewCarPrice($new_car_price);
        $item_id = $request->post('item_id','');

        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if (!$request->isAjax || $id <= 0 || $car_id <= 0 || $new_car_price <= 0 || empty($item_id)) return $result;

        $tran = FixCarT::getDb()->beginTransaction();
        try {
            $follow_car_items = $request->post('follow_car_items');
            $sys_remark = $request->post('sys_remark', '');

            $row = FixCarT::findOne(['id' => $id]);
            $old_status = $row->status;


            //场景选择
            $row->scenario = $row->getModelScenario();

            //批量赋值
            $row->attributes = $request->post();
            $row->remark = $sys_remark;

            //如果有随车物品,则拼接为字符串
            if (!empty($follow_car_items)) $row->follow_car_items = implode($follow_car_items, ',');

            if (!$row->validate()) {
                $errors = array_values($row->errors);
                $result['msg'] = $errors[0];
                return $result;
            }

            if ($old_status >= 0 && $row->status != $old_status) {
                $log_info = new CarLogT();
                $log_info->car_id = $car_id;
                $log_info->op_time = time();
                $log_info->op_man = $this->my->getShowName();
                $log_info->group_name = $this->my->group ? $this->my->group->getPath() : '';
                $log_info->type = 2;

                $log_info->remark = $row->getStatusMark($row->status);
                $log_info->info = $sys_remark;

                if (!$log_info->save()) throw new Exception('');
            }
            if (!$row->save()) throw new Exception('');

            //图片上传
            $base64 = $request->post('result', '');
            $base64_arr = !empty($base64) ? explode('^#@#$,', $base64) : array();

            if (count($base64_arr) > 0) {
                //批量插入
                $table_name = FixCarImg::tableName();
                $field = ['fix_id', 'name', 'type'];
                $insert_data = [];
                foreach ($base64_arr as $base64_body) {
                    if (false === ($img = Upload::upload($base64_body))) continue;
                    array_push($insert_data, ['fix_id' => $id, 'name' => $img, 'type' => $old_status]);
                }
                if (!Yii::$app->db->createCommand()->batchInsert($table_name, $field, $insert_data)->execute()) throw new Exception('');
            }
            $middle = MiddleFixCarT::findOne(['fix_id'=>$id,'type'=>1,'status'=>7]);
            $middle->status = 8;
            if(!$middle->save()) throw new Exception('');

            $result['success'] = true;
            $result['msg'] = '保存成功';
            $result['fix_id'] = $row->id;

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

    /****************************************************   end ******************************************************/

    /****************************************************喷漆工********************************************************/
    public function actionPaintWorkList()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        return $this->render('paint-work-list', $this->getList1($request, $session, self::PAINT_WORK));
    }

    public function actionPaintWorkInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $type = $request->get('type', 0);
        $gift_enable = $request->get('gift_enable', 0);
        $info = FixCarT::findOne(['id' => $id]);

        return $this->render('paint-work-info', [
            'info' => $info,
//            'gift_items' => $gift_items,
            'direction_items' => $this->getDirection(),
            'range_items' => $this->getRange(),
            'log_items' => $this->getCarLog(intval($info->car_id)),
            'driver_items' =>  $this->getDrivers(),
            'brand_items' => $this->getBrands(),
            'series_items' => $this->getSeries(intval($info->brand_id)),
            'displacement_items' => $this->getDisplacement(intval($info->series_id)),
            'type' => $type,
            'gift_enable' => $gift_enable,
            'role' => self::PAINT_WORK,
        ]);
    }
    public function actionAjaxPaintWorkList(){
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $fix_id = $request->get('fix_id', 0);                       //fix_item表_t fix_id

        //fix_group = 7(钣金项目) 并且 status = 0 未总检
        $items = ($res = FixCarItemT::find()->where(['fix_id'=>$fix_id,'fix_user'=>$this->my->id,'lock_id'=>$this->my->id,'fix_group'=>8,'status'=>0])->orWhere(['fix_id'=>$fix_id,'type'=>3])->all()) ? $res : [];
        $items = ArrayHelper::index(ArrayHelper::toArray($items),null,'type');
        $html = $this->renderPartial('ajax-paint-work-list', [
            'items' => $items,
        ]);

        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }
    public function actionPaintWorkSave(){
        $request = Yii::$app->request;

        $id = $request->post('id', 0);
        $car_id = $request->post('car_id',0);
        $new_car_price = $request->post('new_car_price',0);
        $new_car_price = $this->handleNewCarPrice($new_car_price);
        $item_id = $request->post('item_id','');

        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if (!$request->isAjax || $id <= 0 || $car_id <= 0 || $new_car_price <= 0 || empty($item_id)) return $result;

        $tran = FixCarT::getDb()->beginTransaction();
        try {
            $follow_car_items = $request->post('follow_car_items');
            $sys_remark = $request->post('sys_remark', '');

            $row = FixCarT::findOne(['id' => $id]);
            $old_status = $row->status;


            //场景选择
            $row->scenario = $row->getModelScenario();

            //批量赋值
            $row->attributes = $request->post();
            $row->remark = $sys_remark;

            //如果有随车物品,则拼接为字符串
            if (!empty($follow_car_items)) $row->follow_car_items = implode($follow_car_items, ',');

            $is_facial = false;
            //判断是否有钣金
            if(!FixCarItemT::find()->where(['fix_id'=>$row->id,'fix_group'=>7,'fix_status'=>1,'metal_plate_install'=>0,'status'=>0])->all()) $is_facial = true;

            //没有钣金,则默认已通过钣金安装
            if($is_facial) $row->status_1 = 1;
            if (!$row->validate()) {
                $errors = array_values($row->errors);
                $result['msg'] = $errors[0];
                return $result;
            }

            if (!$row->save()) throw new Exception('');

            if ($old_status >= 0 && $row->status != $old_status) {
                $log_info = new CarLogT();
                $log_info->car_id = $car_id;
                $log_info->op_time = time();
                $log_info->op_man = $this->my->getShowName();
                $log_info->group_name = $this->my->group ? $this->my->group->getPath() : '';
                $log_info->type = 2;

                $log_info->remark = $row->getStatusMark($row->status);
                $log_info->info = $sys_remark;

                if (!$log_info->save()) throw new Exception('');
            }

            //图片上传
            $base64 = $request->post('result', '');
            $base64_arr = !empty($base64) ? explode('^#@#$,', $base64) : array();

            if (count($base64_arr) > 0) {
                //批量插入
                $table_name = FixCarImg::tableName();
                $field = ['fix_id', 'name', 'type'];
                $insert_data = [];
                foreach ($base64_arr as $base64_body) {
                    if (false === ($img = Upload::upload($base64_body))) continue;
                    array_push($insert_data, ['fix_id' => $id, 'name' => $img, 'type' => $old_status]);
                }
                if (!Yii::$app->db->createCommand()->batchInsert($table_name, $field, $insert_data)->execute()) throw new Exception('');
            }

            $middle = MiddleFixCarT::findOne(['fix_id'=>$id,'type'=>1,'status'=>8]);

            //判断是否有钣金,有则提交到钣金安装,否则直接到美容
            $middle->status = $is_facial ? 13 : 9;

            if(!$middle->save()) throw new Exception('');

            $result['success'] = true;
            $result['msg'] = '保存成功';
            $result['fix_id'] = $row->id;

            $tran->commit();
        } catch (Exception $e) {
            $tran->rollBack();
        }
        return $result;
    }
    /****************************************************   end ******************************************************/

    /**************************************************钣金安装********************************************************/
    public function actionMetalPlateInstallList()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        return $this->render('metal-plate-install-list', $this->getList1($request, $session, self::METAL_PLATE_INSTALL));
    }

    public function actionMetalPlateInstallInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $type = $request->get('type', 0);
        $gift_enable = $request->get('gift_enable', 0);
        $info = FixCarT::findOne(['id' => $id]);

        return $this->render('metal-plate-install-info', [
            'info' => $info,
//            'gift_items' => $gift_items,
            'direction_items' => $this->getDirection(),
            'range_items' => $this->getRange(),
            'log_items' => $this->getCarLog(intval($info->car_id)),
            'driver_items' => $this->getDrivers(),
            'brand_items' => $this->getBrands(),
            'series_items' => $this->getSeries(intval($info->brand_id)),
            'displacement_items' => $this->getDisplacement(intval($info->series_id)),
            'type' => $type,
            'gift_enable' => $gift_enable,
            'role' => self::METAL_PLATE_INSTALL,
        ]);
    }
    public function actionAjaxMetalPlateInstallList(){
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $fix_id = $request->get('fix_id', 0);                       //fix_item表_t fix_id

        //fix_group = 7(钣金项目) 并且 status = 0 未总检
        $items = ($res = FixCarItemT::find()->where(['fix_id'=>$fix_id,'fix_user'=>$this->my->id,'lock_id'=>$this->my->id,'fix_group'=>7,'fix_status'=>1,'status'=>0])->orWhere(['fix_id'=>$fix_id,'type'=>3])->all()) ? $res : [];
        $items = ArrayHelper::index(ArrayHelper::toArray($items),null,'type');
        $html = $this->renderPartial('ajax-metal-plate-install-list', [
            'items' => $items,
        ]);

        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }
    public function actionMetalPlateInstallSave(){
        $request = Yii::$app->request;

        $id = $request->post('id', 0);
        $car_id = $request->post('car_id',0);
        $new_car_price = $request->post('new_car_price',0);
        $new_car_price = $this->handleNewCarPrice($new_car_price);
        $item_id = $request->post('item_id','');

        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if (!$request->isAjax || $id <= 0 || $car_id <= 0 || $new_car_price <= 0 || empty($item_id)) return $result;

        $tran = FixCarT::getDb()->beginTransaction();
        try {
            $follow_car_items = $request->post('follow_car_items');
            $sys_remark = $request->post('sys_remark', '');

            $row = FixCarT::findOne(['id' => $id]);
            $old_status = $row->status;


            //场景选择
            $row->scenario = $row->getModelScenario();

            //批量赋值
            $row->attributes = $request->post();
            $row->status_1 = 1;
            $row->remark = $sys_remark;

            //如果有随车物品,则拼接为字符串
            if (!empty($follow_car_items)) $row->follow_car_items = implode($follow_car_items, ',');

            if (!$row->validate()) {
                $errors = array_values($row->errors);
                $result['msg'] = $errors[0];
                return $result;
            }

            if ($old_status >= 0 && $row->status != $old_status) {
                $log_info = new CarLogT();
                $log_info->car_id = $car_id;
                $log_info->op_time = time();
                $log_info->op_man = $this->my->getShowName();
                $log_info->group_name = $this->my->group ? $this->my->group->getPath() : '';
                $log_info->type = 2;

                $log_info->remark = $row->getStatusMark($row->status);
                $log_info->info = $sys_remark;

                if (!$log_info->save()) throw new Exception('');
            }
            if (!$row->save()) throw new Exception('');

            //图片上传
            $base64 = $request->post('result', '');
            $base64_arr = !empty($base64) ? explode('^#@#$,', $base64) : array();

            if (count($base64_arr) > 0) {
                //批量插入
                $table_name = FixCarImg::tableName();
                $field = ['fix_id', 'name', 'type'];
                $insert_data = [];
                foreach ($base64_arr as $base64_body) {
                    if (false === ($img = Upload::upload($base64_body))) continue;
                    array_push($insert_data, ['fix_id' => $id, 'name' => $img, 'type' => $old_status]);
                }
                if (!Yii::$app->db->createCommand()->batchInsert($table_name, $field, $insert_data)->execute()) throw new Exception('');
            }

            $middle = MiddleFixCarT::findOne(['fix_id'=>$id,'type'=>1,'status'=>9]);
            $middle->status = 13;
            if(!$middle->save()) throw new Exception('');

            $result['success'] = true;
            $result['msg'] = '保存成功';
            $result['fix_id'] = $row->id;

            $tran->commit();
        } catch (Exception $e) {
            $tran->rollBack();
        }
        return $result;
    }
    /****************************************************   end ******************************************************/

    /************************************************** 机电  ********************************************************/
    public function actionElectromechanicalList()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        return $this->render('electromechanical-list', $this->getList1($request, $session, self::ELECTROMECHANICAL));
    }

    public function actionElectromechanicalInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $type = $request->get('type', 0);
        $gift_enable = $request->get('gift_enable', 0);
        $info = FixCarT::findOne(['id' => $id]);

        return $this->render('electromechanical-info', [
            'info' => $info,
//            'gift_items' => $gift_items,
            'direction_items' => $this->getDirection(),
            'range_items' => $this->getRange(),
            'log_items' => $this->getCarLog(intval($info->car_id)),
            'driver_items' => $this->getDrivers(),
            'brand_items' => $this->getBrands(),
            'series_items' => $this->getSeries(intval($info->brand_id)),
            'displacement_items' => $this->getDisplacement(intval($info->series_id)),
            'type' => $type,
            'gift_enable' => $gift_enable,
            'role' => self::ELECTROMECHANICAL,
        ]);
    }
    public function actionAjaxElectromechanicalList(){
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $fix_id = $request->get('fix_id', 0);                       //fix_item表_t fix_id

        //fix_group = 7(钣金项目) 并且 status = 0 未总检
        $items = ($res = FixCarItemT::find()->where('fix_id='.$fix_id.' AND fix_user='.$this->my->id.' AND lock_id='.$this->my->id.' AND fix_group IN(10,11) AND status=0' )->orWhere(['fix_id'=>$fix_id,'type'=>3])->all()) ? $res : [];
        $items = ArrayHelper::index(ArrayHelper::toArray($items),null,'type');
        $html = $this->renderPartial('ajax-electromechanical-list', [
            'items' => $items,
        ]);

        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }
    public function actionElectromechanicalSave(){
        $request = Yii::$app->request;

        $id = $request->post('id', 0);
        $car_id = $request->post('car_id',0);
        $new_car_price = $request->post('new_car_price',0);
        $new_car_price = $this->handleNewCarPrice($new_car_price);

        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if (!$request->isAjax || $id <= 0 || $car_id <= 0 || $new_car_price <= 0) return $result;

        $tran = FixCarT::getDb()->beginTransaction();
        try {
            $follow_car_items = $request->post('follow_car_items');
            $sys_remark = $request->post('sys_remark', '');

            $row = FixCarT::findOne(['id' => $id]);
            $old_status = $row->status;


            //场景选择
            $row->scenario = $row->getModelScenario();

            //批量赋值
            $row->attributes = $request->post();
            $row->status_2 = 1;
            $row->remark = $sys_remark;

            //如果有随车物品,则拼接为字符串
            if (!empty($follow_car_items)) $row->follow_car_items = implode($follow_car_items, ',');

            if (!$row->validate()) {
                $errors = array_values($row->errors);
                $result['msg'] = $errors[0];
                return $result;
            }

            if ($old_status >= 0 && $row->status != $old_status) {
                $log_info = new CarLogT();
                $log_info->car_id = $car_id;
                $log_info->op_time = time();
                $log_info->op_man = $this->my->getShowName();
                $log_info->group_name = $this->my->group ? $this->my->group->getPath() : '';
                $log_info->type = 2;

                $log_info->remark = $row->getStatusMark($row->status);
                $log_info->info = $sys_remark;

                if (!$log_info->save()) throw new Exception('');
            }
            if (!$row->save()) throw new Exception('');

            //图片上传
            $base64 = $request->post('result', '');
            $base64_arr = !empty($base64) ? explode('^#@#$,', $base64) : array();

            if (count($base64_arr) > 0) {
                //批量插入
                $table_name = FixCarImg::tableName();
                $field = ['fix_id', 'name', 'type'];
                $insert_data = [];
                foreach ($base64_arr as $base64_body) {
                    if (false === ($img = Upload::upload($base64_body))) continue;
                    array_push($insert_data, ['fix_id' => $id, 'name' => $img, 'type' => $old_status]);
                }
                if (!Yii::$app->db->createCommand()->batchInsert($table_name, $field, $insert_data)->execute()) throw new Exception('');
            }

            $middle = MiddleFixCarT::findOne(['fix_id'=>$id,'type'=>2,'status'=>11]);
            $middle->status = 13;
            if(!$middle->save()) throw new Exception('');

            $result['success'] = true;
            $result['msg'] = '保存成功';
            $result['fix_id'] = $row->id;

            $tran->commit();
        } catch (Exception $e) {
            $tran->rollBack();
        }
        return $result;
    }
    /****************************************************   end ******************************************************/

    /************************************************** 洗车  *****************************************************/
    public function actionCarWashList()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        return $this->render('car-wash-list', $this->getList1($request, $session, self::CAR_WASH));
    }

    public function actionCarWashInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $type = $request->get('type', 0);
        $gift_enable = $request->get('gift_enable', 0);
        $info = FixCarT::findOne(['id' => $id]);

        return $this->render('car-wash-info', [
            'info' => $info,
            'direction_items' => $this->getDirection(),
            'range_items' => $this->getRange(),
            'log_items' => $this->getCarLog(intval($info->car_id)),
            'driver_items' => $this->getDrivers(),
            'brand_items' =>$this->getBrands(),
            'series_items' => $this->getSeries(intval($info->brand_id)),
            'displacement_items' => $this->getDisplacement(intval($info->series_id)),
            'type' => $type,
            'gift_enable' => $gift_enable,
            'role' => self::CAR_WASH,
        ]);
    }
    public function actionAjaxCarWashList(){
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $fix_id = $request->get('fix_id', 0);                       //fix_item表_t fix_id

        //fix_group = 7(钣金项目) 并且 status = 0 未总检
        $items = ($res = FixCarItemT::find()->where(['fix_id'=>$fix_id,'type'=>3])->orWhere(['fix_id'=>$fix_id,'type'=>5])->all()) ? $res : [];
        $items = ArrayHelper::index(ArrayHelper::toArray($items),null,'type');
        $html = $this->renderPartial('ajax-car-wash-list', [
            'items' => $items,
        ]);

        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }
    public function actionCarWashSave(){
        $request = Yii::$app->request;

        $id = $request->post('id', 0);
        $car_id = $request->post('car_id',0);
        $new_car_price = $request->post('new_car_price',0);
        $new_car_price = $this->handleNewCarPrice($new_car_price);
        $status = $request->post('status');

        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if (!$request->isAjax || $id < 1 || $car_id < 1 || $new_car_price < 1 || $status < 1) return $result;

        $tran = FixCarT::getDb()->beginTransaction();
        try {
            $follow_car_items = $request->post('follow_car_items');
            $sys_remark = $request->post('sys_remark', '');

            $row = FixCarT::findOne(['id' => $id]);
            $old_status = $row->status;
            $row->status = $status;


            //场景选择
            $row->scenario = $row->getModelScenario();

            //批量赋值
            $row->attributes = $request->post();
            $row->remark = $sys_remark;

            //如果有随车物品,则拼接为字符串
            if (!empty($follow_car_items)) $row->follow_car_items = implode($follow_car_items, ',');

            if (!$row->validate()) {
                $errors = array_values($row->errors);
                $result['msg'] = $errors[0];
                return $result;
            }

            if ($old_status >= 0 && $row->status != $old_status) {
                $log_info = new CarLogT();
                $log_info->car_id = $car_id;
                $log_info->op_time = time();
                $log_info->op_man = $this->my->getShowName();
                $log_info->group_name = $this->my->group ? $this->my->group->getPath() : '';
                $log_info->type = 2;

                $log_info->remark = $row->getStatusMark($row->status);
                $log_info->info = $sys_remark;

                if (!$log_info->save()) throw new Exception('');
            }
            if (!$row->save()) throw new Exception('a');

            //图片上传
            $base64 = $request->post('result', '');
            $base64_arr = !empty($base64) ? explode('^#@#$,', $base64) : array();

            if (count($base64_arr) > 0) {
                //批量插入
                $table_name = FixCarImg::tableName();
                $field = ['fix_id', 'name', 'type'];
                $insert_data = [];
                foreach ($base64_arr as $base64_body) {
                    if (false === ($img = Upload::upload($base64_body))) continue;
                    array_push($insert_data, ['fix_id' => $id, 'name' => $img, 'type' => $old_status]);
                }
                if (!Yii::$app->db->createCommand()->batchInsert($table_name, $field, $insert_data)->execute()) throw new Exception('');
            }

            if(14 == $status) {
                $middle_fix_car_t = MiddleFixCarT::findOne(['fix_id' => $id, 'type' => 1, 'status' => 13]);
                $middle_fix_car_t->status = 14;
                if (!$middle_fix_car_t->save()) throw new Exception('操作失败!');
            }
            $result['success'] = true;
            $result['msg'] = '保存成功';
            $result['fix_id'] = $row->id;

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

    /****************************************************   end ******************************************************/

    /******************************************************  总检  ****************************************************/
    public function actionLastCheckList()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        return $this->render('last-check-list', $this->getList($request, $session,self::LAST_CHECK));
    }

    public function actionLastCheckInfo()
    {
        $request = Yii::$app->request;
        $id = $request->get('id', 0);
        $type = $request->get('type', 0);
        $gift_enable = $request->get('gift_enable', 0);
        $info = FixCarT::findOne(['id' => $id]);

        return $this->render('last-check-info', [
            'info' => $info,
//            'gift_items' => $gift_items,
            'direction_items' => $this->getDirection(),
            'range_items' => $this->getRange(),
            'log_items' => $this->getCarLog(intval($info->car_id)),
            'driver_items' =>  $this->getDrivers(),
            'brand_items' => $this->getBrands(),
            'series_items' => $this->getSeries(intval($info->brand_id)),
            'displacement_items' => $this->getDisplacement(intval($info->series_id)),
            'type' => $type,
            'gift_enable' => $gift_enable,
        ]);
    }
    public function actionAjaxLastCheckList(){
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $fix_id = $request->get('fix_id', 0);                       //fix_item表_t fix_id

        //fix_group = 7(钣金项目) 并且 status = 0 未总检
        $items = ($res = FixCarItemT::find()->where('fix_id='.$fix_id.' AND fix_group!=13')->all()) ? $res : [];
        $items = ArrayHelper::index(ArrayHelper::toArray($items),null,'type');
        $html = $this->renderPartial('ajax-last-check-list', [
            'items' => $items,
        ]);

        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }
    public function actionLastCheckSave(){
        $request = Yii::$app->request;

        $id = $request->post('id', 0);
        $car_id = $request->post('car_id',0);
        $new_car_price = $request->post('new_car_price',0);
        $new_car_price = $this->handleNewCarPrice($new_car_price);

        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if (!$request->isAjax || $id <= 0 || $car_id <= 0 || $new_car_price <= 0) return $result;

        $tran = FixCarT::getDb()->beginTransaction();
        try {
            $follow_car_items = $request->post('follow_car_items');
            $sys_remark = $request->post('sys_remark', '');

            $row = FixCarT::findOne(['id' => $id]);
            $old_status = $row->status;


            //场景选择
            $row->scenario = $row->getModelScenario();

            //批量赋值
            $row->attributes = $request->post();
            $row->remark = $sys_remark;

            //如果有随车物品,则拼接为字符串
            if (!empty($follow_car_items)) $row->follow_car_items = implode($follow_car_items, ',');

            if (!$row->validate()) {
                $errors = array_values($row->errors);
                $result['msg'] = $errors[0];
                return $result;
            }

            if ($old_status >= 0 && $row->status != $old_status) {
                $log_info = new CarLogT();
                $log_info->car_id = $car_id;
                $log_info->op_time = time();
                $log_info->op_man = $this->my->getShowName();
                $log_info->group_name = $this->my->group ? $this->my->group->getPath() : '';
                $log_info->type = 2;

                $log_info->remark = $row->getStatusMark($row->status);
                $log_info->info = $sys_remark;

                if (!$log_info->save()) throw new Exception('');
            }
            if (!$row->save()) throw new Exception('a');

            //图片上传
            $base64 = $request->post('result', '');
            $base64_arr = !empty($base64) ? explode('^#@#$,', $base64) : array();

            if (count($base64_arr) > 0) {
                //批量插入
                $table_name = FixCarImg::tableName();
                $field = ['fix_id', 'name', 'type'];
                $insert_data = [];
                foreach ($base64_arr as $base64_body) {
                    if (false === ($img = Upload::upload($base64_body))) continue;
                    array_push($insert_data, ['fix_id' => $id, 'name' => $img, 'type' => $old_status]);
                }
                if (!Yii::$app->db->createCommand()->batchInsert($table_name, $field, $insert_data)->execute()) throw new Exception('');
            }
            $result['success'] = true;
            $result['msg'] = '保存成功';
            $result['fix_id'] = $row->id;

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

    /*********************************************公共方法*************************************************************/

    /**
     *------------------------------------------------------------
     *  清单添加 art.dialog
     * @param int fix_id fix_car_t 主键 及 fix_item_t 表外键
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionDialogBox()
    {
        $request = Yii::$app->request;

        $fix_id = $request->get('fix_id', 0);
        $type = $request->get('type', 0);
        $info = $request->get('info', 0);

        $data = [
            'fix_id' => $fix_id,
            'type' => $type
        ];
        if ($info > 0) {
            $id = $request->get('id', 0);
            $info = FixItemT::findOne($id);

            $gid = $info->userT->group_id;
            $user = UserT::findAll(['group_id' => $gid]);
            $data['info'] = $info;
            $data['user'] = $user;
        }
        return $this->render('dialog-box', $data);
    }

    public function actionFixUserSibling()
    {
        $request = Yii::$app->request;

        $result = [];
        $result['success'] = false;
        if (!$request->isAjax) return $result;

        $fix_user = $request->post('fix_user', 0);
        $gid = UserT::findOne($fix_user)->group_id;
        if ($gid <= 0) return $result;

        $siblings = UserT::find()->where(['group_id' => $gid])->all();
        if ($siblings) {
            $result['success'] = true;
            $result['content'] = $siblings;
        }
        return $result;
    }

    public function actionFixCarSave()
    {
        $request = Yii::$app->request;

        $result = array();
        $result['success'] = false;
        $result['msg'] = '保存失败';

        if (!$request->isAjax) return $result;
        $tran = FixCarT::getDb()->beginTransaction();
        try {
            $id = $request->post('id', 0);
            $follow_car_items = $request->post('follow_car_items');
            $car_id = $request->post('car_id');
            $sys_remark = $request->post('sys_remark', '');

            $row = null;
            if ($id > 0) {
                $row = FixCarT::findOne(['id' => $id]);
                $old_status = $row->status;
            } else {
                if (!($row = FixCarT::findOne(['car_id' => $car_id]))) {
                    $row = new FixCarT();
                }
                $old_status = 0;
            }

            //场景选择
            $row->scenario = $row->getModelScenario();

            //批量赋值
            $row->attributes = $request->post();

            $row->remark = $sys_remark;

            //如果有随车物品,则拼接为字符串
            if (!empty($follow_car_items)) $row->follow_car_items = implode($follow_car_items, ',');

            if (!$row->validate()) {
                $errors = array_values($row->errors);
                $result['msg'] = $errors[0];
                return $result;
            }

            //新增
            if ($row->isNewRecord) {
                $row->submit_date = date('Y-m-d');
                $row->user_id = $this->my->id;
            }

            if ($old_status >= 0 && $row->status != $old_status) {
                $log_info = new CarLogT();
                $log_info->car_id = $car_id;
                $log_info->op_time = time();
                $log_info->op_man = $this->my->getShowName();
                $log_info->group_name = $this->my->group ? $this->my->group->getPath() : '';
                $log_info->type = 2;

                //提单审核 提交
                //上门接车 && (自费维修 || 保险理赔),都进入司机接车
                if ((2 == $row->status) && ('上门接车' == $row->receive_type)) {
                    $row->status = 2;
                } //客户自送 && 自费维修,则直接进入前台审核
                elseif (2 == $row->status && ('客户自送' == $row->receive_type)) {
                    $row->status = 3;
                }

                //前台审核 提交
                if (4 == $row->status && '自费维修' == $row->accident_type) {
                    $row->status = 5;
                }

                $log_info->remark = $row->getStatusMark($row->status);
                $log_info->info = $sys_remark;

                if (!$log_info->save()) throw new Exception('');
            }

//            //已进入车间维修
//            if(6 == $row->status){
//                $groups = FixCarItemT::find()->select('fix_group')->where(['fix_id' => $id, 'status' => 0, 'fix_status' => 0, 'fix_user' => 0, 'lock_id' => 0])->groupBy('fix_group')->asArray()->all();
//                $groups = array_column($groups,'fix_group');
//                //如果有机电项目,则标记机电为未完成
//                if(in_array(10,$groups) || in_array(11,$groups)){
//                    $row->status_2 = 0;
//                    $middle_fix_car_t = MiddleFixCarT::findOne(['fix_id'=>$id,'type'=>2,'status'=>13]);
//                    if($middle_fix_car_t){
//                        $middle_fix_car_t->status=11;
//                        $middle_fix_car_t->save();
//                    }
//                }
//
//                //如果有钣金项目,则标记钣金为未完成
//                if(in_array(7,$groups) || in_array(13,$groups) || in_array(14,$groups)){
//                    $row->status_1 = 0;
//                    $middle_fix_car_t = MiddleFixCarT::findOne(['fix_id'=>$id,'type'=>1,'status'=>13]);
//                    if($middle_fix_car_t){
//                        $middle_fix_car_t->status=6;
//                        $middle_fix_car_t->save();
//                    }
//                }
//            }
            if (!$row->save()) throw new Exception('');


            //图片上传
            $base64 = $request->post('result', '');
            $base64_arr = !empty($base64) ? explode('^#@#$,', $base64) : array();

            if (count($base64_arr) > 0) {
                //批量插入
                $table_name = FixCarImg::tableName();
                $field = ['fix_id', 'name', 'type'];
                $insert_data = [];
                foreach ($base64_arr as $base64_body) {
                    if (false === ($img = Upload::upload($base64_body))) continue;
                    array_push($insert_data, ['fix_id' => $id, 'name' => $img, 'type' => $old_status]);
                }
                if (!Yii::$app->db->createCommand()->batchInsert($table_name, $field, $insert_data)->execute()) throw new Exception('');
            }
            $result['success'] = true;
            $result['msg'] = '保存成功';
            $result['fix_id'] = $row->id;

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

    /**
     *------------------------------------------------------------
     *
     * @param int fix_id fix_item表_t fix_id
     * @param int pay_type 保险理赔、自费维修
     * @param int small_type_id 对应 更换清单、维修清单、辅料清单、待定清单、汽车保养、美容装饰 其中一种
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionAjaxItemList()
    {
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $fix_id = $request->get('fix_id', 0);                       //fix_item表_t fix_id

        $fix_items = null;

        $items = FixCarItemT::findAll(['fix_id'=>$fix_id]);

        var_dump(ArrayHelper::index(ArrayHelper::toArray($items),null,'type'));
        die;
        $html = $this->renderPartial('ajax-item-list', [
            'insurances' => $insurances_after_group,
            'facial' => $facial,
            'maintenance' => $maintenance,
            'self_paying' => $self_paying_after_group
        ]);
        $result['success'] = true;
        $result['html'] = $html;
        return $result;
    }

    public function actionAjaxItemListBak()
    {
        $request = Yii::$app->request;
        $result['success'] = false;
        $result['msg'] = '读取失败';

        $fix_id = $request->get('fix_id', 0);                       //fix_item表_t fix_id
        $pay_type = $request->get('pay_type', 0);                   //pay_type 保险理赔、自费维修
        $small_type_id = $request->get('small_type_id', 0);         //small_type_id 对应 更换清单、维修清单、辅料清单、待定清单、汽车保养、美容装饰 其中一种
        $role = $request->get('role', '');                          //role 对应钣金、底子工...

        //钣金分组
        $role_id = $role ? $this->getRoleId($role) : 0;

        $query = null;
        $query = FixItemT::find();

        $type1_items = [];
        if (1 == $pay_type && $small_type_id === 0) {
            $query = $query->where('fix_id=' . $fix_id . ' and pay_type=' . $pay_type . ' AND small_type_id BETWEEN 1 AND 4');
            if (0 !== $role_id) $query = $query->andWhere('type = ' . $role_id);
            $type1_items = $query->all();
            $arr = [];
            foreach ($type1_items as $k => $v) {
                if (!$v->small_type_id) continue;
                $arr[$v->small_type_id][] = $v;
            }
            $type1_items = $arr;
        }

        $type2_items = [];
        if (2 == $pay_type && $small_type_id === 0) {
            $query = $query->where('fix_id=' . $fix_id . ' and pay_type=' . $pay_type . ' AND small_type_id BETWEEN 1 AND 4');
            if (0 !== $role_id) $query = $query->andWhere('type = ' . $role_id);
            $type2_items = $query->all();
            $arr = [];
            foreach ($type2_items as $k => $v) {
                if (!$v->small_type_id) continue;
                $arr[$v->small_type_id][] = $v;
            }
            $type2_items = $arr;
        }

        $type3_items = [];
        $query = $query->where('fix_id=' . $fix_id . ' AND small_type_id=' . $small_type_id);
        if (0 !== $role_id) $query = $query->andWhere('type = ' . $role_id);
        $type3_items = $query->all();
        if ($type3_items) {
            $arr = [];
            foreach ($type3_items as $k => $v) {
                if (5 != $v->small_type_id) continue;
                $arr[$v->small_type_id][] = $v;
            }
            $type3_items = $arr;
        }

        $type4_items = [];
        $query = $query->where('fix_id=' . $fix_id . ' AND small_type_id=' . $small_type_id);
        if (0 !== $role_id) $query = $query->andWhere('type = ' . $role_id);
        $type4_items = $query->all();
        if ($type4_items) {
            $arr = [];
            foreach ($type4_items as $k => $v) {
                if (6 != $v->small_type_id) continue;
                $arr[$v->small_type_id][] = $v;
            }
            $type4_items = $arr;
        }

        $query = $query->where('fix_id=' . $fix_id . ' and big_type_id=5 and pay_type NOT IN(1,2)');
        if (0 !== $role_id) $query = $query->andWhere('type = ' . $role_id);
        $type5_items = $query->all();
        $html = $this->renderPartial('ajax-item-list', [
            'type1_items' => $type1_items,
            'type2_items' => $type2_items,
            'type3_items' => $type3_items,
            'type4_items' => $type4_items,
            'type5_items' => $type5_items
        ]);
        $result['success'] = true;
        $result['msg'] = '读取成功';
        $result['html'] = $html;
        return $result;
    }

    public function actionPrintOrder()
    {
        $request = Yii::$app->request;
        var_dump($request->post());
        die;
    }

    /**
     *------------------------------------------------------------
     *  维修已完成操作
     * @param   int id fix_item_t 表 id
     * @return json $result
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionFixItemFinish()
    {
        $result = [];
        $result['success'] = false;
        $result['msg'] = '操作失败!';

        $request = Yii::$app->request;
        if (!$request->isAjax) return $result;

        $id = $request->post('id', 0);
        if (0 == $id) return $result;

        $fix_item = FixItemT::findOne($id);
        $fix_item->status = 1;
        $fix_item->save();

        $result['success'] = true;
        $result['msg'] = '操作成功';
        $result['status'] = self::FIX_FINISH;

        return $result;
    }

    /**
     *------------------------------------------------------------
     *  根据角色名获取对应id
     * @param string $name , default null
     * @return int role_t 表id
     * @author liuyingjie
     *------------------------------------------------------------
     */
    private function getRoleId($name = null)
    {
        $role = null;
        if (is_null($name)) return 0;
        if (!($role = RoleT::findOne(['name' => $name]))) return 0;
        return ArrayHelper::getValue($role, 'id');
    }

    /**
     *------------------------------------------------------------
     *  损伤程度
     * @param
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionGetDamageLevel()
    {
        $request = Yii::$app->request;

        $result = [];
        $result['success'] = false;
        $result['msg'] = '操作失败!';

        if (!$request->isAjax) return $result;

        $level = $request->post('level');
        $id = $request->post('id');

        if ($level <= 0 || $id <= 0) return $result;

        $middles = MiddleDamageLevel::find()->where('metal_id=' . $id . ' AND level=' . $level)->one();

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

        return $result;
    }

    public function actionGetMetalPlate()
    {
        $request = Yii::$app->request;

        $result = [];
        $result['success'] = false;
        $result['msg'] = '操作失败!';

        if (!$request->isAjax) return $result;

        $name = $request->post('search');

        if (empty($name)) return $result;

        $parts = MetalPlatePart::find()->where(['like', 'name', $name])->all();

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

        return $result;
    }

    /**
     *------------------------------------------------------------
     *  根据维修部位、新车购置价 查询自费单价
     * @param string name 维修部位
     * @param int price 新车购置价
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionGetSelfFree()
    {
        $request = Yii::$app->request;

        $result = [];
        $result['success'] = false;
        $result['msg'] = '操作失败!';

        if (!$request->isAjax) return $result;

        $name = $request->post('name', '');
        $car_price = $request->post('price', 0);
        $level = $request->post('level');

        $i = $m = null;
        if ($car_price >= 3) {
            $len = strlen($car_price);
            switch ($len) {
                case 1:
                    break;
                case 2:
                    $car_price = floor(doubleval($car_price / 10)) * 10;
                    break;
                case 3:
                    $car_price = floor(doubleval($car_price / 100)) * 100;
                    break;
            }

            $i = MetalPlatePart::find()->where('name=\'' . $name . '\'')->one();
//            $m = MiddleParintPrice::find()->where('metal_id=' . $i->id . ' AND min_price=' . $car_price)->one();
            $m = MiddleDamageLevel::find()->where('metal_id='.$i->id.' AND level='.$level)->one();
        }

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

        return $result;
    }

    /**
     *------------------------------------------------------------
     *  根据配件名获取自费单价
     * @param
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionGetPriceByShop()
    {
        $request = Yii::$app->request;

        $name = $request->post('name');
        $price = $request->post('price');

        $result = [];
        $result['success'] = true;
        $result['msg'] = '操作失败!';

        if (!$request->isAjax || empty($name) || empty($price)) return $result;

        $i = $s = $m = null; //初始化

        //格式化新车购置价
        if ($price >= 3) {
            $len = strlen($price);
            switch ($len) {
                case 1:
                    break;
                case 2:
                    $price = floor(doubleval($price / 10)) * 10;
                    break;
                case 3:
                    $price = floor(doubleval($price / 100)) * 100;
                    break;
            }
            $s = StoreRoom::find()->where('name=\'' . $name . '\'')->one();
            $i = FixCarCategory::find()->where('name=\'' . $name . '\'')->one();
            $m = MiddleScaleHour::find()->where('scale_id=' . $i->id . ' AND min_price=' . $price)->one();

            //配件售价($selling_price) = 产品价格($s->price) * 比例($i->scale)
            $selling_price = $s ? ($s->price + ($s->price * ($i->scale / 100))) : 0;

            //工时($m->work_hour) + 配件售价($selling_price)
            $work_hour = $m ? ($m->work_hour + $selling_price) : $selling_price;

            $result['success'] = true;
            $result['msg'] = '操作成功!';
            $result['content'] = $work_hour;
        }

        return $result;
    }
    /**
     *------------------------------------------------------------
     *Ajax 删除图片
     * @param id fix_car_img 表id
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionRmImg()
    {
        $request = Yii::$app->request;
        $id = $request->post('id', 0);

        $result['success'] = false;
        $result['msg'] = '删除失败';
        if ($request->isAjax) {
            $model = FixCarImg::findOne($id);
            if (unlink($model->name)) {
                $model->delete();

                $result['success'] = true;
                $result['msg'] = '删除成功';
            }
        }
        return $result;
    }
    /**
     *------------------------------------------------------------
     *下载图片
     * @param int id fix_car_img 表外键
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionDownloadImg()
    {
        $request = Yii::$app->request;
        $id = $request->get('id');
        $model = FixCarImg::findOne($id);
        return Yii::$app->response->sendFile(realpath($model->name));
    }

    /**
     *------------------------------------------------------------
     * 调用WebUploader插件
     * @param int type 图片分类 ; int id fix_car_t 表主键
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionWebUploader(){
        $request = Yii::$app->request;
        $type = $request->post('type',0);
        $id = $request->post('id',0);
        $html = $this->renderPartial('web-uploader',['type'=>$type,'id'=>$id]);

        return Message::getMessage(true,'操作成功!',$html);
    }

    /**
     *------------------------------------------------------------
     * 查看图片
     * @param int type 图片分类 ; id fix_car_t 表主键
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionLookImage(){
        $request = Yii::$app->request;
        $type = $request->post('type',0);
        $id = $request->post('id',0);

        $images = FixCarImg::find()->where('fix_id='.$id.' AND type<='.$type)->asArray()->all();
        $images = ArrayHelper::index($images,null,'type');
        $html = $this->render('look-image',['images'=>$images]);
        return Message::getMessage(true,'操作成功!',$html);
    }

    /**
     *------------------------------------------------------------
     *  清单列表
     * @param int id fix_car_t 表主键 ;
     * @param int gid  fix_car_group 表主键
     *          7 钣金项目 ; 8 喷漆项目 ; 10 维修项目 ; 11 保养项目 ; 12 美容项目
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionRefreshItemList(){
        $request = Yii::$app->request;
        $id = $request->post('id',0);
        $gid = $request->post('gid',0);
        $is_report = $request->post('report');
        if($id < 1 || $gid < 1) return Message::getMessage();

        $items = ($res = FixCarItemT::find()->where('fix_id='.$id . ' AND fix_group !='.$gid)->all()) ? $res : [];

        //查勘定损、前台派工
        if('is_report' === $is_report){
            $render['reports'] = FixCarReport::find()->where('fix_id='.$id)->all();
        }
        $render['items'] = $items = ArrayHelper::index(ArrayHelper::toArray($items),null,'type');
        $html = $this->render('fix-item-list',$render);
        return Message::getMessage(true,'操作成功!',$html);
    }
    /************************************************* end ************************************************************/
}