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

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\FixCarCategory;
use common\models\MiddleScaleHour;
use common\models\WorkHour;
use Yii;
use yii\data\Pagination;
use yii\db\Exception;
use yii\helpers\ArrayHelper;
use yii\web\Response;

class ScaleController extends BaseController
{
    /**
     *------------------------------------------------------------
     *  列表页
     * @param int page 分页
     * @param int pid item_scale 表 pid
     * @param string name item_scale 表 name
     * @return view
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionIndex()
    {
        $session = Yii::$app->session;
        $request = Yii::$app->request;

        $page = $request->get('page', 1);
        $pid = $request->get('pid');
        $name = $request->get('name', '');


        $parents = FixCarCategory::find()->where('pid=0')->all();

        $pid_arr = [];
        foreach ($parents as $parent) {
            array_push($pid_arr, $parent->id);
        }
        $parent_key_value = ArrayHelper::index(ArrayHelper::toArray($parents), 'id');

        $pids = '';
        if (count($pid_arr) > 0) $pids = implode(',', $pid_arr);

        $query = FixCarCategory::find();
        $query = $query->where('pid IN(' . $pids . ')');

        if ($pid > 0) $query = $query->andWhere('pid=' . $pid);

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

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

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

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

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

        foreach ($sons as &$son) {
            $son->name = '/' . $parent_key_value[$son->pid]['name'] . '/' . $son->name;
        }

        return $this->render('index', [
            'sons' => $sons,
            'page_info' => $page_info,
            'page' => $page,
            'parents' => $parents,
            'pid' => $pid,
            'name' => $name
        ]);
    }

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

        if ($request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;
            $id = $request->post('id', 0);

            $result = [];
            $result['success'] = false;
            $result['msg'] = '添加失败!';

            $model = $id > 0 ? FixCarCategory::findOne($id) : new FixCarCategory;

            $tran = Yii::$app->getDb()->beginTransaction();

            try {
                $model->scenario = 'insert';
                $model->attributes = $request->post();

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

                if (!$model->save()) throw new Exception('item_scale表保存失败!');

                //添加或则更新
                MiddleScaleHour::deleteAll('scale_id=' . $id);

                $all_price = [3,4,5,6,7,8,9,10,15,20,30,40,50,60,70,80,90,100,200,300];
                foreach ($all_price as $price) {
                    $insert[] = ['scale_id' => $id, 'min_price' => $price, 'work_hour' => intval($request->post('str_' . $price))];
                }

                if (isset($insert)) {
                    if (!Yii::$app->db->createCommand()->batchInsert(MiddleScaleHour::tableName(), ['scale_id', 'min_price', 'work_hour'], $insert)->execute()) throw new Exception('中间表更新失败!');
                }

                $result['success'] = true;
                $result['msg'] = '添加成功!';

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

        $id = $request->get('id');

        $item_scale = $hours = $parents = $middles = null;
        if ($id > 0) { //编辑
            $item_scale = FixCarCategory::findOne($id);
            $hours = WorkHour::find()->where('id>0')->all();
            $middles = MiddleScaleHour::find()->where('scale_id=' . $id)->all();
            $middles = ArrayHelper::index(ArrayHelper::toArray($middles), 'min_price');
        }

        //
        $it = new FixCarCategory();
        $parents = $it->getCategory(0);

        return $this->render('info', [
            'parents' => $parents,
            'item_scale' => $item_scale,
            'hours' => $hours,
            'middle' => $middles
        ]);
    }

    /**
     *------------------------------------------------------------
     *  获取二级分类
     * @param int pid item_scale 表 pid
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionGetMachine(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;

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

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

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

        $it = new FixCarCategory;
        $sons = $it->getCategory($pid);

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

        return $result;
    }

    /**
     *------------------------------------------------------------
     *
     * @param
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionGetSelfFree(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;

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

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

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

        $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 = FixCarCategory::find()->where( 'name=\''.$name.'\'')->one();
            $m = MiddleScaleHour::find()->where('scale_id='.$i->id.' AND min_price='.$car_price)->one();
        }

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

        return $result;
    }
}