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

import com.ycwl.basic.pricing.dto.*;
import com.ycwl.basic.pricing.service.IBundleDiscountService;
import com.ycwl.basic.pricing.service.IDiscountProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

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

/**
 * 打包购买优惠提供者
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class BundleDiscountProvider implements IDiscountProvider {

    private final IBundleDiscountService bundleDiscountService;

    @Override
    public String getProviderType() {
        return "BUNDLE_PURCHASE";
    }

    @Override
    public int getPriority() {
        return 100; // 第二高优先级，仅次于一口价
    }

    @Override
    public List<DiscountInfo> detectAvailableDiscounts(DiscountDetectionContext context) {
        List<DiscountInfo> discounts = new ArrayList<>();

        try {
            if (context.getProducts() == null || context.getProducts().isEmpty()) {
                log.debug("打包优惠检测失败: 商品列表为空");
                return discounts;
            }

            // 检测所有可用的打包优惠
            List<BundleDiscountInfo> bundleDiscounts = bundleDiscountService.detectAvailableBundleDiscounts(context);

            for (BundleDiscountInfo bundleDiscount : bundleDiscounts) {
                if (bundleDiscount.getActualDiscountAmount() != null &&
                    bundleDiscount.getActualDiscountAmount().compareTo(BigDecimal.ZERO) > 0) {

                    // 创建优惠信息
                    DiscountInfo discountInfo = new DiscountInfo();
                    discountInfo.setProviderType(getProviderType());
                    discountInfo.setDiscountName(bundleDiscount.getBundleName());
                    discountInfo.setDiscountAmount(bundleDiscount.getActualDiscountAmount());
                    discountInfo.setDiscountDescription(bundleDiscount.getBundleDescription());
                    discountInfo.setBundleDiscountInfo(bundleDiscount);
                    discountInfo.setPriority(getPriority());
                    discountInfo.setStackable(true); // 默认可叠加，具体规则由配置控制

                    discounts.add(discountInfo);

                    log.info("检测到打包优惠: 名称={}, 优惠金额={}",
                            bundleDiscount.getBundleName(), bundleDiscount.getActualDiscountAmount());
                }
            }

        } catch (Exception e) {
            log.error("打包优惠检测失败", e);
        }

        return discounts;
    }

    @Override
    public DiscountResult applyDiscount(DiscountInfo discountInfo, DiscountDetectionContext context) {
        DiscountResult result = new DiscountResult();
        result.setDiscountInfo(discountInfo);
        result.setSuccess(false);

        try {
            if (!getProviderType().equals(discountInfo.getProviderType())) {
                result.setFailureReason("优惠类型不匹配");
                return result;
            }

            BundleDiscountInfo bundleDiscount = discountInfo.getBundleDiscountInfo();
            if (bundleDiscount == null) {
                result.setFailureReason("打包优惠信息为空");
                return result;
            }

            // 检查优惠的叠加限制
            boolean canUseWithOtherDiscounts = checkDiscountCombinationRules(bundleDiscount, context);
            if (!canUseWithOtherDiscounts) {
                result.setFailureReason("打包优惠不可与其他优惠叠加使用");
                return result;
            }

            // 重新验证打包优惠有效性
            if (!bundleDiscountService.isBundleDiscountValid(bundleDiscount, context)) {
                result.setFailureReason("打包优惠已失效");
                return result;
            }

            // 计算实际优惠金额
            BigDecimal actualDiscount = bundleDiscountService.calculateBundleDiscount(bundleDiscount, context.getProducts());
            if (actualDiscount.compareTo(BigDecimal.ZERO) <= 0) {
                result.setFailureReason("打包优惠金额为零");
                return result;
            }

            // 应用打包优惠
            BigDecimal finalAmount = context.getCurrentAmount().subtract(actualDiscount);
            if (finalAmount.compareTo(BigDecimal.ZERO) < 0) {
                finalAmount = BigDecimal.ZERO;
                actualDiscount = context.getCurrentAmount();
            }

            result.setSuccess(true);
            result.setActualDiscountAmount(actualDiscount);
            result.setFinalAmount(finalAmount);
            result.setFailureReason("打包购买优惠已应用");

            log.info("打包优惠应用成功: 优惠金额={}, 最终金额={}", actualDiscount, finalAmount);

        } catch (Exception e) {
            log.error("打包优惠应用失败", e);
            result.setFailureReason("打包优惠应用失败: " + e.getMessage());
        }

        return result;
    }

    @Override
    public boolean canApply(DiscountInfo discountInfo, DiscountDetectionContext context) {
        try {
            if (!getProviderType().equals(discountInfo.getProviderType())) {
                return false;
            }

            BundleDiscountInfo bundleDiscount = discountInfo.getBundleDiscountInfo();
            if (bundleDiscount == null) {
                return false;
            }

            // 检查打包优惠是否仍然有效
            return bundleDiscountService.isBundleDiscountValid(bundleDiscount, context);

        } catch (Exception e) {
            log.error("检查打包优惠可用性失败", e);
            return false;
        }
    }

    @Override
    public BigDecimal getMaxPossibleDiscount(DiscountInfo discountInfo, DiscountDetectionContext context) {
        try {
            BundleDiscountInfo bundleDiscount = discountInfo.getBundleDiscountInfo();
            if (bundleDiscount != null && bundleDiscount.getActualDiscountAmount() != null) {
                return bundleDiscount.getActualDiscountAmount();
            }

            // 如果没有预计算的优惠金额，重新计算
            if (bundleDiscount != null && context.getProducts() != null) {
                return bundleDiscountService.calculateBundleDiscount(bundleDiscount, context.getProducts());
            }

        } catch (Exception e) {
            log.error("获取打包优惠最大优惠金额失败", e);
        }

        return BigDecimal.ZERO;
    }

    /**
     * 检查优惠叠加规则
     */
    private boolean checkDiscountCombinationRules(BundleDiscountInfo bundleDiscount, DiscountDetectionContext context) {
        // 检查是否可以与优惠券叠加
        if (Boolean.FALSE.equals(bundleDiscount.getCanUseWithCoupon()) &&
            Boolean.TRUE.equals(context.getAutoUseCoupon())) {
            log.debug("打包优惠配置不允许与优惠券叠加使用");
            return false;
        }

        // 检查是否可以与券码叠加
        if (Boolean.FALSE.equals(bundleDiscount.getCanUseWithVoucher()) &&
            (Boolean.TRUE.equals(context.getAutoUseVoucher()) ||
             context.getVoucherCode() != null)) {
            log.debug("打包优惠配置不允许与券码叠加使用");
            return false;
        }

        // 检查是否可以与一口价叠加
        // 注意：由于一口价优先级更高，这个检查主要用于记录和调试
        if (Boolean.FALSE.equals(bundleDiscount.getCanUseWithOnePrice())) {
            log.debug("打包优惠配置不允许与一口价叠加使用");
            // 这里不返回false，因为一口价会优先应用，打包优惠不会被触发
        }

        return true;
    }
}