package com.ycwl.basic.pricing.service.impl;

import com.ycwl.basic.pricing.dto.*;
import com.ycwl.basic.pricing.entity.PriceBundleConfig;
import com.ycwl.basic.pricing.entity.PriceProductConfig;
import com.ycwl.basic.pricing.service.ICouponService;
import com.ycwl.basic.pricing.service.IDiscountProvider;
import com.ycwl.basic.pricing.service.IPriceBundleService;
import com.ycwl.basic.pricing.service.IProductConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 优惠券折扣提供者
 */
@Slf4j
@Component
public class CouponDiscountProvider implements IDiscountProvider {
    
    private final ICouponService couponService;
    private final IProductConfigService productConfigService;
    private final IPriceBundleService bundleService;
    
    public CouponDiscountProvider(@Lazy ICouponService couponService,
                                  @Lazy IProductConfigService productConfigService,
                                  @Lazy IPriceBundleService bundleService) {
        this.couponService = couponService;
        this.productConfigService = productConfigService;
        this.bundleService = bundleService;
    }
    
    @Override
    public String getProviderType() {
        return "COUPON";
    }
    
    @Override
    public int getPriority() {
        return 60; // 优惠券优先级最低
    }
    
    @Override
    public List<DiscountInfo> detectAvailableDiscounts(DiscountDetectionContext context) {
        List<DiscountInfo> discounts = new ArrayList<>();
        
        if (!Boolean.TRUE.equals(context.getAutoUseCoupon()) || context.getUserId() == null) {
            return discounts;
        }
        
        // 检查商品配置和打包配置是否允许使用优惠券
        if (!checkCanUseCoupon(context)) {
            log.debug("商品配置不允许使用优惠券，跳过优惠券检测");
            return discounts;
        }
        
        try {
            CouponInfo bestCoupon = couponService.selectBestCoupon(
                context.getUserId(), 
                context.getProducts(), 
                context.getCurrentAmount()
            );
            
            if (bestCoupon != null && bestCoupon.getActualDiscountAmount().compareTo(BigDecimal.ZERO) > 0) {
                DiscountInfo discountInfo = new DiscountInfo();
                discountInfo.setDiscountId(bestCoupon.getCouponId());
                discountInfo.setDiscountType("COUPON");
                discountInfo.setDiscountName(bestCoupon.getCouponName());
                discountInfo.setDiscountDescription("优惠券减免");
                discountInfo.setDiscountAmount(bestCoupon.getActualDiscountAmount());
                discountInfo.setProviderType(getProviderType());
                discountInfo.setPriority(getPriority());
                discountInfo.setStackable(true); // 优惠券可与券码叠加
                discountInfo.setCouponId(bestCoupon.getCouponId());
                
                discounts.add(discountInfo);
            }
        } catch (Exception e) {
            log.warn("检测优惠券时发生异常", e);
        }
        
        return discounts;
    }
    
    @Override
    public DiscountResult applyDiscount(DiscountInfo discountInfo, DiscountDetectionContext context) {
        DiscountResult result = new DiscountResult();
        result.setDiscountInfo(discountInfo);
        
        try {
            // 应用优惠券逻辑
            BigDecimal actualDiscount = discountInfo.getDiscountAmount();
            BigDecimal finalAmount = context.getCurrentAmount().subtract(actualDiscount);
            
            if (finalAmount.compareTo(BigDecimal.ZERO) < 0) {
                finalAmount = BigDecimal.ZERO;
                actualDiscount = context.getCurrentAmount();
            }
            
            result.setActualDiscountAmount(actualDiscount);
            result.setFinalAmount(finalAmount);
            result.setSuccess(true);
            
            log.info("成功应用优惠券: {}, 优惠金额: {}", discountInfo.getDiscountName(), actualDiscount);
            
        } catch (Exception e) {
            log.error("应用优惠券失败: " + discountInfo.getDiscountName(), e);
            result.setSuccess(false);
            result.setFailureReason("优惠券应用失败: " + e.getMessage());
        }
        
        return result;
    }
    
    @Override
    public boolean canApply(DiscountInfo discountInfo, DiscountDetectionContext context) {
        return "COUPON".equals(discountInfo.getDiscountType()) && 
               Boolean.TRUE.equals(context.getAutoUseCoupon()) &&
               context.getUserId() != null &&
               checkCanUseCoupon(context);
    }
    
    /**
     * 检查商品配置和打包配置是否允许使用优惠券
     */
    private boolean checkCanUseCoupon(DiscountDetectionContext context) {
        if (context.getProducts() == null || context.getProducts().isEmpty()) {
            return true; // 如果没有商品信息，默认允许
        }
        
        try {
            // 检查是否使用了打包购买
            BigDecimal bundlePrice = bundleService.getBundlePrice(context.getProducts());
            if (bundlePrice != null) {
                // 如果使用了打包购买，检查打包配置的优惠券使用开关
                PriceBundleConfig bundleConfig = bundleService.getBundleConfig(context.getProducts());
                if (bundleConfig != null) {
                    boolean canUseCoupon = Boolean.TRUE.equals(bundleConfig.getCanUseCoupon());
                    log.debug("打包配置优惠券开关检查: bundleId={}, canUseCoupon={}", bundleConfig.getId(), canUseCoupon);
                    return canUseCoupon;
                }
            }
            
            // 检查单个商品的优惠券使用开关（使用景区维度配置）
            for (ProductItem product : context.getProducts()) {
                String productId = product.getProductId() != null ? product.getProductId() : "default";

                try {
                    PriceProductConfig productConfig = productConfigService.getProductConfig(
                        product.getProductType().getCode(), productId, context.getScenicId());

                    if (productConfig != null) {
                        if (!Boolean.TRUE.equals(productConfig.getCanUseCoupon())) {
                            log.debug("商品配置不允许使用优惠券: productType={}, productId={}, scenicId={}",
                                product.getProductType().getCode(), productId, context.getScenicId());
                            return false;
                        }
                    }
                } catch (Exception e) {
                    // 如果获取具体商品配置失败，尝试获取default配置
                    try {
                        PriceProductConfig defaultConfig = productConfigService.getProductConfig(
                            product.getProductType().getCode(), "default", context.getScenicId());

                        if (defaultConfig != null) {
                            if (!Boolean.TRUE.equals(defaultConfig.getCanUseCoupon())) {
                                log.debug("商品默认配置不允许使用优惠券: productType={}, scenicId={}",
                                    product.getProductType().getCode(), context.getScenicId());
                                return false;
                            }
                        }
                    } catch (Exception ex) {
                        log.warn("获取商品配置失败，默认允许使用优惠券: productType={}, productId={}, scenicId={}",
                            product.getProductType().getCode(), productId, context.getScenicId());
                    }
                }
            }
            
        } catch (Exception e) {
            log.error("检查优惠券使用开关时发生异常，默认允许使用", e);
        }
        
        return true; // 默认允许使用优惠券
    }
}