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

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ycwl.basic.pricing.dto.PricingFilterRequest;
import com.ycwl.basic.pricing.dto.TierConfigFilterRequest;
import com.ycwl.basic.pricing.entity.PriceProductConfig;
import com.ycwl.basic.pricing.entity.PriceTierConfig;
import com.ycwl.basic.pricing.exception.ProductConfigNotFoundException;
import com.ycwl.basic.pricing.mapper.PriceProductConfigMapper;
import com.ycwl.basic.pricing.mapper.PriceTierConfigMapper;
import com.ycwl.basic.pricing.service.IProductConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * 商品配置管理服务实现
 */
@Slf4j
@Service("pricingProductConfigServiceImpl")
@RequiredArgsConstructor
public class ProductConfigServiceImpl implements IProductConfigService {
    
    private final PriceProductConfigMapper productConfigMapper;
    private final PriceTierConfigMapper tierConfigMapper;
    
    @Override
    public List<PriceProductConfig> getProductConfig(String productType) {
        return productConfigMapper.selectByProductType(productType);
    }
    
    @Override
    public PriceProductConfig getProductConfig(String productType, String productId) {
        PriceProductConfig config = productConfigMapper.selectByProductTypeAndId(productType, productId);
        if (config == null) {
            throw new ProductConfigNotFoundException("商品配置未找到: " + productType + ", productId: " + productId);
        }
        return config;
    }
    
    @Override
    public PriceTierConfig getTierConfig(String productType, String productId, Integer quantity) {
        if (quantity == null || quantity <= 0) {
            return null;
        }
        PriceTierConfig config = tierConfigMapper.selectByProductTypeAndQuantity(productType, productId, quantity);
//        不使用default配置，没查到就算了
//        // 如果没有找到特定商品的阶梯配置，尝试使用default配置
//        if (config == null && !"default".equals(productId)) {
//            log.warn("阶梯定价配置未找到: productType={}, productId={}, quantity={}, 尝试使用default配置",
//                    productType, productId, quantity);
//            config = tierConfigMapper.selectByProductTypeAndQuantity(productType, "default", quantity);
//            if (config != null) {
//                log.debug("使用default阶梯配置: productType={}, quantity={}, price={}",
//                        productType, quantity, config.getPrice());
//            }
//        }
//
        if (config == null) {
            return null;
        }
        log.warn("阶梯定价: productType={}, productId={}, quantity={}，config={}",
                productType, productId, quantity, config);
        return config;
    }

    @Override
    public PriceProductConfig getProductConfig(String productType, String productId, Long scenicId) {
        if (scenicId == null) {
            // 如果没有景区ID，使用原有逻辑
            return getProductConfig(productType, productId);
        }

        String scenicIdStr = scenicId.toString();

        // 查询优先级：
        // 1. 景区+商品ID
        PriceProductConfig config = productConfigMapper.selectByProductTypeIdAndScenic(
                productType, productId, scenicIdStr);
        if (config != null) {
            log.debug("使用景区特定商品配置: productType={}, productId={}, scenicId={}",
                    productType, productId, scenicId);
            return config;
        }

        // 2. 景区+景区ID作为商品ID（productId未命中时回退）
        if (!scenicIdStr.equals(productId)) {
            config = productConfigMapper.selectByProductTypeIdAndScenic(
                    productType, scenicIdStr, scenicIdStr);
            if (config != null) {
                log.debug("使用景区ID作为商品ID的配置: productType={}, scenicId={}", productType, scenicId);
                return config;
            }
        }

        // 3. 景区+默认
        if (!"default".equals(productId)) {
            config = productConfigMapper.selectByProductTypeIdAndScenic(
                    productType, "default", scenicIdStr);
            if (config != null) {
                log.debug("使用景区默认配置: productType={}, scenicId={}", productType, scenicId);
                return config;
            }
        }

        // 4. 全局+商品ID (兜底)
        try {
            config = productConfigMapper.selectGlobalByProductTypeAndId(productType, productId);
            if (config != null) {
                log.debug("使用全局商品配置: productType={}, productId={}", productType, productId);
                return config;
            }
        } catch (Exception e) {
            log.debug("全局商品配置未找到: productType={}, productId={}", productType, productId);
        }

        // 5. 全局+默认 (最后兜底)
        config = productConfigMapper.selectGlobalByProductTypeAndId(productType, "default");
        if (config != null) {
            log.debug("使用全局默认配置: productType={}", productType);
            return config;
        }

        throw new ProductConfigNotFoundException(
                String.format("商品配置未找到: productType=%s, productId=%s, scenicId=%s",
                        productType, productId, scenicId));
    }

