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

namespace app\common\model;

use file\PathHelper;
use think\Exception;
use think\Model;

class Article extends Model
{
    const STATUS_OPEN = 1;
    const STATUS_CLOSE = 0;


    //description
    public function getDescriptionAttr($value, $data)
    {
        if (empty($data['seo_description'])) {
            //尝试从文章内容提取描述,去掉HTML及PHP标记
            return strip_tags(subStrCN($data['content'], 200));
        }
        return $data['seo_description'];
    }

    //get_seo_title
    public function getGetSeoTitleAttr($value, $data)
    {
        if (empty($data['seo_title'])) {
            return $data['title'];
        }
        return $data['seo_title'];
    }

    //content
    public function getContentAttr($value, $data)
    {
        if ($this->article_editor == 'markdown') {
            return $data['content2'];
        }
        return $value;
    }

    /**
     * 获取缩略图，尝试从内容中提取
     * @return bool|mixed|string
     */
    public function getThumb()
    {
        if ($this->thumb) {
            return geturl($this->thumb);
        } else {
            if (empty($this->content)) {
                return "";
            }
            $imgs = matchImg($this->content);
            return count($imgs) == 0 ? "" : $imgs[0];
        }
    }

    /**
     * 按规则生成路径
     * @param $catalogPath [uri使用相对路径,生成文件用物理路径]
     * @param $rule [文章路径规则]
     * @return mixed
     * @throws \Exception
     */
    public function getRulePath($catalogPath, $rule)
    {
        if (empty($rule)) {
            throw new Exception("null articleRule error");
        }

        $rule = replaceDS($rule);//处理分隔符
        $time = $this->getData('create_time');
        $search = ["{cpath}", "{Y}", "{M}", "{D}", "{aid}", "{cid}", "{tid}", "{tpath}"];
        $replace = [
            PathHelper::getDir($catalogPath),
            date('Y', $time),
            date('m', $time),
            date('d', $time),
            $this->filename ?: $this->id,
            $this->catalog_id,
            $this->article_cate_id,
            $this->article_cate_id && $this->cate ? $this->cate->tpath() : "",
        ];
        $rulePath = replaceDS(str_replace($search, $replace, $rule));

        if (ifContain($catalogPath, Templet::getRootDir())) {
            //生成操作时,处理路径不在根目录里的
            if (!ifContain($rulePath, Templet::getRootDir()))
                $rulePath = Templet::getRootDir() . deleteStartDS($rulePath);
        } else {
            //获取URI时,处理路径{aid}.html
            $rulePath = appendStartDS($rulePath);
        }
        return $rulePath;
    }


    /**
     * 获取文章uri
     * @param int $catalogId [文章设置了分类，且分类设置了多个栏目时，可指定栏目Id]
     * @return mixed|string
     * @throws \Exception
     */
    public function getUri($catalogId = 0)
    {
        if ($this->article_cate_id && $this->catalog_id) {
            throw new \Exception("文章不能同时发布到栏目和分类");
        }
        if ($this->article_cate_id) {
            if (empty($this->cate) || empty($this->cate->catalogs)) {
                throw new \Exception("文章{$this->id}找不到对应的栏目");
            }
            $catalogs = $this->cate->catalogs;
            //有多个栏目时，默认第一个栏目，排序最大的
            $catalog = $catalogs[0];
            //如果有指定 $catalogId ，则获取对应的栏目
            if ($catalogId && count($catalogs) > 0) {
                foreach ($catalogs as $catalog_) {
                    if ($catalog_->id == $catalogId)
                        $catalog = $catalog_;
                }
            }
        } elseif ($this->catalog_id) {
            $catalog = $this->catalog;
        } else {
            return "";
        }
        return replaceUrlDS($this->getRulePath($catalog->path, $catalog->article_rule));
    }

    /**
     * 当文章发布到多个栏目时，通过匹配路径获取文章uri
     * @param string $path_pattern
     * @return mixed|string
     */
    public function getUriByPattern($path_pattern = "/m/")
    {
        if ($this->article_cate_id) {
            $catalogs = $this->cate->catalogs;
            foreach ($catalogs as $catalog) {
                if (ifContain($catalog->path, $path_pattern)) {
                    return $this->getUri($catalog->id);
                }
            }
        }
        return $this->getUri();
    }

    /**
     * 标签
     * @return array 数组
     */
    public function getTags()
    {
        if (empty($this->tag)) {
            return [];
        }
        return explode(',', $this->tag);
    }

    /**
     * 上一篇
     */
    public function last()
    {
        $where = [
            'status' => self::STATUS_OPEN,
            'article_cate_id' => $this->article_cate_id,
            'catalog_id' => $this->catalog_id
        ];
        return $this->where("id", "<", $this->id)->where($where)->order('id desc')->find();
    }

    /**
     * 下一篇
     */
    public function next()
    {
        $where = [
            'status' => self::STATUS_OPEN,
            'article_cate_id' => $this->article_cate_id,
            'catalog_id' => $this->catalog_id
        ];
        return $this->where("id", ">", $this->id)->where($where)->order('id asc')->find();
    }


    /**
     * 获取多个栏目属性集合
     */
    public function getCatalogValues($field = "title")
    {
        $catalogs = $this->cate->catalogs;
        if ($catalogs) {
            $name = [];
            foreach ($catalogs as $catalog) {
                $name[] = $catalog->getData($field);
            }
            return implode(',', $name);
        }
        return "";
    }

    //关联多栏目(通过分类发布到栏目时)
    public function catalogs()
    {
        if (empty($this->article_cate_id) && empty($this->catalog_id)) {
            throw new Exception("请先关联栏目或分类");
        }
        if (!$this->cate) {
            throw new Exception("文章{$this->id}找不到对应的分类");
        }
        if (!$this->cate->catalogs) {
            throw new Exception("文章{$this->id}找不到对应的栏目");
        }
        return $this->cate->catalogs;
    }

    //获取一个栏目(多栏目时)
    public function getFirstCatalog()
    {
        if (!$this->cate) {
            throw new Exception("文章{$this->id}找不到对应的分类");
        }
        $catalogs = $this->cate->catalogs;
        if (empty($catalogs)) {
            throw new Exception("文章{$this->id}找不到对应的栏目");
        }
        //有多个栏目时，默认第一个栏目，排序最大的
        return $catalogs[0];
    }

    //关联栏目(直接发布到栏目时)
    public function catalog()
    {
        return $this->belongsTo('Catalog');
    }

    //关联分类
    public function cate()
    {
        return $this->belongsTo('ArticleCate');
    }

    //发布人
    public function admin()
    {
        return $this->belongsTo('Admin');
    }

    //修改人
    public function editor()
    {
        return $this->belongsTo('Admin', 'edit_admin_id');
    }
}
