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

namespace frontend\controllers;


use common\libs\MyLib;
use common\models\DisplacementT;
use common\models\FixCarPart;
use common\models\Message;
use common\models\SDYMiddle;
use common\models\SeriesT;
use Yii;
use common\models\BrandT;
use common\models\YearT;
use yii\base\Controller;
use yii\data\Pagination;
use yii\db\Exception;
use yii\helpers\ArrayHelper;
use yii\web\Response;

class CarModelController extends Controller
{
    /**
     *------------------------------------------------------------
     *  列表
     * @param void
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionIndex()
    {
        $request = Yii::$app->request;
        $session = Yii::$app->session;
        $page = $request->get('page');

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

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

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

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

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

        $this->getCarModel($render);


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

    /**
     *------------------------------------------------------------
     *  详情、编辑、保存
     * @param int id
     * @return mixed
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionInfo()
    {
        $request = Yii::$app->request;

        //编辑、保存
        if ($request->isPost) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            $id = $request->post('id');

            try{
                $SDY = $id > 0 ? FixCarPart::findOne($id) : new FixCarPart();

                $SDY->attributes = $request->post();

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

                if(!$SDY->save()) throw new Exception('操作失败!');

                return Message::getMessage(true,'操作成功!');
            }catch(Exception $e){
                return Message::getMessage();
            }

        }

        $render = [];
        $this->getCarModel($render);

        //详情
        $id = $request->get('id',0);
        if($id > 0 ){
            $render['info'] = ($SDY = SDYMiddle::findOne($id)) ? $SDY : [];
            $render['series'] = ($series = SeriesT::findAll($SDY->series_id)) ? $series : [];
            $render['displacements'] = ($displacement = DisplacementT::findAll($SDY->displacement_id)) ? $displacement : [];
        }
        return $this->render('info', $render);
    }

    private function getCarModel(&$render)
    {
        //品牌
        $render['brands'] = ($brands = BrandT::find()->all()) ? $brands : [];

        //年份
        $render['years'] = ($years = YearT::find()->all()) ? $years : [];
    }
    public function actionRemove(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $id = $request->post('id');

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

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

        SDYMiddle::findOne($id)->delete();

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

        return $result;
    }
    /**
     *------------------------------------------------------------
     *  查询条件
     * @param object $request ; 引用 $query,$render
     * @return void
     * @author liuyingjie
     *------------------------------------------------------------
     */
    private function getQuery($request, &$query, &$render)
    {
        $op = $request->get('op');
        $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);


        if ('0' === $op) $query = $query->andWhere('id=-1');
        if ($brand_id > 0) {
            $query = $query->joinWith('seriesT')->andWhere(['series_t.brand_id'=>$brand_id]);
        }
        $render['series'] = $render['displacements'] = [];
        if ($series_id > 0) {
            $query = $query->andWhere(['s_d_y_middle.series_id'=>$series_id]);
            $render['series'] = SeriesT::findAll(['brand_id'=>$brand_id]);
        }
        if ($displacement_id > 0){
            $query = $query->andWhere(['s_d_y_middle.displacement_id'=>$displacement_id]);
            $render['displacements'] = DisplacementT::findAll(['series_id'=>$series_id]);
        }
        if ($year_id > 0) $query = $query->andWhere(['s_d_y_middle.year_id'=>$year_id]);


        $render['brand_id'] = $brand_id;
        $render['series_id'] = $series_id;
        $render['displacement_id'] = $displacement_id;
        $render['year_id'] = $year_id;
    }
}