<?php
/**
 * Created by PhpStorm.
 * User: 中闽 < 1464674022@qq.com >
 * Date: 2019/12/5
 * Time: 17:44
 */

namespace app\common\model;


class Catalog extends Tree
{
    protected $autoWriteTimestamp = false;

    const TYPE_CATALOG = 0;
    const TYPE_ARTICLE_LIST = 1;
    const TYPE_DIRECTORY = 2;

    const TYPES = [
        self::TYPE_DIRECTORY => '目录',
        self::TYPE_CATALOG => '栏目',
        self::TYPE_ARTICLE_LIST => '文章列表',
    ];

    //type_text 栏目类型
    public function getTypeTextAttr($value, $data)
    {
        return self::TYPES[$data['type']]??$data['type'];
    }

    //article_count 文章数量
    public function getArticleCountAttr($value, $data)
    {
        return $this->hasMany('Article')->where('status', Article::STATUS_OPEN)->count();
    }

    //article_cate_count 分类数量
    public function getArticleCateCountAttr($value, $data)
    {
        return $this->belongsToMany('ArticleCate', 'app\common\model\CateCatalog')->where('status', ArticleCate::STATUS_OPEN)->count();
    }

    /**
     * 栏目下拉数据
     */
    public function treelistForCatalog()
    {
        $catalogs = $this->where('type', self::TYPE_DIRECTORY)->order('sort asc,id')->select();
        return $this->treelist($catalogs);
    }

    /**
     * 文章下拉框数据
     */
    public function treelistForArticle()
    {
        $catalogs = $this->where(['type' => ['in', [self::TYPE_ARTICLE_LIST, self::TYPE_DIRECTORY]], 'status' => self::STATUS_OPEN])->order("tree_path")->select();

        $whileflag = true;
        while ($whileflag) {
            $count = 0;
            foreach ($catalogs as $key => $catalog) {
                if ($catalog->getData('type') == self::TYPE_DIRECTORY) {
                    $flag = false;
                    foreach ($catalogs as $key2 => $catalog2) {
                        if ($catalog2->pid == $catalog->id) {
                            $flag = true;
                            break;
                        }
                    }
                    if (!$flag) {
                        $count++;
                        unset($catalogs[$key]);
                    }
                } else if ($catalog->articleCateCount) {
                    $count++;
                    unset($catalogs[$key]);
                }
            }
            if ($count == 0) {
                $whileflag = false;
            }
        }

        return $this->treelist2($catalogs);
    }

    /**
     * 栏目HTML生成路径
     * @return string
     */
    public function getRealPath()
    {
        return Templet::getRootDir() . deleteStartDS(replaceDS($this->tpath()));
    }

    /**
     * 发布路径
     * 如果存在上级目录，则拼接上级目录
     */
    public function tpath()
    {
        $tpath = "";
        if ($this->pid) {
            $pnode = $this->getDirectParentNode();
            if ($pnode && $pnode->tpath()) {
                $tpath = $pnode->tpath();
            }
        }
        $enname = $this->path;
        if ($tpath && $enname) {
            return $tpath . appendStartDS($enname, '/');
        } else {
            return $enname ?: $tpath;
        }
    }

    /**
     * 获取栏目uri
     * @return mixed
     */
    public function getUri()
    {
        return replaceUrlDS($this->getData('path'));
    }


    /**
     * 获取栏目模板
     * @return Templet|null
     */
    public function getCatalogTemplet()
    {
        return (new Templet)->setName($this->catalog_templet);
    }

    /**
     * 获取文章模板
     * @return Templet|null
     */
    public function getArticleTemplet()
    {
        return (new Templet)->setName($this->article_templet);
    }

    //关联分类
    public function articleCates()
    {
        return $this->belongsToMany('ArticleCate', 'app\common\model\CateCatalog')->where('status', ArticleCate::STATUS_OPEN)->order('sort desc');
    }

    //分类个数
    public function articleCateCount()
    {
        return $this->belongsToMany('ArticleCate', 'app\common\model\CateCatalog')->where('status', ArticleCate::STATUS_OPEN)->count();
    }

    /**
     * 获取一个分类
     * @return mixed
     * @throws \Exception
     */
    public function getFirstArticleCate()
    {
        $cates = $this->articleCates;
        if (empty($cates)) {
            throw new \Exception("栏目{$this->id}找不到对应的分类");
        }
        return current($cates);
    }

}