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

namespace frontend\controllers;

use common\models\FixCarGroup;
use Yii;
use yii\db\Exception;
use yii\helpers\ArrayHelper;
use yii\web\Response;

class FixCarGroupController extends BaseController
{
    public function actionIndex()
    {
        $requst = Yii::$app->request;
        $session = Yii::$app->session;

        $pid = $requst->get('pid', 0);

        //父级
        $render['parents'] = $parents = FixCarGroup::findAll(['pid' => 0]);
        $parent_key_value = ArrayHelper::index(ArrayHelper::toArray($parents), 'id');

        $lists = FixCarGroup::find()->all();

        foreach ($lists as $list) {
            if (0 == $list->pid) continue;
            $list->name = $parent_key_value[$list->pid]['name'] . '/' . $list->name;
        }

        $render['lists'] = $lists;

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

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

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

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

            $id = $request->post('id', 0);
            $name = $request->post('name');
            $pid = $request->post('pid');
            $fix_car_group = $id > 0 ? FixCarGroup::findOne($id) : new FixCarGroup();

            $fix_car_group->pid = $pid;
            $fix_car_group->name = $name;

            try {
                $fix_car_group->save();

                $result['success'] = true;
                $result['msg'] = '操作成功!';
                return $result;
            } catch (Exception $e) {
                $result['msg'] = '分组名不可重复!';
                return $result;
            }
        }

        $render['parents'] = $parents = FixCarGroup::findAll(['pid' => 0]);

        $id = $request->get('id');
        if($id > 0 ){
            $render['info'] = FixCarGroup::findOne($id);
        }

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