    @Override
    public PriceTierConfig getTierConfig(String productType, String productId, Integer quantity, Long scenicId) {
        if (quantity == null || quantity <= 0) {
            return null;
        }

        if (scenicId == null) {
            // 如果没有景区ID，使用原有逻辑
            return getTierConfig(productType, productId, quantity);
        }

        String scenicIdStr = scenicId.toString();

        // 查询优先级：
        // 1. 景区+商品ID
        PriceTierConfig config = tierConfigMapper.selectByProductTypeQuantityAndScenic(
                productType, productId, quantity, scenicIdStr);
        if (config != null) {
            log.debug("使用景区特定阶梯定价: productType={}, productId={}, quantity={}, scenicId={}",
                    productType, productId, quantity, scenicId);
            return config;
        }

        // 2. 景区+景区ID作为商品ID（productId未命中时回退）
        if (!scenicIdStr.equals(productId)) {
            config = tierConfigMapper.selectByProductTypeQuantityAndScenic(
                    productType, scenicIdStr, quantity, scenicIdStr);
            if (config != null) {
                log.debug("使用景区ID作为商品ID的阶梯定价: productType={}, quantity={}, scenicId={}",
                        productType, quantity, scenicId);
                return config;
            }
        }

        // 3. 景区+默认
        if (!"default".equals(productId)) {
            config = tierConfigMapper.selectByProductTypeQuantityAndScenic(
                    productType, "default", quantity, scenicIdStr);
            if (config != null) {
                log.debug("使用景区默认阶梯定价: productType={}, quantity={}, scenicId={}",
                        productType, quantity, scenicId);
                return config;
            }
        }

        // 4. 全局+商品ID (兜底)
        config = tierConfigMapper.selectGlobalByProductTypeAndQuantity(productType, productId, quantity);
        if (config != null) {
            log.debug("使用全局阶梯定价: productType={}, productId={}, quantity={}",
                    productType, productId, quantity);
            return config;
        }

        // 5. 全局+默认 (最后兜底)
        config = tierConfigMapper.selectGlobalByProductTypeAndQuantity(productType, "default", quantity);
        if (config != null) {
            log.debug("使用全局默认阶梯定价: productType={}, quantity={}", productType, quantity);
        }

        return config;
    }
    
    @Override
    public List<PriceProductConfig> getActiveProductConfigs() {
        return productConfigMapper.selectActiveConfigs();
    }
    
    @Override
    public List<PriceProductConfig> getAllProductConfigs() {
        return productConfigMapper.selectActiveConfigs();
    }
    
    @Override
    public List<PriceTierConfig> getTierConfigs(String productType) {
        return tierConfigMapper.selectByProductType(productType);
    }
    
    @Override
    public List<PriceTierConfig> getTierConfigs(String productType, String productId) {
        return tierConfigMapper.selectByProductTypeAndId(productType, productId);
    }
    
    @Override
    public List<PriceTierConfig> getAllTierConfigs() {
        return tierConfigMapper.selectAllActiveConfigs();
    }
    
    // ==================== 管理端接口（包含禁用的配置） ====================
    
    @Override
    public List<PriceProductConfig> getAllProductConfigsForAdmin() {
        return productConfigMapper.selectAllConfigsForAdmin();
    }
    
    @Override
    public List<PriceTierConfig> getAllTierConfigsForAdmin() {
        return tierConfigMapper.selectAllConfigsForAdmin();
    }
    
    @Override
    public List<PriceTierConfig> getTierConfigsForAdmin(String productType) {
        return tierConfigMapper.selectByProductTypeForAdmin(productType);
    }
    
    @Override
    public List<PriceTierConfig> getTierConfigsForAdmin(String productType, String productId) {
        return tierConfigMapper.selectByProductTypeAndIdForAdmin(productType, productId);
    }
    
    @Override
    public PageInfo<PriceProductConfig> pageProductConfigsForAdmin(PricingFilterRequest request) {
        // 开启分页
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        
        // 构建查询条件
        QueryWrapper<PriceProductConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0); // 未删除的记录
        
        // 添加筛选条件
        if (StringUtils.hasText(request.getScenicId())) {
            queryWrapper.eq("scenic_id", request.getScenicId());
        }
        if (request.getProductType() != null) {
            queryWrapper.eq("product_type", request.getProductType().getCode());
        }
        if (request.getIsActive() != null) {
            queryWrapper.eq("is_active", request.getIsActive());
        }
        
        // 按创建时间降序排列
        queryWrapper.orderByDesc("create_time");
        
        // 执行查询
        List<PriceProductConfig> list = productConfigMapper.selectList(queryWrapper);
        
        // 返回分页结果
        return new PageInfo<>(list);
    }
    
    @Override
    public PageInfo<PriceTierConfig> pageTierConfigsForAdmin(TierConfigFilterRequest request) {
        // 开启分页
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        
        // 构建查询条件
        QueryWrapper<PriceTierConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0); // 未删除的记录
        
        // 添加筛选条件
        if (StringUtils.hasText(request.getScenicId())) {
            queryWrapper.eq("scenic_id", request.getScenicId());
        }
        if (request.getProductType() != null) {
            queryWrapper.eq("product_type", request.getProductType().getCode());
        }
        if (StringUtils.hasText(request.getProductId())) {
            queryWrapper.eq("product_id", request.getProductId());
        }
        if (request.getIsActive() != null) {
            queryWrapper.eq("is_active", request.getIsActive());
        }
        
        // 按排序字段升序，再按创建时间降序排列
        queryWrapper.orderByAsc("sort_order").orderByDesc("create_time");
        
        // 执行查询
        List<PriceTierConfig> list = tierConfigMapper.selectList(queryWrapper);
        
        // 返回分页结果
        return new PageInfo<>(list);
    }
}