<?php

namespace App\Models;

use App\Models\traits\Filter;

class GoodsSku extends Model
{
    use Filter;

    //查询字段
    public $fieldSearchable = [
        'sku_title',
        'status',
        'exclude_ids',
        'external_sku_id',
        'is_combination',
        "create_time_start",
        "create_time_end",
        'min_stock',
        'max_stock',
        'min_sale_stock',
        'max_sale_stock',
        "neq_stock",
        "neq_sale_stock",
    ];

    protected $fillable = [
        'goods_id',
        'title',
        'sku_code',
        'status',
        'num',
        'stock',
        'cost',
        'two_days_ago_num',
        'yesterday_num',
        'reference_price',
        'reserve',
        'thumb_url',
        'external_sku_id',
        'is_combination',
        'name',
        'sale_stock',
        'attribute'
    ];

    public static $STATUS_ON_SALE = 1;
    public static $STATUS_DOWN = 0;

    /**
     * 获取状态
     *
     * @param string $value
     * @return string
     */
    public function getStatusAttribute($value)
    {
        $map = [
            0 => '下架',
            1 => '在售',
            2 => '预警',
        ];
        return $map[$value];
    }

    public function setThumbUrlAttribute($value)
    {
        $this->attributes['thumb_url'] = json_encode($value, 256);
    }

    public function getThumbUrlAttribute($value)
    {
        return json_decode($value, true);
    }

    public function getNameAttribute($value)
    {
        if(empty($value)){
            return $this->attributes['title']??'';
        }
        return $value;
    }

    /**
     * 此规格从属于一个商品
     */
    public function goods()
    {
        return $this->belongsTo(Goods::class, 'goods_id', 'id');
    }

    /**
     * 此规格每日记录
     */
    public function daily()
    {
        return $this->hasOne(DailyStockRecord::class, 'sku_id', 'id');
    }

    public function combinationItems()
    {
        return $this->hasMany(CombinationGood::class, 'item_id', 'id');
    }

    public function combinationGoods()
    {
        return $this->hasMany(CombinationGood::class, 'goods_sku_id', 'id');
    }

    public function todayPrice()
    {
        return $this->hasOne(TodayPrice::class, 'external_sku_id', 'external_sku_id');
    }
}
