<?php

namespace app\model\mall;

use app\model\Base;
use app\model\Spu;
use Exception;
use think\model\relation\HasOne;

class SpuLimitTime extends Base
{
    public const TYPE = 'limit_time';// 活动类型

    /**
     * 获取限时折扣列表
     *
     * @param  array  $where
     * @param  array  $field
     * @param  int  $page
     * @param  int  $size
     * @param  callable|null  $callable
     * @param  array  $order
     * @return array
     * @throws Exception
     */
    public static function fetchList(array $where, array $field = [], int $page = 1, int $size = 20, callable $callable = null, array $order = []): array
    {
        $res = SpuLimitTime::findList($where, $field, $page, $size, $callable, $order);

        $res['list'] = $res['list']->each(function ($item) {
            $statusText = '进行中';
            $now        = date('Y-m-d H:i:s');
            if ($item['begin_at'] > $now) {
                $statusText = '未开始';
            }

            if ($item['begin_at'] < $now && $now < $item['end_at']) {
                $statusText = '进行中';
            }

            if ($item['end_at'] < $now) {
                $statusText = '已结束';
            }

            $item->activity_status = $statusText;
            $item->status_text = $item->is_restore == SpuLimitTime::COMMON_ON ? '暂停' : '开启';
        });

        return $res;
    }

    /**
     * @return HasOne
     */
    public function spu(): HasOne
    {
        return $this->hasOne(Spu::class, 'id', 'spu_id');
    }
}