<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务,帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件,不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\store\model\sharp;

use app\common\model\sharp\ActiveTime as ActiveTimeModel;
use app\store\model\sharp\ActiveGoods as ActiveGoodsModel;

/**
 * 整点秒杀-活动会场场次模型
 * Class ActiveTime
 * @package app\store\model\sharp
 */
class ActiveTime extends ActiveTimeModel
{
    /**
     * 获取活动会场场次列表
     * @param int $activeId 活动会场ID
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(int $activeId): \think\Paginator
    {
        return $this->with(['active'])
            ->withCount(['goods'])
            ->where('active_id', '=', $activeId)
            ->order(['active_time' => 'asc'])
            ->paginate(15);
    }

    /**
     * 修改商品状态
     * @param int $state
     * @return bool|false
     */
    public function setStatus(int $state): bool
    {
        return $this->save(['status' => $state]) !== false;
    }

    /**
     * 获取指定会场的所有场次时间
     * @param int $activeId 活动会场ID
     * @return array
     */
    public function getActiveTimeData(int $activeId): array
    {
        return $this->where('active_id', '=', $activeId)->column('active_time');
    }

    /**
     * 根据活动场次ID获取商品列表 (格式化后用于编辑页)
     * @param int $activeTimeId 场次ID
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function getGoodsListByActiveTimeId(int $activeTimeId): array
    {
        // 根据活动场次ID获取商品列表
        $list = ActiveGoodsModel::getGoodsListByActiveTimeId($activeTimeId);
        // 格式化
        $data = [];
        foreach ($list as $item) {
            $data[] = [
                'sharp_goods_id' => $item['sharp_goods_id'],
                'seckill_price_min' => $item['seckill_price_min'],
                'seckill_price_max' => $item['seckill_price_max'],
                'seckill_stock' => $item['seckill_stock'],
                'goods_id' => $item['goods_id'],
                'goods_name' => $item['goods']['goods_name'],
                'goods_image' => $item['goods']['goods_image'],
            ];
        }
        return $data;
    }

    /**
     * 新增记录
     * @param int $activeId 活动会场ID
     * @param array $data
     * @return bool|mixed
     */
    public function add(int $activeId, array $data)
    {
        // 表单验证
        if (!$this->onValidate($data)) return false;
        // 事务处理
        return $this->transaction(function () use ($activeId, $data) {
            // 新增活动场次
            $this->onBatchAdd(
                $activeId,
                $data['activeTimes'],
                $data['sharpGoodsIds'],
                $data['status']
            );
            return true;
        });
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool|mixed
     */
    public function edit(array $data)
    {
        // 验证是否选择商品
        if (!$this->onValidateSharpGoods($data)) {
            return false;
        }
        // 事务处理
        return $this->transaction(function () use ($data) {
            // 更新活动场次
            $this->save($data);
            // 更新场次的商品关联记录
            $this->onUpdateActiveGoodsRec($data['sharpGoodsIds']);
            return true;
        });
    }

    /**
     * 更新当前场次的商品关联记录
     * @param array $sharpGoodsIds 秒杀商品ID集
     * @return bool
     */
    private function onUpdateActiveGoodsRec(array $sharpGoodsIds): bool
    {
        // 数据整理
        $saveData = [];
        foreach ($sharpGoodsIds as $goodsId) {
            $saveData[] = [
                'active_id' => $this['active_id'],
                'active_time_id' => $this['active_time_id'],
                'sharp_goods_id' => $goodsId,
                'store_id' => static::$storeId,
            ];
        }
        // 删除商品关联关系
        ActiveGoodsModel::deleteAll(['active_time_id' => $this['active_time_id']]);
        // 再写入新的关联关系
        return (new ActiveGoodsModel)->addAll($saveData) !== false;
    }

    /**
     * 表单验证
     * @param array $data
     * @return bool
     */
    private function onValidate(array $data): bool
    {
        // 验证是否选择活动场次
        if (empty($data['activeTimes'])) {
            $this->error = '您还没有选择活动场次';
            return false;
        }
        // 验证是否选择商品
        if (!$this->onValidateSharpGoods($data)) {
            return false;
        }
        return true;
    }

    /**
     * 验证是否选择商品
     * @param array $data
     * @return bool
     */
    private function onValidateSharpGoods(array $data): bool
    {
        // 验证是否选择商品
        if (empty($data['sharpGoodsIds'])) {
            $this->error = '您还没有选择秒杀商品';
            return false;
        }
        return true;
    }

    /**
     * 批量新增活动场次
     * @param int $activeId 活动会场ID
     * @param array $times 活动场次数据
     * @param array $sharpGoodsIds 秒杀商品ID集
     * @param int $status 活动状态
     * @return bool
     */
    public function onBatchAdd(int $activeId, array $times, array $sharpGoodsIds, int $status = 1): bool
    {
        // 整理活动场次数据
        $timeData = [];
        foreach ($times as $time) {
            $timeData[] = [
                'active_id' => $activeId,
                'active_time' => (int)$time,
                'status' => (int)$status,
                'store_id' => static::$storeId,
            ];
        }
        // 批量新增活动场次
        $activeTimes = $this->addAll($timeData);
        // 新增活动场次与商品关联关系记录
        !empty($sharpGoodsIds) && $this->onBatchAddActiveGoodsRec($activeTimes, $sharpGoodsIds);
        return true;
    }

    /**
     * 新增活动场次与商品关联记录
     * @param mixed $activeTimes 活动场次集
     * @param array $sharpGoodsIds 秒杀商品ID集
     * @return bool
     */
    private function onBatchAddActiveGoodsRec($activeTimes, array $sharpGoodsIds): bool
    {
        $saveData = [];
        foreach ($activeTimes as $item) {
            foreach ($sharpGoodsIds as $goodsId) {
                $saveData[] = [
                    'active_id' => $item['active_id'],
                    'active_time_id' => $item['active_time_id'],
                    'sharp_goods_id' => $goodsId,
                    'store_id' => static::$storeId,
                ];
            }
        }
        return (new ActiveGoodsModel)->addAll($saveData) !== false;
    }

    /**
     * 根据活动ID删除全部场次和商品关系
     * @param int $activeId 活动会场ID
     * @return bool
     */
    public function onDeleteByActiveId(int $activeId): bool
    {
        // 事务处理
        $this->transaction(function () use ($activeId) {
            // 删除全部场次
            static::deleteAll(['active_id' => $activeId]);
            // 删除商品关联关系
            ActiveGoodsModel::deleteAll(['active_id' => $activeId]);
        });
        return true;
    }

    /**
     * 删除当前场次
     * @return bool
     */
    public function onDelete(): bool
    {
        // 事务处理
        $this->transaction(function () {
            // 删除当前记录
            $this->delete();
            // 删除商品关联关系
            ActiveGoodsModel::deleteAll(['active_time_id' => $this['active_time_id']]);
        });
        return true;
    }
}