<?php
/**
 * Created by PhpStorm.
 * User: liuyingjie
 * Date: 2017/8/8
 * Time: 17:14
 */

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\BrandT;
use common\models\CarLogT;
use common\models\DisplacementT;
use common\models\FixCarGroup;
use common\models\FixCarItemT;
use common\models\FixCarMateials;
use common\models\FixCarPart;
use common\models\FixCarProject;
use common\models\FixCarReport;
use common\models\FixCarScale;
use common\models\FixCarT;
use common\models\FixCarTrimsRoom;
use common\models\FixCategoryA;
use common\models\FixItemRecord;
use common\models\FixCarCategory;
use common\models\FixPurchaseItem;
use common\models\Message;
use common\models\SDYMiddle;
use common\models\SeriesT;
use common\models\StoreList;
use common\models\StoreLog;
use common\models\StoreRoom;
use common\models\YearT;
use Yii;
use common\models\UserT;
use yii\base\InvalidParamException;
use yii\data\Pagination;
use yii\db\Exception;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\web\Response;

class StoreRoomController extends FixCarBaseController
{
    public $my = null;

    public function behaviors()
    {
        return [
            [
                'class' => 'yii\filters\ContentNegotiator',
                'only' => ['ajax-get-item','ajax-store-search','operation-out-store'],
                'formats' => [
                    'application/json' => Response::FORMAT_JSON,
                ]
            ],
            'verbs' => [
                'class' => \yii\filters\VerbFilter::className(),
                'actions' => [
                    'ajax-get-item'  => ['post'],
                ],
            ],
        ];
    }

