package org.dromara.mall.trade.service.impl;

import cn.hutool.core.lang.Dict;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.mall.promotion.domain.MallPromotion;
import org.dromara.mall.promotion.domain.vo.MallPromotionVo;
import org.dromara.mall.promotion.domain.vo.MallSeckillVo;
import org.dromara.mall.promotion.mapper.MallPromotionMapper;
import org.dromara.mall.promotion.service.MallSeckillService;
import org.dromara.mall.trade.service.SeckillOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 秒杀订单处理Service业务层实现
 *
 * @author pengles
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class SeckillOrderServiceImpl implements SeckillOrderService {

    private final MallSeckillService mallSeckillService;
    private final MallPromotionMapper promotionMapper;

    /**
     * 活动类型：秒杀
     */
    private static final Integer PROMOTION_TYPE_SECKILL = 2;

    /**
     * 默认限购数量
     */
    private static final Integer DEFAULT_PURCHASE_LIMIT = 1;

    /**
     * 验证秒杀活动是否可用
     */
    @Override
    public SeckillValidationResult validateSeckillActivity(Long seckillId, Integer quantity) {
        // 查询秒杀活动
        MallSeckillVo seckillVo = mallSeckillService.queryById(seckillId);
        if (seckillVo == null) {
            return new SeckillValidationResult(false, "秒杀活动不存在");
        }

        // 验证秒杀活动状态
        if (seckillVo.getStatus() != 0) {
            return new SeckillValidationResult(false, "秒杀活动已禁用");
        }

        // 验证秒杀活动时间
        Date now = new Date();
        if (seckillVo.getStartTime() != null && seckillVo.getStartTime().after(now)) {
            return new SeckillValidationResult(false, "秒杀活动尚未开始");
        }
        if (seckillVo.getEndTime() != null && seckillVo.getEndTime().before(now)) {
            return new SeckillValidationResult(false, "秒杀活动已结束");
        }

        // 验证秒杀库存
        if (seckillVo.getSeckillStock() == null || seckillVo.getSeckillStock() < quantity) {
            return new SeckillValidationResult(false, "秒杀库存不足");
        }

        // 验证关联的营销活动
        if (seckillVo.getPromotionId() != null) {
            MallPromotionVo promotionVo = promotionMapper.selectVoById(seckillVo.getPromotionId());
            if (promotionVo == null) {
                return new SeckillValidationResult(false, "关联的营销活动不存在");
            }
            if (promotionVo.getStatus() != 0) {
                return new SeckillValidationResult(false, "关联的营销活动已禁用");
            }
            if (!PROMOTION_TYPE_SECKILL.equals(promotionVo.getType())) {
                return new SeckillValidationResult(false, "关联的营销活动类型不正确");
            }
        }

        // 返回验证通过的结果，包含秒杀信息
        Map<String, Object> data = new HashMap<>();
        data.put("seckillPrice", seckillVo.getSeckillPrice());
        data.put("promotionId", seckillVo.getPromotionId());
        data.put("skuId", seckillVo.getSkuId());

        return new SeckillValidationResult(true, null, data);
    }

    /**
     * 验证秒杀限购
     */
    @Override
    public Boolean validatePurchaseLimit(Long seckillId, Long userId, Long skuId) {
        // 查询秒杀活动信息
        MallSeckillVo seckillVo = mallSeckillService.queryById(seckillId);
        if (seckillVo == null) {
            throw new ServiceException("秒杀活动不存在");
        }

        // 获取限购数量（从营销活动的rules JSON中读取，或使用默认值）
        Integer purchaseLimit = DEFAULT_PURCHASE_LIMIT;
        if (seckillVo.getPromotionId() != null) {
            MallPromotion promotion = promotionMapper.selectById(seckillVo.getPromotionId());
            if (promotion != null && promotion.getRules() != null) {
                try {
                    Dict rules = JsonUtils.parseMap(promotion.getRules());
                    if (rules != null && rules.containsKey("purchaseLimit")) {
                        Object limitObj = rules.get("purchaseLimit");
                        if (limitObj instanceof Number) {
                            purchaseLimit = ((Number) limitObj).intValue();
                        }
                    }
                } catch (Exception e) {
                    log.warn("解析营销活动规则JSON失败，使用默认限购数量: {}", e.getMessage());
                }
            }
        }

        // TODO: 查询用户已购买的秒杀订单数量
        // 注意：由于订单实体类和服务尚未实现，这里暂时返回true（允许购买）
        // 后续需要在订单服务中实现此逻辑：
        // 1. 查询用户已购买的秒杀订单数量（同一秒杀活动、同一SKU，仅统计已支付的订单）
        // 2. 校验是否超过限购数量
        // 示例代码（需要等订单服务实现后）：
        // LambdaQueryWrapper<MallOrder> lqw = new LambdaQueryWrapper<>();
        // lqw.eq(MallOrder::getUserId, userId);
        // lqw.eq(MallOrder::getSeckillId, seckillId);
        // lqw.eq(MallOrder::getPayStatus, PAY_STATUS_PAID);
        // lqw.ne(MallOrder::getOrderStatus, 4);
        // Long purchasedCount = orderMapper.selectCount(lqw);
        // return purchasedCount == null || purchasedCount < purchaseLimit;

        log.info("秒杀限购校验 - 秒杀ID: {}, 用户ID: {}, SKU ID: {}, 限购数量: {} (待订单服务实现后完善)", seckillId, userId, skuId, purchaseLimit);
        return true; // 临时返回true，待订单服务实现后完善
    }

    /**
     * 预扣秒杀库存
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean preDeductSeckillStock(Long seckillId, Integer quantity) {
        return mallSeckillService.reduceStock(seckillId, quantity);
    }

    /**
     * 恢复秒杀库存（订单取消时调用）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean restoreSeckillStock(Long seckillId, Integer quantity) {
        return mallSeckillService.restoreStock(seckillId, quantity);
    }

    /**
     * 获取秒杀价格
     */
    @Override
    public Integer getSeckillPrice(Long seckillId) {
        MallSeckillVo seckillVo = mallSeckillService.queryById(seckillId);
        if (seckillVo == null) {
            throw new ServiceException("秒杀活动不存在");
        }
        return seckillVo.getSeckillPrice();
    }

}
