<?php

namespace Modules\User\Models;


use App\Models\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Arr;
use Modules\Mall\Models\Order;
use Modules\User\Traits\BelongsToUser;

class UserStock extends Model
{
    use BelongsToUser;

    const STATUS_PAID      = 1;
    const STATUS_DELIVER   = 2;
    const STATUS_DELIVERED = 3;
    const STATUS_SIGNED    = 4;

    const STOCK_ORDER_STATUS = [
        self::STATUS_PAID      => '待提货',
        self::STATUS_DELIVER   => '待发货',
        self::STATUS_DELIVERED => '待签收',
        self::STATUS_SIGNED    => '已签收',
    ];

    const STOCK_ORDER_STATUS_MAP = [
        '待提货' => 'primary',
        '待发货' => 'success',
        '待签收' => 'danger',
        '已签收' => 'info',
    ];

    public $appends = ['residue'];

    /**
     * Notes: 获取剩余
     *
     * @Author: 玄尘
     * @Date: 2022/7/29 14:01
     * @return string
     */
    public function getResidueAttribute()
    {
        return bcsub($this->stock, $this->hold);
    }

    /**
     * Notes: 日志
     *
     * @Author: 玄尘
     * @Date: 2022/8/2 14:43
     * @return HasMany
     */
    public function logs(): HasMany
    {
        return $this->hasMany(UserStockLog::class);
    }

    /**
     * Notes: 获取体验官提货订单状态
     *
     * @Author: 玄尘
     * @Date: 2022/9/1 16:40
     */
    public function getStockOrderStatusAttribute()
    {
        $order = $this->user->orders()->first();
        if (empty($order)) {
            return 1;
        } elseif ($order->state == Order::STATUS_PAID) {
            return 2;
        } elseif ($order->state == Order::STATUS_DELIVERED) {
            return 3;
        } elseif ($order->state == Order::STATUS_SIGNED) {
            return 4;
        }
    }


    /**
     * Notes: 获取体验官订单名称
     *
     * @Author: 玄尘
     * @Date: 2022/9/1 16:45
     */
    public function getStockOrderStatusTextAttribute()
    {
        return Arr::get(self::STOCK_ORDER_STATUS, $this->stock_order_status, '未知');
    }

}