    /**
     *------------------------------------------------------------
     *  入库列表
     * @param
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionPutInStore()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;
        $name = $request->get('name', '');
        $page = $request->get('page', 1);
        $category_1 = $request->get('category_1', 0);
        $brand_id = $request->get('brand_id', 0);
        $series_id = $request->get('series_id', 0);
        $displacement_id = $request->get('displacement_id', 0);
        $year_id = $request->get('year_id', 0);


        $query =  StoreRoom::find();
        if('1' === $category_1){
            $query = $query->joinWith('parts','right');
        }elseif('2' === $category_1){
            $query = $query->joinWith('category','right')->where('fix_car_category.pid=213');
        }elseif('3' === $category_1){
            $query = $query->joinWith('category','right')->where('fix_car_category.pid=131');
        }
        $series = $displacements = null;
        if($series_id > 0) {
            $query->andWhere('fix_car_part.series_id='.$series_id);
            $series = $this->getSeries($brand_id);
        }
        if($displacement_id > 0) {
            $query->andWhere('fix_car_part.displacement_id='.$displacement_id);
            $displacements = $this->getDisplacement($series_id);
        }
        if($year_id > 0) $query->andWhere('fix_car_part.year_id='.$year_id);

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

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

        $query = $query->offset($pagination->offset)->limit($pagination->limit);
        $stores = $query->all();
        $store_logs = StoreLog::find()->where('type=1')->orderBy('created_at DESC')->all();


        $page_info = MyLib::getPageInfo($pagination);
        return $this->render('put-in-store',
            [
                'stores' => $stores,
                'name' => $name,
                'page_info' => $page_info,
                'page' => $page,
                'store_logs'=>$store_logs,
                'brands' => $this->getBrands(),
                'years'=>$this->getYears(),
                'category_1'=>$category_1,
                'series_id'=>$series_id,
                'displacement_id'=>$displacement_id,
                'year_id'=>$year_id,
                'brand_id'=>$brand_id,
                'series'=>$series,
                'displacements'=>$displacements
            ]);
    }

    /**
     *------------------------------------------------------------
     *  配件入库详情、添加、编辑
     * @param int category_1 关联item_scale 顶级分类
     * @param int scale_id 关联 item_scale 子分类
     * @return mixed
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionPutInStoreInfo()
    {
        $request = Yii::$app->request;

        //提交、保存操作
        if ($request->isAjax) {
            $tran = StoreRoom::getDb()->beginTransaction();
            try{
                Yii::$app->response->format = Response::FORMAT_JSON;
                $id = $request->post('id', 0);
                $displacement_id = $request->post('displacement_id');
                $series_id = $request->post('series_id');
                $year_id = $request->post('year_id');
                $category_id = $request->post('category_id');
                $parent_id = $request->post('parent_id');
                $price = $request->post('price');

                //判断该分类是否存在
                if (!($category = FixCarCategory::findOne($category_id))) return Message::getMessage(false,'该配件不存在!');
                if(!in_array($parent_id,[131,213])){
                    //判断该系列车是否存在
                    if (!($part = FixCarPart::findOne(['series_id' => $series_id, 'displacement_id' => $displacement_id, 'year_id' => $year_id]))) return Message::getMessage(false,'该系列车不存在,请先到基础管理->车辆品牌型号管理添加!');

                }

                $store_room = $id > 0 ? StoreRoom::findOne($id) : new StoreRoom();
                $store_room->scenario = 'default';
                $store_room->attributes = $request->post();
                $store_room->selling_price = intval($price) * $category->scale/100;
                $store_room->good_sn = $this->getCreateOrderSn();
                //非材料、辅料为 null
                if(!in_array($parent_id,[131,213])) $store_room->category_2 = null;
                if (!$store_room->validate()) {
                    $errors = array_values($store_room->errors);
                    return Message::getMessage(false,$errors[0]);
                }
                if(!$store_room->save()) throw new Exception('入库失败!');
                //非材料、辅料
                if(!in_array($parent_id,[131,213])){
                    $id < 1 ? $part->link('storeRooms',$store_room) : '';
                    //判断该分类是否存在
                    if (!($category = FixCarCategory::findOne($category_id))) return Message::getMessage(false,'该配件不存在!');
                }else{
                    //如果是新增，则添加相应数据到关联表
                    if($id < 1 ){
                        if(213 == $parent_id){
                            $materials = new FixCarMateials();
                            $materials->link('storeRoom',$store_room);
                            $materials->save();
                        }elseif(131 == $parent_id){
                            $trims_room = new FixCarTrimsRoom();
                            $trims_room->link('storeRoom',$store_room);
                            $trims_room->save();
                        }
                    }
                }

                //入库记录
                $store_log = new StoreLog();
                $store_log->op_man = $this->my->name;
                $store_log->op_time = date('Y-m-d H:i:s');
                $store_log->brand_id = isset($part) ? $part->series->brand_id : '';
                $store_log->series_id = $series_id ? $series_id : '';
                $store_log->displacement_id = $displacement_id ? $displacement_id : '';
                $store_log->year_id = $year_id ? $year_id : '';
                $store_log->number = $store_room->number;
                $store_log->name = $store_room->category->name;
                $store_log->type = 1;
                if(!$store_log->save()) throw new Exception('记录入库日志失败!');

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

        $id = $request->get('id', 0);
        $renders = [];
        $renders['brands'] = $this->getBrands();     //品牌
        $renders['parents'] = $parents = $this->getParents();
        $renders['years'] = $this->getYears();
        $renders['categorys'] = FixCategoryA::find()->all();

        //编辑
        if ($id > 0) {
            $renders['info'] = $info = StoreRoom::findOne($id);
            if(!in_array($info->category->pid,[131,213])){
                $series = SeriesT::findOne($info->parts['series_id']);
                $renders['b'] = $series->brand_id;
                $renders['series'] = SeriesT::findAll(['brand_id' => $series->brand_id]);  //车型
                $renders['displacements'] = $dis = DisplacementT::findAll(['brand_id' => $series->brand_id, 'series_id' => $info->parts['series_id']]);
            }
        }
        //品牌
        return $this->render('put-in-store-info', $renders);
    }

    /**
     *------------------------------------------------------------
     * 辅料添加页
     * @param void
     * @return void
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionIngredientsView(){
        return $this->render('ingredients-view');
    }

    /**
     *------------------------------------------------------------
     * 辅料添加操作
     * @param void
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionIngredientsCreate(){
    }
    /**
     *------------------------------------------------------------
     *  出库
     * @param
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionPutOutStore()
    {
        $items = FixItemRecord::find()->where('status>0 AND is_del=0')->all();
        $store_logs = StoreLog::find()->where('type=2')->orderBy('created_at DESC')->all();

        return $this->render('put-out-store', [
            'fix_items' => $items,
            'store_logs' => $store_logs
        ]);
    }

    /**
     *------------------------------------------------------------
     *  盘点
     * @param
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionCheckStore()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;
        $name = $request->get('name', '');
        $page = $request->get('page', 1);

        $query = StoreRoom::find();

        if ('' !== $name) {
            $query->andWhere(['like', 'name', $name]);
        }

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

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

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

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

        return $this->render('check-store', [
            'stores' => $stores,
            'name' => $name,
            'page_info' => $page_info,
            'page' => $page
        ]);
    }

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

        $info = StoreRoom::findOne($id);

        $brands = BrandT::find()->all();     //品牌
        return $this->render('check-store-info', [
            'brands' => $brands,
            'info' => $info
        ]);
    }

    /**
     *------------------------------------------------------------
     *  采购清单
     * @param
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionStoreList()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;
        $name = $request->get('name', '');
        $page = $request->get('page', 1);

        $query = StoreRoom::find();

        if ('' !== $name) {
            $query->andWhere(['like', 'name', $name]);
        }

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

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

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

        $page_info = MyLib::getPageInfo($pagination);
        return $this->render('store-list',
            [
                'stores' => $stores,
                'name' => $name,
                'page_info' => $page_info,
                'page' => $page
            ]);
    }

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

        //提交、保存操作
        if ($request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            $id = $request->post('id', 0);

            $store_room = ($id > 0) ? StoreList::findOne($id) : new StoreList;
            $store_room->scenario = 'default';
            $store_room->attributes = $request->post();
            if (!$store_room->validate()) {
                $errors = array_values($store_room->errors);
                $result['msg'] = $errors[0];
                return $result;
            }
            $store_room->save();

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

        $id = $request->get('id', 0);
        $renders = [];
        $renders['brands'] = BrandT::find()->all();     //品牌
        $renders['parents'] = $parents = FixCarCategory::getCategory(0);
        $renders['data_list_default'] = count($parents) > 0 ? FixCarCategory::findOne('pid=' . $parents[0]->id) : [];

        //编辑
        if ($id > 0) {
            $renders['info'] = $info = StoreRoom::findOne($id);
            $renders['series'] = SeriesT::findAll(['brand_id' => $info->brand_id]);  //车型
            $renders['displacements'] = $dis = DisplacementT::findAll(['brand_id' => $info->brand_id, 'series_id' => $info->series_id]);
        }
        //品牌
        return $this->render('store-list-info', $renders);
    }

    /**
     *------------------------------------------------------------
     *  模糊查询
     * @param
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionAjaxStoreSearch()
    {
        $request = Yii::$app->request;
        if (!$request->isAjax) return Message::getMessage();

        $name = $request->post('search', '');
        $searches = StoreRoom::find()->where(['like', 'name', $name])->andWhere('number > 0')->all();

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

    /**
     *------------------------------------------------------------
     * 出库
     * @param car_log_t type = 3
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionOperationOutStore()
    {
        $request = Yii::$app->request;
        if (!$request->isAjax) return Message::getMessage();
        $item_id = $request->post('item_id', '');
        $get_man = $request->post('get_man', '');
        $number = $request->post('number', 0);
        $id = $request->post('id', 0);
        $record_id = $request->post('record_id', 0);

        $tran = StoreRoom::getDb()->beginTransaction();
        try {
            $store = StoreRoom::findOne($id);
            $store->scenario = 'put_out_store';
            $store->number -= $number;
            if ($store->number < 0) throw new Exception('库存不足');
            if (!$store->save()) throw new Exception('库存更改失败');

            //更新维修清单
            $fix_item = FixCarItemT::findOne($item_id);
            $fix_item->get_time = date('Y-m-d H:i:s');
            if (!$fix_item->save()) throw new Exception('维修条目更新失败!');

            //删除出库清单
            $record_model = FixItemRecord::findOne($record_id);
            $record_model->is_del = 1;
            if(!$record_model->save()) throw new Exception('出库清单删除失败!');

            //出库记录
            $store_log = new StoreLog();
            $store_log->op_man = $this->my->name;
            $store_log->op_time = date('Y-m-d H:i:s');
            $store_log->brand_id = $store->brand_id;
            $store_log->series_id = $store->series_id;
            $store_log->displacement_id = $store->displacement_id;
            $store_log->year_id = $store->year_id;
            $store_log->get_man = $get_man;
            $store_log->number = $number;
            $store_log->name = $store->category->name;
            $store_log->type = 2;
            if(!$store_log->save()) throw new Exception('记录出库日志失败!');

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

        return Message::getMessage();
    }

    /**
     *------------------------------------------------------------
     *  树形菜单文件夹打开
     * @param   int car_price 新车购置价
     * @param   int id  fix_car_t表 主键
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    function actionGetTree()
    {
        $request = Yii::$app->request;
        $render['url'] = $request->referrer;
        $render['car_price'] = $request->get('car_price', 0);
        $render['fix_id'] = $request->get('id', 0);

        return $this->render('get-tree', $render);
    }

    /**
     *------------------------------------------------------------
     *  左边菜单
     * @param
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    function actionLeft()
    {
        $request = Yii::$app->request;
        $t = $request->get('t');
        $fix_id = $request->get('fix_id',0);

        $items = [];
        switch ($t) {
            //更换清单
            case 1:
                //排除养护类pid=10、辅料类pid=131
                $items = FixCarCategory::find()->where('pid=0 AND id NOT IN (131,213)')->asArray()->all();
                $pids = '';
                foreach ($items as &$item) {
                    $item['url'] = '';
                    $pids .= $item['id'].',';
                }
                $pids = rtrim($pids,',');
                $subs = FixCarCategory::find()->where('pid IN('.$pids.')')->asArray()->all();
                foreach($subs as &$sub){
                    $sub['url'] = '/store-room/shop?id='.$sub['id'].'&fix_id='.$fix_id;
                }
                $items = array_merge($items,$subs);
                break;
            case 2:
                //维修清单
                $items = FixCarGroup::find()->asArray()->all();
                foreach ($items as &$item) {
                    $item['url'] = '';
                    //当有子类时，url为空
                    if (!FixCarGroup::findOne(['pid' => $item['id']])) {
                        $item['url'] = '/store-room/container?g_id=' . $item['id'].'&fix_id='.$fix_id;
                    }
                }
                break;
        }
        $items = Json::encode($items);
        return $this->render('left', ['items' => $items]);
    }

    /**
     *------------------------------------------------------------
     *  维修清单
     * @param int g_id 分组id
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    function actionContainer()
    {
        $request = Yii::$app->request;
        $session = Yii::$app->session;
        $g_id = $request->get('g_id');
        $price = $request->get('car_price');
        $op = $request->get('op',0);
        $fix_id = $request->get('fix_id',0);
        $page = $request->get('page',0);
        $name = $request->get('name','');
        $url = $request->url;

        if(1 == $op)  return $this->render('container', ['projects'=>[],'fix_id'=>0,'status'=>0,'page_info'=>'','url'=>'','name'=>'']);

        //处理后的新车购置价
        $price = $this->handleNewCarPrice($price);

        $query = FixCarProject::find()->joinWith('category');

        switch ($g_id) {
            case 7://钣金项目
                $query = $query->andWhere('fix_car_project.group_id=' . $g_id.' AND car_price=1');
                break;
            case 8: //喷漆
            case 10://机电项目->维修
            case 11://机电项目->保养
                $query = $query->andWhere('fix_car_project.group_id=' . $g_id . ' AND fix_car_project.car_price='.$price);
                break;
            case 12://美容项目
                $query = $query->andWhere('fix_car_project.group_id=' . $g_id . ' AND fix_car_project.car_price=0');
                break;
        }

        if('' != $name){
            $query = $query->andWhere(['like','fix_car_category.name',$name]);
        }

        $sql = $query->createCommand()->rawSql;
        $session->remove('store-room-container');
        $session->set('store-room-container',$sql);

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

        $query = $query->offset($pagination->offset)->limit($pagination->limit);
        $render['projects'] = $query->all();

        $render['page_info'] = MyLib::getPageInfo($pagination);

        //查勘定损、报案号
        $render['status'] = $status = FixCarT::findOne($fix_id)->status;

        if( 4 === $status){
            $render['reports'] = FixCarReport::findAll(['fix_id'=>$fix_id]);
        }

        $render['fix_id'] = $fix_id;
        $render['page'] = $page;
        $render['url'] = $url;
        $render['name'] = $name;

        return $this->render('container', $render);
    }

    /**
     *------------------------------------------------------------
     *  更换清单
     * @param
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionShop()
    {
        $request = Yii::$app->request;
        $session = Yii::$app->session;
        try{
            $id = $request->get('id',0);
            $op = $request->get('op',0);
            $name = $request->get('name','');
            $page = $request->get('page',0);
            $fix_id = $request->get('fix_id',0);
            $url = $request->url;

            if(1 == $op) return $this->render('shop-container', ['stores'=>[],'fix_id'=>0,'status'=>0,'name'=>'','page_info'=>'','url'=>'']);

            $info = FixCarT::find()->select('brand_id,series_id,displacement_id,car_year,new_price,status')->where('id='.$fix_id)->one();

            if(!$info->brand_id || !$info->series_id || !$info->displacement_id || !$info->car_year) throw new InvalidParamException('【品牌 或 车系 或 排量 或 年份不可为空！】');

            $year = YearT::findOne(['name'=>$info->car_year]);

            $query = StoreRoom::find()->where('category_id='.$id.' AND brand_id='.$info->brand_id.' AND series_id='.$info->series_id.' AND displacement_id='.$info->displacement_id.' AND year_id='.$year->id);
            if('' != $name) $query = $query->andWhere(['like','name',$name]);
            $sql = $query->createCommand()->rawSql;
            $total = $query->count();
            $session->remove('store-room-shop');
            $session->set('store-room-shop',$sql);

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

            $render['stores'] = $query->all();

            $render['page_info'] = MyLib::getPageInfo($pagination);

            //查勘定损、报案号
            $render['status'] = $info->status;
            if( 4 === $info->status){
                $render['reports'] = FixCarReport::findAll(['fix_id'=>$fix_id]);
            }
            $render['page'] = $page;
            $render['fix_id'] = $fix_id;
            $render['url'] = $url;
            $render['name'] = $name;

            return $this->render('shop-container', $render);

        }catch(InvalidParamException $e){
            return $e->getMessage();
        }

    }

    /**
     *------------------------------------------------------------
     *  辅料清单
     * @param   int category_1 125
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionTrimsRoom()
    {
        $request = Yii::$app->request;
        $session = Yii::$app->session;
        $fix_id = $request->get('fix_id');
        $page = $request->get('page',0);
        $name = $request->get('name','');
        $url = $request->url;

        $categories = FixCarScale::find()->where('pid=131')->select('category_id')->asArray()->all();
        $categories = implode(',', ArrayHelper::getColumn($categories, 'category_id'));

        $query = StoreRoom::find()->joinWith('category')->where('store_room.category_id IN(' . $categories . ')');
        if('' != $name){
            $query = $query->andWhere(['like','fix_car_category.name',$name]);
        }

        $sql = $query->createCommand()->rawSql;
        $session->remove('store-room-trims-room');
        $session->set('store-room-trims-room',$sql);

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

        $query = $query->offset($pagination->offset)->limit($pagination->limit);
        $render['stores'] = $query->all();
        $render['page_info'] = MyLib::getPageInfo($pagination);
        $render['fix_id'] = $fix_id;
        $render['url'] = $url;
        $render['name'] = $name;
        $render['page'] = $page;

        //查勘定损、报案号
        $render['status'] = $status = FixCarT::findOne($fix_id)->status;

        if( 4 == $status){
            $render['reports'] = FixCarReport::findAll(['fix_id'=>$fix_id]);
        }
        return $this->render('trims-room', $render);
    }
}