<?php

namespace App\Models;

use App\Models\Traits\BelongsToCategory;
use App\Models\Traits\HasCovers;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;

class Article extends Model
{

    use HasCovers, BelongsToCategory;

    public function getLinkAttribute(): string
    {
        return route('article.show', $this);
    }

    public function getLogoUrlAttribute(): string
    {
        return $this->parseImageUrl($this->logo);
    }

    /***
     * Notes: 获取详情内图片
     * @Author: 玄尘
     * @Date  : 2021/10/8 11:58
     * @return mixed|string
     */
    public function get_content_cover()
    {
        preg_match("/<img.*?src=\"([^\"]+)\"[^>].*?>/isU", str_ireplace("\\", "", $this->content), $matches);

        if (isset($matches[1])) {
            return $matches[1];
        } else {
            return '';
        }
    }

    /**
     * Notes: 获取一个默认图片
     * @Author: 玄尘
     * @Date  : 2020/6/3 16:29
     * @return mixed|string
     */
    public function get_one_cover()
    {
        if ($this->cover_url) {
            $path = $this->cover_url;
        } else {
            $path = $this->get_content_cover();
            if ($path) {
                $this->cover = str_replace("/storage", "", $path);
                $this->save();
                $path = config('app.url') . $path;

            }

        }

        return $path;

    }

    /**
     * Notes: 关联分类
     * @Author: 玄尘
     * @Date  : 2021/4/2 9:11
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function categories(): BelongsToMany
    {
        return $this->belongsToMany(Category::class)
                    ->using(ArticleCategory::class);
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }

    public function category_old(): BelongsTo
    {
        return $this->belongsTo(CategoryOld::class);
    }

    /**
     * Notes: description
     * @Author: 玄尘
     * @Date  : 2021/4/2 9:17
     * @param $query
     * @param $ids
     * @return mixed
     */
    public function scopeByCategory($query, $ids)
    {
        if (!is_array($ids)) {
            $ids = [$ids];
        }

        return $query->whereIn('category_id', $ids);
        //
        //        return $query->whereHas('categories', function ($q) use ($ids) {
        //            $q->whereIN('id', $ids);
        //        });
    }

}
