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

import com.ycwl.basic.pricing.dto.*;
import com.ycwl.basic.pricing.service.ICouponService;
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 CouponDiscountProvider implements IDiscountProvider {
    
    private final ICouponService couponService;
    
    @Override
    public String getProviderType() {
        return "COUPON";
    }
    
    @Override
    public int getPriority() {
        return 80; // 优惠券优先级为80，低于券码的100
    }
    
    @Override
    public List<DiscountInfo> detectAvailableDiscounts(DiscountDetectionContext context) {
        List<DiscountInfo> discounts = new ArrayList<>();
        
        if (!Boolean.TRUE.equals(context.getAutoUseCoupon()) || context.getUserId() == null) {
            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;
    }
}