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

import com.ycwl.basic.product.capability.DuplicateCheckStrategy;
import com.ycwl.basic.product.capability.PricingMode;
import com.ycwl.basic.product.capability.ProductTypeCapability;
import com.ycwl.basic.product.mapper.ProductTypeCapabilityMapper;
import com.ycwl.basic.product.service.IProductTypeCapabilityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * 商品类型能力服务实现
 */
@Slf4j
@Service
public class ProductTypeCapabilityServiceImpl implements IProductTypeCapabilityService {

    @Autowired
    private ProductTypeCapabilityMapper mapper;

    @Override
    public ProductTypeCapability getCapability(String productType) {
        if (productType == null || productType.trim().isEmpty()) {
            log.warn("商品类型代码为空，返回默认配置");
            return getDefaultCapability(null);
        }

        try {
            ProductTypeCapability capability = mapper.selectByProductType(productType);
            if (capability == null) {
                log.warn("未找到商品类型能力配置: {}, 使用默认配置", productType);
                return getDefaultCapability(productType);
            }

            // 验证配置完整性
            if (!isValidCapability(capability)) {
                log.warn("商品类型能力配置不完整: {}, 使用默认配置", productType);
                return getDefaultCapability(productType);
            }

            return capability;
        } catch (Exception e) {
            log.error("查询商品类型能力配置失败: {}, 降级到默认配置", productType, e);
            return getDefaultCapability(productType);
        }
    }

    @Override
    public String getDisplayName(String productType) {
        ProductTypeCapability capability = getCapability(productType);
        return capability.getDisplayName();
    }

    @Override
    public boolean allowDuplicatePurchase(String productType) {
        ProductTypeCapability capability = getCapability(productType);
        return Boolean.TRUE.equals(capability.getAllowDuplicatePurchase());
    }

    @Override
    public PricingMode getPricingMode(String productType) {
        ProductTypeCapability capability = getCapability(productType);
        return capability.getPricingModeEnum();
    }

    @Override
    public DuplicateCheckStrategy getDuplicateCheckStrategy(String productType) {
        ProductTypeCapability capability = getCapability(productType);
        return capability.getDuplicateCheckStrategyEnum();
    }

    @Override
    public void refreshCache() {
        log.info("刷新所有商品类型能力缓存");
    }

    @Override
    public void refreshCache(String productType) {
        log.info("刷新商品类型能力缓存: {}", productType);
    }

    /**
     * 获取默认能力配置（兜底方案）
     * 设计原则：安全第一，宁可限制也不放开
     *
     * @param productType 商品类型代码（可为null）
     * @return 安全的默认配置
     */
    private ProductTypeCapability getDefaultCapability(String productType) {
        ProductTypeCapability defaultCap = new ProductTypeCapability();
        defaultCap.setProductType(productType);
        defaultCap.setDisplayName("景区商品");
        defaultCap.setCategory("GENERAL");

        // 定价相关：默认固定价格
        defaultCap.setPricingMode(PricingMode.FIXED.getCode());
        defaultCap.setSupportsTierPricing(false);

        // 购买限制：默认不允许重复购买（安全策略）
        defaultCap.setAllowDuplicatePurchase(false);
        defaultCap.setDuplicateCheckStrategy(DuplicateCheckStrategy.NO_CHECK.getCode());

        // 优惠能力：默认全部允许
        defaultCap.setCanUseCoupon(true);
        defaultCap.setCanUseVoucher(true);
        defaultCap.setCanUseOnePrice(true);
        defaultCap.setCanUseBundle(true);

        defaultCap.setIsActive(true);

        return defaultCap;
    }

    /**
     * 验证配置完整性
     */
    private boolean isValidCapability(ProductTypeCapability capability) {
        if (capability == null) {
            return false;
        }

        // 必填字段检查
        if (capability.getProductType() == null || capability.getProductType().trim().isEmpty()) {
            return false;
        }

        if (capability.getDisplayName() == null || capability.getDisplayName().trim().isEmpty()) {
            return false;
        }

        if (capability.getPricingMode() == null) {
            return false;
        }

        // 验证枚举值有效性
        try {
            PricingMode.fromCode(capability.getPricingMode());
            if (capability.getDuplicateCheckStrategy() != null) {
                DuplicateCheckStrategy.fromCode(capability.getDuplicateCheckStrategy());
            }
        } catch (IllegalArgumentException e) {
            log.error("商品类型能力配置包含无效的枚举值: {}", capability.getProductType(), e);
            return false;
        }

        return true;
    }
}
