<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class AgentShop extends BaseModel
{
    use HasFactory;

    public $fillable = ['shop_id', 'sku', 'ratio', 'freight', 'lotto_code', 'is_show', 'payment_id'];

    //渣酒id
    public const WINEID = 3;
    public const ALPHA_WINEID = 1;
    //渣酒抽奖id
    public const LOTTERYID = 41;
    public const ALPHA_LOTTERYID = 18;
    //手环id
    public const BANDID = 89;
    public const ALPHA_BANDID = 1;
    //手环抽奖
    public const BAND_LOTTERY_ID = 39;
    public const ALPHA_BAND_LOTTERY_ID = 18;

    protected $casts = [
        'sku' => 'array',
    ];

    public function scopeShow($query)
    {
        return $query->where('is_show', 1);
    }

    public function getSkus()
    {
        $agent_shop_skus = $this->sku;
        $shop_skus = $this->shop->sku;
        $skus =[];
        foreach ($agent_shop_skus as $agent_shop_sku){

            foreach ($shop_skus as $shop_sku) {
                if ($shop_sku['sku_id'] == $agent_shop_sku['sku_id']) {
                    $shop_sku['name'] = $agent_shop_sku['sku_name']??$shop_sku['name'];
                    $skus[] = array_merge($agent_shop_sku,$shop_sku);
                }
            }
        }
        return $skus;
    }

    public function shop()
    {
        return $this->belongsTo(Shop::class, 'shop_id', 'id');
    }
    public static function getGoodsShip($sku, $num) {
        if ($num <= $sku["ship_num"]) return $sku['ship_price'];
        $over_num = number_format($num - $sku['ship_num']);
        $ship_price = $sku['ship_price'] + $over_num * $sku['ship_each_price'];
        if ($sku['ship_max_price'] && $ship_price > $sku['ship_max_price']) return $sku['ship_max_price'];
        return $ship_price;
    }

    public function payment()
    {
        return $this->belongsTo(Payment::class, 'payment_id', 'id');
    }
}
