<?php


namespace frontend\modules\api\controllers;


use common\components\AjaxException;
use common\models\Dictionary;
use common\services\DictionaryRelationshipService;
use common\services\DictionaryService;
use frontend\modules\api\components\BaseAdminController;
use Throwable;
use Yii;
use yii\base\InvalidConfigException;
use yii\db\Exception;
use yii\web\Response;

class DictionaryController extends BaseAdminController
{
    /**
     * 字典对象数据
     * @param $is_all
     * @return Response
     */
    public function actionList($is_all = 0)
    {
        //返回
        if ($is_all == 1) {
            $data['data'] = DictionaryService::getDictionaryObjAllData();
        } else {
            $data['data'] = DictionaryService::getDictionaryObjShowData();
        }
        return $this->asJson($data);
    }

    /**
     * 字典分类列表
     * @return Response
     */
    public function actionListCategory($category)
    {
        $post = Yii::$app->request->post();
        $query = Dictionary::find()
            ->where(['classname' => $category]);
        //排序
        $this->initSequence($query);
        //主要筛选条件
        $query = $this->addConditionToQuery("optionname", $query, true);

        $data['data'] = $query->asArray()->all();
        return $this->asJson($data);
    }

    /**
     * 字典分类列表
     * @return Response
     */
    public function actionListCategoryName()
    {
        $info = Dictionary::find()
            ->select("id,classname")
            ->orderBy("id asc")
            ->asArray()
            ->all();
        //组合
        $arr = [];
        foreach ($info as $key => $value) {
            if (!in_array($value['classname'], $arr)) {
                $arr[] = $value['classname'];
            }
        }
        //返回
        $data['data'] = $arr;
        return $this->asJson($data);
    }

    /**
     * 字典列表
     * @return Response
     */
    public function actionListAll()
    {
        $info = Dictionary::find()
            ->where(['status' => 1])
            ->orderBy("id asc")
            ->asArray()
            ->all();
        //返回
        $data['data'] = $info;
        return $this->asJson($data);
    }

    /**
     * 字典列表
     * @return Response
     */
    public function actionAll()
    {
        $query = Dictionary::find();
        $data['data'] = $query->asArray()->all();
        return $this->asJson($data);
    }

    /**
     * 字典添加
     * @return Response
     * @throws Exception
     * @throws Throwable
     */
    public function actionAdd()
    {
        $post = Yii::$app->request->post();
        if (!isset($post["name"]) || strlen(trim($post["name"])) == 0) {
            return $this->asJson([], 1, "名称不可以为空！");
        }
        $parent = null;
        //判断父分类是否存在
        if ($post["pid"] != 0) {
            $parent = Dictionary::findOne($post["pid"]);
            if (!$parent) {
                throw new AjaxException("分类不存在！");
            }
        }
        $dictionary = Dictionary::find()->where(["name" => $post["name"], "pid" => $post["pid"]])->one();
        if ($dictionary) {
            return $this->asJson([], 1, "名称 {$post["name"]} 已存在！");
        }
        $param = [
            "has_children" => $post["has_children"],
            "name" => $post["name"],
            "pid" => $post["pid"],
            "status" => $post["status"],
            "multiple" => $post["multiple"],
            "sort" => $post["sort"] ?: 0,
        ];
        $model = new Dictionary($param);
        $model->param_name = "";
        Yii::$app->db->transaction(function () use ($model, $parent, $post) {
            if (!$model->save()) {
                throw new Exception($model->getErrorSummary(true)[0]);
            }
            //给父分类的has_child如果为0，那么改为1
            if ($post["pid"] != 0) {
                if ($parent->has_children == 0) {
                    $parent->has_children = 1;
                    $parent->save();
                }
            }
            //添加派生关系
            if ($post["derive"] != []) {
                DictionaryRelationshipService::addByDerive($post["derive"], $model->id);
            }
        });
        return $this->asJson();
    }

    /**
     * 字典修改
     * @param $id
     * @return Response
     * @throws AjaxException
     * @throws InvalidConfigException
     * @throws Throwable
     */
    public function actionUpdate($id)
    {
        $post = Yii::$app->request->post();
        //校验
        /** @var  Dictionary $dictionary */
        $model = Dictionary::findOne(['id' => $post["id"]]);
        if (!$model) {
            return $this->asJson([], 1, "记录不存在！"); //通知前端
        }
        $parent = null;
        //判断父分类是否存在
        if ($post["pid"] != 0) {
            $parent = Dictionary::findOne($post["pid"]);
            if (!$parent) {
                throw new AjaxException("分类不存在！");
            }
        }
        //校验是否重名
        $otherInfo = Dictionary::find()
            ->where(['<>', 'id', $id])
            ->andWhere(["name" => $post["name"], "pid" => $post["pid"]])
            ->one();
        if ($otherInfo) {
            return $this->asJson([], 1, "名称 {$post["name"]} 已存在！"); //通知前端
        }
        $this->setAttributeFromGetAndPost($model);
        Yii::$app->db->transaction(function () use ($model, $parent, $post) {
            if (!$model->save()) {
                throw new Exception($model->getErrorSummary(true)[0]);
            }
            //给父分类的has_child如果为0，那么改为1
            if ($post["pid"] != 0) {
                if ($parent->has_children == 0) {
                    $parent->has_children = 1;
                    $parent->save();
                }
            }
            //修改派生关系
            if ($post["derive"] != []) {
                DictionaryRelationshipService::updateByDerive($post["derive"], $model->id);
            }
        });
        return $this->asJson();
    }
}