<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/13/013
 * Time: 14:30
 */

namespace frontend\controllers;

use frontend\models\Article;
use frontend\models\ArticleCategory;

class ArticleCategoryController extends BaseController
{
    // public $exceptIds = [2,4,6,7,8,9,10,11,13,14,15,16,20,22,23];
    /**
     * 获取所有文章分类
     */
    public function actionGetArticleCategoryTreeList()
    {
        $allCategory = ArticleCategory::find()->asArray()->all();
        $result = $this->recursiveArticleCategoryTreeList($allCategory, null);
        return $this->outJson(1, $result);
    }

    /**
     * 递归父类排序分类树(获取层级)
     * @param $allArticleCategoryList
     * @param $parent_id
     * @param int $temp
     * @return array
     */
    private function recursiveArticleCategoryTreeList($allArticleCategoryList, $parent_id, &$temp = [])
    {
        foreach ($allArticleCategoryList as $articleCategory) {
            if ($articleCategory['parent_id'] == $parent_id) {
                $temp[] = $articleCategory;
                $this->recursiveArticleCategoryTreeList($allArticleCategoryList, $articleCategory['id'], $temp);
            }
        }
        return $temp;
    }

    /**
     * 获取文章分类列表
     */
    public function actionGetArticleCategoryList()
    {
        $categoryModel = ArticleCategory::find();
        $query = clone $categoryModel;
        $allCategory = $query->asArray()->all();
        $allCategory = $this->recursiveArticleCategoryTreeList($allCategory, null);
        if ($allCategory) {
            $article = Article::find();
            foreach ($allCategory as $key => $category) {
                $articleQuery = $article->where(['article_category_id' => $category['id']]);
                $count = $articleQuery->count();
                $allCategory[$key]['article_count'] = (int)$count;
                $parent = $categoryModel->where(['id' => $category['parent_id']])->asArray()->one();
                $allCategory[$key]['parent'] = !empty($parent) ? $parent : [];
            }
            return $this->outJson(1, $allCategory);
        } else {
            return $this->outJson(0, [], '不存在分类');
        }
    }

    /**
     * 新增文章分类
     */
    public function actionArticleCategorySave()
    {
        $request = \Yii::$app->getRequest()->post();
        if (!empty($request['id'])) {
            $model = ArticleCategory::findOne(['id' => $request['id']]);
            $request['modify_date'] = date('Y-m-d H:i:s', time());
            $request['create_date'] = $model->create_date;
            $request['parent_id'] = $model->parent_id;
            if (!$this->isUniqueBySign($model->sign, $request['sign'])) {
                return $this->outJson(0, [], '标识已存在!');
            }
        } else {
            $model = new ArticleCategory();
            $request['create_date'] = date('Y-m-d H:i:s', time());
            $request['modify_date'] = date('Y-m-d H:i:s', time());

            if ($this->isExistBySign($request['sign'])) {
                return $this->outJson(0, [], '标识已存在!');
            }
        }

        $request['grade'] = isset($request['grade']) ? (int)$request['grade'] : '';
        $request['language'] = isset($request['language']) ? (int)$request['language'] : '';
        $request['order_list'] = isset($request['order_list']) ? (int)$request['order_list'] : '';
        $model->setAttributes($request);

        if ($model->save()) {
            if ($request['parent_id']) {
                $model->path = $request['parent_id'].','.$model->id;
            } else {
                $model->path = (string)$model->id;
            }
            $model->save();
            return $this->outJson(1, $model->id);
        } else {
            return $this->outJson(0, [], '新增分类失败');
        }
    }

    /**
     * 检测sign是否唯一
     */
    public function actionCheckSign()
    {
        $response = [];
        $request = \Yii::$app->getRequest()->get();
        $data['oldValue'] = isset($request['oldValue']) ? $request['oldValue'] : '';
        $data['sign'] = isset($request['sign']) ? $request['sign'] : '';

        $isExist = $this->isUniqueBySign($data['oldValue'], $data['sign']);
        if ($isExist) {
            $response['isSuccess'] = true;
        } else {
            $response['isSuccess'] = false;
        }
        return $this->outJson(1, $response);
    }

    private function isUniqueBySign($oldValue, $newSign)
    {
        if (strtolower($oldValue) == strtolower($newSign)) {
            return true;
        } else {
            if ($this->isExistBySign($newSign)) {
                return false;
            } else {
                return true;
            }
        }
    }

    private function isExistBySign($sign)
    {
        $sign = strtolower($sign);
        $exist = ArticleCategory::find()->where(['lower(sign)' => $sign])->one();
        if ($exist != null) {
            return true;
        }
        return false;
    }

    /**
     * 获取文章分类详情
     */
    public function actionArticleCategoryDetail()
    {
        $request = \Yii::$app->getRequest()->get();
        $request['id'] = isset($request['id']) ? (int)$request['id'] : '';
        $category = ArticleCategory::find();
        $rs = $category->where(['id' => $request['id']])->asArray()->one();
        if ($rs) {
            if ($rs['parent_id']) {
                $parent = $category->where(['id' => $rs['parent_id']])->asArray()->one();
                $rs['parent'] = $parent;
            }
        }
        return $this->outJson(1, $rs);
    }

    /**
     * 删除文章分类
     */
    public function actionArticleCategoryDelete()
    {
        $id = \Yii::$app->getRequest()->get('id');
        $model = ArticleCategory::findOne(['id' => $id]);
        $children = intval(ArticleCategory::find()->where(['id' => $id])->orWhere(['parent_id' => $id])->count());
        if ($children >= 2) {
            return $this->outJson(0, [], "文章分类\"".$model->name."\"存在下级分类,删除失败!");
        }
        $article = Article::find();
        $articleQuery = $article->where(['article_category_id' => $model->id]);
        $count = intval($articleQuery->count());
        if ($count > 0) {
            return $this->outJson(0, [], "文章分类\"".$model->name."\"下存在文章,删除失败!");
        }

        $rs = ArticleCategory::deleteAll(['id' => $id]);
        return $this->outJson(1, $rs);
    }
}
