<?php
declare (strict_types = 1);

namespace app\index\model;

use app\common\model\ProductBaseModel;
use think\facade\Db;
use think\model\concern\SoftDelete;

/**
 * 产品模型
 * @mixin \think\Model
 */
class ProductModel extends ProductBaseModel
{
    // 启用软件删除
    use SoftDelete;
    // 软件删除时间字段
    protected $deleteTime = 'deleted_at';

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

    // 关联sku
    public function sku()
    {
        return $this->hasMany(ProductSkuModel::class, 'product_id', 'id');
    }

    // 所属分类范围查询
    public function scopeByCategory($query, $category)
    {
        if (is_array($category)) {
            $query->whereIn('category_id', $category);
            return;
        }
        $query->where('category_id', '=', $category);
    }

    // 所属语言范围查询
    public function scopeLanguage($query, $language)
    {
        $query->where('language_id', '=', $language);
    }

    // 启用状态范围查询
    public function scopeEnabled($query)
    {
        $query->where('status', '=', 1);
    }

    // 在售状态范围查询
    public function scopeOnSale($query, bool $stat = true)
    {
        $query->where('is_sale', '=', (int)$stat);
    }

    // 上架状态范围查询
    public function scopeOnShelves($query, bool $stat = true)
    {
        $query->where('is_show', '=', (int)$stat);
    }

    // 热销状态范围查询
    public function scopeHot($query, bool $stat = true)
    {
        $query->where('is_hot', '=', (int)$stat);
    }

    // 新品状态范围查询
    public function scopeIsNew($query, bool $stat = true)
    {
        $query->where('is_new', '=', (int)$stat);
    }

    // 关键词搜索
    public function searchKeywordsAttr($query, string $keywords)
    {
        $query->whereRaw('spu LIKE "%' . $keywords . '%" OR name LIKE "%' . $keywords . '%" OR short_name LIKE "%' . $keywords . '%"');
    }
}
