package com.ycwl.basic.order.strategy.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ycwl.basic.order.entity.OrderItemV2;
import com.ycwl.basic.order.entity.OrderV2;
import com.ycwl.basic.order.enums.OrderStatus;
import com.ycwl.basic.order.enums.PaymentStatus;
import com.ycwl.basic.order.exception.DuplicatePurchaseException;
import com.ycwl.basic.order.mapper.OrderItemMapper;
import com.ycwl.basic.order.mapper.OrderV2Mapper;
import com.ycwl.basic.order.strategy.DuplicateCheckContext;
import com.ycwl.basic.order.strategy.IDuplicatePurchaseChecker;
import com.ycwl.basic.pricing.enums.ProductType;
import com.ycwl.basic.product.capability.DuplicateCheckStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 父资源/套餐重复购买检查策略
 * 适用于：套餐类商品（RECORDING_SET录像集、PHOTO_SET照片集等）
 *
 * 检查逻辑：
 * 1. 查找用户在该景区已支付的有效订单
 * 2. 检查订单明细中是否包含相同product_type的商品（不关心具体productId）
 * 3. 如果存在，抛出重复购买异常
 *
 * SQL查询: WHERE order_id = ? AND product_type = ?
 */
@Lazy
@Slf4j
@Component
public class ParentResourceDuplicateChecker implements IDuplicatePurchaseChecker {

    @Autowired
    private OrderV2Mapper orderV2Mapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public DuplicateCheckStrategy getStrategyType() {
        return DuplicateCheckStrategy.PARENT_RESOURCE;
    }

    @Override
    public void check(DuplicateCheckContext context) throws DuplicatePurchaseException {
        String userId = context.getUserId();
        String scenicId = context.getScenicId();
        String productType = context.getProductType();  // 如"RECORDING_SET"或"PHOTO_SET"

        // 获取人脸ID（从扩展参数中）
        Long faceId = context.getParam("faceId");

        log.debug("执行父资源重复购买检查: userId={}, faceId={}, scenicId={}, productType={}",
                userId, faceId, scenicId, productType);

        // 构建查询条件：查找已支付的有效订单
        QueryWrapper<OrderV2> orderQuery = new QueryWrapper<>();
        orderQuery.eq("member_id", userId)
                .eq("scenic_id", scenicId)
                .eq("payment_status", PaymentStatus.PAID.getCode())
                .in("order_status",
                        OrderStatus.PAID.getCode(),
                        OrderStatus.PROCESSING.getCode(),
                        OrderStatus.COMPLETED.getCode())
                .eq("deleted", 0);

        // 如果提供了人脸ID，也作为查询条件
        if (faceId != null) {
            orderQuery.eq("face_id", faceId);
        }

        List<OrderV2> existingOrders = orderV2Mapper.selectList(orderQuery);

        for (OrderV2 order : existingOrders) {
            // 检查订单明细中是否包含该类型的商品（仅按productType匹配）
            QueryWrapper<OrderItemV2> itemQuery = new QueryWrapper<>();
            itemQuery.eq("order_id", order.getId())
                    .eq("product_type", productType);  // 仅按productType匹配

            long count = orderItemMapper.selectCount(itemQuery);
            if (count > 0) {
                log.warn("检测到重复购买父资源: userId={}, faceId={}, scenicId={}, productType={}, existingOrderId={}",
                        userId, faceId, scenicId, productType, order.getId());

                ProductType productTypeEnum = ProductType.fromCode(productType);

                throw new DuplicatePurchaseException(
                        String.format("您已购买过%s", productTypeEnum.getDescription()),
                        order.getId(),
                        order.getOrderNo(),
                        productTypeEnum
                );
            }
        }

        log.debug("父资源重复购买检查通过: userId={}, faceId={}, scenicId={}, productType={}",
                userId, faceId, scenicId, productType);
    }
}
