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

namespace frontend\controllers;

use common\libs\MyLib;
use common\models\FixCarCategory;
use common\models\FixCarGroup;
use common\models\Message;
use common\models\MiddleGroupCategory;
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 FixCarCategoryController 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('fix-car-category-index');
        $session->set('fix-car-category-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,
            'groups' => FixCarGroup::find()->all()
        ]);
    }

    /**
     *------------------------------------------------------------
     *  详情页(编辑、新增)
     * @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表保存失败!');

                $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);
        }

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

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

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

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

        $model = new FixCarCategory;
        $sub_categories = $model->getCategory('pid='.$pid);

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

    /**
     *------------------------------------------------------------
     * 分组
     * @param int gid fix_car_group表主键;分为钣金、喷漆、机电、美容
     * @param arrray category_ids fix_car_category表主键集合
     * @return json
     * @author liuyingjie
     *------------------------------------------------------------
     */
    public function actionGrouping(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $request = Yii::$app->request;
        $gid = $request->post('gid',0);
        $category_ids = $request->post('category_id',[]);
        if($gid < 1 || empty($category_ids)) return Message::getMessage();

//        MiddleGroupCategory::deleteAll(['fix_group_id'=>$gid]);
        $insert = [];
        foreach($category_ids as $key=>$category_id){
            if(MiddleGroupCategory::findOne(intval($gid.$category_id))) continue;
            array_push($insert,['id'=>intval($gid.$category_id),'fix_group_id'=>$gid,'fix_car_category_id'=>$category_id]);
        }

        if(!empty($insert)) Yii::$app->db->createCommand()->batchInsert(MiddleGroupCategory::tableName(),['id','fix_group_id','fix_car_category_id'],$insert)->execute();
        return Message::getMessage(true,'操作成功!');
    }
}