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

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ycwl.basic.pricing.dto.BundleConfigFilterRequest;
import com.ycwl.basic.pricing.dto.BundleProductItem;
import com.ycwl.basic.pricing.dto.ProductItem;
import com.ycwl.basic.pricing.entity.PriceBundleConfig;
import com.ycwl.basic.pricing.enums.ProductType;
import com.ycwl.basic.pricing.mapper.PriceBundleConfigMapper;
import com.ycwl.basic.pricing.service.IPriceBundleService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 一口价套餐服务实现
 */
@Slf4j
@Service("pricingBundleServiceImpl")
@RequiredArgsConstructor
public class PriceBundleServiceImpl implements IPriceBundleService {
    
    private final PriceBundleConfigMapper bundleConfigMapper;
    private final ObjectMapper objectMapper;
    
    @Override
    public boolean isBundleApplicable(List<ProductItem> products) {
        List<PriceBundleConfig> bundles = getActiveBundles();
        if (bundles.isEmpty()) {
            return false;
        }
        
        Set<String> productTypes = new HashSet<>();
        for (ProductItem product : products) {
            productTypes.add(product.getProductType().getCode());
        }
        
        for (PriceBundleConfig bundle : bundles) {
            if (isProductsMatchBundle(productTypes, bundle)) {
                return true;
            }
        }
        
        return false;
    }
    
    @Override
    public BigDecimal getBundlePrice(List<ProductItem> products) {
        if (!isBundleApplicable(products)) {
            return null;
        }
        
        List<PriceBundleConfig> bundles = getActiveBundles();
        Set<String> productTypes = new HashSet<>();
        for (ProductItem product : products) {
            productTypes.add(product.getProductType().getCode());
        }
        
        for (PriceBundleConfig bundle : bundles) {
            if (isProductsMatchBundle(productTypes, bundle)) {
                return bundle.getBundlePrice();
            }
        }
        
        return null;
    }
    
    @Override
    public PriceBundleConfig getBundleConfig(List<ProductItem> products) {
        if (!isBundleApplicable(products)) {
            return null;
        }
        
        List<PriceBundleConfig> bundles = getActiveBundles();
        Set<String> productTypes = new HashSet<>();
        for (ProductItem product : products) {
            productTypes.add(product.getProductType().getCode());
        }
        
        for (PriceBundleConfig bundle : bundles) {
            if (isProductsMatchBundle(productTypes, bundle)) {
                return bundle;
            }
        }
        
        return null;
    }
    
    @Override
    public List<PriceBundleConfig> getActiveBundles() {
        return bundleConfigMapper.selectActiveBundles();
    }
    
    @Override
    public List<PriceBundleConfig> getAllBundles() {
        return bundleConfigMapper.selectActiveBundles();
    }
    
    // ==================== 管理端接口（包含禁用的配置） ====================
    
    @Override
    public List<PriceBundleConfig> getAllBundlesForAdmin() {
        return bundleConfigMapper.selectAllBundlesForAdmin();
    }
    
    @Override
    public PageInfo<PriceBundleConfig> pageBundleConfigsForAdmin(BundleConfigFilterRequest request) {
        // 开启分页
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        
        // 构建查询条件
        QueryWrapper<PriceBundleConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("deleted", 0); // 未删除的记录
        
        // 添加筛选条件
        if (StringUtils.hasText(request.getScenicId())) {
            queryWrapper.eq("scenic_id", request.getScenicId());
        }
        if (StringUtils.hasText(request.getBundleName())) {
            queryWrapper.like("bundle_name", request.getBundleName()); // 模糊查询
        }
        if (request.getIsActive() != null) {
            queryWrapper.eq("is_active", request.getIsActive());
        }
        
        // 按创建时间降序排列
        queryWrapper.orderByDesc("create_time");
        
        // 执行查询
        List<PriceBundleConfig> list = bundleConfigMapper.selectList(queryWrapper);
        
        // 返回分页结果
        return new PageInfo<>(list);
    }
    
    private boolean isProductsMatchBundle(Set<String> productTypes, PriceBundleConfig bundle) {
        try {
            // 检查包含的商品
            if (bundle.getIncludedProducts() != null && !bundle.getIncludedProducts().isEmpty()) {
                Set<String> requiredProducts = new HashSet<>();
                for (BundleProductItem item : bundle.getIncludedProducts()) {
                    requiredProducts.add(item.getType());
                }
                if (!productTypes.containsAll(requiredProducts)) {
                    return false;
                }
            }
            
            // 检查排除的商品
            if (bundle.getExcludedProducts() != null && !bundle.getExcludedProducts().isEmpty()) {
                for (BundleProductItem item : bundle.getExcludedProducts()) {
                    if (productTypes.contains(item.getType())) {
                        return false;
                    }
                }
            }
            
            return true;
            
        } catch (Exception e) {
            log.error("解析一口价配置失败: bundleId={}", bundle.getId(), e);
            return false;
        }
    }
}