<?php

namespace App\Models;

use App\Models\Traits\HasCovers;
use Encore\Admin\Traits\AdminBuilder;
use Encore\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Category extends Model
{

    use AdminBuilder, ModelTree, HasCovers;

    const  TYPE_LINK    = 'link';
    const  TYPE_ARTICLE = 'article';
    const  TYPE_ADVERT  = 'advert';
    const  TYPE_PERSON  = 'person';
    const  TYPE_LEADER  = 'leader';

    const TYPES = [
        self::TYPE_ARTICLE => '文章列表',
        self::TYPE_LINK    => '外链',
        self::TYPE_ADVERT  => '图片',
        self::TYPE_PERSON  => '领导',
        self::TYPE_LEADER  => '人才梯队',
    ];

    /**
     * Notes: 跳转链接
     *
     * @Author: 玄尘
     * @Date: 2022/4/28 13:53
     * @return string
     */
    public function getLinkAttribute(): string
    {
        switch ($this->type) {
            case self::TYPE_LEADER:
                return route('leader.index');
            case self::TYPE_PERSON:
                return route('staff.index');
            default:
                return route('category.show', $this);

        }
    }

    /**
     * 关联的数据
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo|\Illuminate\Database\Eloquent\Relations\BelongsToMany|\Illuminate\Database\Eloquent\Relations\HasMany|null [type] [description]
     */
    public function relations()
    {
        switch ($this->type) {
            case self::TYPE_ARTICLE:
                return $this->belongsToMany(Article::class);
                break;
            case self::TYPE_ADVERT:
                return $this->hasMany(Advert::class);
                break;
            default:
                return null;
        }
    }

    public function childrens()
    {
        return $this->hasMany(self::class, 'parent_id');
    }

    public function parent()
    {
        return $this->hasOne(self::class, 'id', 'parent_id');
    }

    public function article()
    {
        return $this->belongsTo(Article::class);
    }

    public function articles(): BelongsToMany
    {
        return $this->belongsToMany(Article::class);
    }

    /**
     * Notes: 获取当前分类及子分类ID
     *
     * @Author: <C.Jason>
     * @Date  : 2020/4/6 3:12 下午
     * @return array
     */
    public function getAllChildrenId()
    {
        $ids = array_keys($this->buildSelectOptions([], $this->id));
        array_unshift($ids, $this->id);

        return $ids;
    }

    /**
     * Notes: 获取顶级分类
     *
     * @Author: 玄尘
     * @Date: 2022/4/28 13:52
     * @param $category_id
     * @return void
     */
    public function getTopCategory()
    {
        $category = $this;

        while ($category) {
            if ($category->parent) {
                $category = $category->parent;
            } else {
                return $category;
            }
        }
    }

}
