<?php
declare (strict_types = 1);

namespace app\admin\model\v1;

use app\common\model\ArticleBaseModel;
use think\model\concern\SoftDelete;

/**
 * @mixin \think\Model
 */
class ArticleModel extends ArticleBaseModel
{
    // 启用软删除
    use SoftDelete;
    // 软删除标记数据字段
    protected $deleteTime = 'deleted_at';

    // 写入前，处理发布时间为空情况
    public static function onBeforeWrite(ArticleModel $article)
    {
        $article->release_time = empty($article->release_time) ? null : $article->release_time;
    }

    // 关联分类
    public function category()
    {
        return $this->belongsTo(ArticleCategoryModel::class, 'category_id', 'id');
    }

    // 搜索名称
    public function searchTitleAttr($query, $value, $data)
    {
        if (is_null($value)) {
            return;
        }
        $query->where('title', 'like', '%' . $value . '%');
    }

    // 搜索发布时间
    public function searchReleaseTimeAttr($query, $value, $data)
    {
        if (is_null($value)) {
            return;
        }
        if (is_array($value)) {
            if (count($value) == 2) {
                if ($value[0] == $value[1]) {
                    $value[1] = date('Y-m-d 23:59:59', strtotime($value[1]));
                }
                $query->whereBetweenTime('release_time', $value[0], $value[1]);
            } else {
                $query->whereTime('release_time', '>=', $value[0]);
            }
        }
    }

    // 搜索新增时间
    public function searchCreatedAtAttr($query, $value, $data)
    {
        if (is_null($value)) {
            return;
        }
        if (is_array($value)) {
            if (count($value) == 2) {
                if ($value[0] == $value[1]) {
                    $value[1] = date('Y-m-d 23:59:59', strtotime($value[1]));
                }
                $query->whereBetweenTime('created_at', $value[0], $value[1]);
            } else {
                $query->whereTime('created_at', '>=', $value[0]);
            }
        }
    }

    // 语言查询
    public function scopeLanguage($query, $value)
    {
        if (is_null($value)) {
            return;
        }
        $query->where('language_id', '=', $value);
    }

    // 分类查询
    public function scopeCategory($query, $value)
    {
        if (is_array($value) || str_contains($value, ',')) {
            $query->whereIn('category_id', $value);
            return;
        }
        $query->where('category_id', '=', $value);
    }
    public function scopeCategoryNullable($query, $value) 
    {
        if (is_null($value)) {
            return;
        }
        if (is_array($value) || str_contains($value, ',')) {
            $query->whereIn('category_id', $value);
            return;
        }
        $query->where('category_id', '=', $value);
    }
}
