package com.ylx.massage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ylx.massage.domain.*;
import com.ylx.massage.domain.dto.*;
import com.ylx.massage.domain.vo.H5ProductVo;
import com.ylx.massage.domain.vo.PlatformProductStats;
import com.ylx.massage.domain.vo.ProductSalesStats;
import com.ylx.massage.domain.vo.SpecComboVO;
import com.ylx.massage.mapper.*;
import com.ylx.massage.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * 商品表(Product)表服务实现类
 *
 * @author ylx
 * @since 2026-03-26
 */
@Slf4j
@Service("productService")
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {

    @Resource
    private ProductCategoryMapper productCategoryMapper;

    @Resource
    private ProductSpecMapper productSpecMapper;

    @Resource
    private ProductSpecValueMapper productSpecValueMapper;

    @Resource
    private ProductSkuMapper productSkuMapper;

    @Resource
    private ProductMapper productMapper;

    @Resource
    private ProductOrderItemMapper productOrderItemMapper;

    /**
     * 新增商品
     *
     * @param dto 新增商品请求DTO
     * @return Long 商品ID
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createProduct(ProductCreateDTO dto) {
        // 1. 校验分类是否存在
        ProductCategory category = productCategoryMapper.selectById(dto.getCategoryId());
        if (category == null) {
            throw new RuntimeException("商品分类不存在");
        }

        // 校验规格列表是否为空
        if (CollectionUtils.isEmpty(dto.getSpecList())) {
            throw new RuntimeException("商品规格不能为空");
        }

        // 校验SKU列表是否为空
        if (CollectionUtils.isEmpty(dto.getSkuList())) {
            throw new RuntimeException("商品SKU不能为空");
        }

        // 2. 保存商品基本信息
        Product product = new Product();
        product.setCategoryId(dto.getCategoryId());
        product.setProductNo(dto.getProductNo());
        product.setName(dto.getName());
        product.setProductMainImage(dto.getProductMainImage());
        product.setProductImage(dto.getProductImage());
        product.setSummary(dto.getSummary());
        product.setDetail(dto.getDetail());
        product.setFreight(dto.getFreight());
        product.setDeliveryTime(dto.getDeliveryTime());
        product.setServicePromise(dto.getServicePromise());
        product.setSaleStartTime(dto.getSaleStartTime());
        product.setSaleEndTime(dto.getSaleEndTime());
        //判断付款方式
        Integer paymentType = dto.getPaymentType();
        List<ProductSkuDTO> skuList = dto.getSkuList();
        switch (paymentType) {
            // 积分支付
            case 1:
                Integer pricePoint = skuList.get(0).getPricePoint();
                //积分价格不能为空
                if (pricePoint == null) {
                    throw new RuntimeException("积分价格不能为空");
                }
                break;
            // 金额支付
            case 2:
                BigDecimal priceMoney = skuList.get(0).getPriceMoney();
                //金额价格不能为空
                if (priceMoney == null) {
                    throw new RuntimeException("金额价格不能为空");
                }
                break;
            // 积分+金额支付
            case 3:
                Integer pricePoint1 = skuList.get(0).getPricePoint();
                BigDecimal priceMoney1 = skuList.get(0).getPriceMoney();
                //积分价格不能为空
                if (pricePoint1 == null) {
                    throw new RuntimeException("积分价格不能为空");
                }
                //金额价格不能为空
                if (priceMoney1 == null) {
                    throw new RuntimeException("金额价格不能为空");
                }
                break;
            default:
                throw new RuntimeException("付款方式错误");
        }
        // 设置付款方式
        product.setPaymentType(paymentType);
        // 设置积分价格
        product.setPricePoint(skuList.get(0).getPricePoint());
        // 设置现金价格
        product.setPriceMoney(skuList.get(0).getPriceMoney());
        product.setStatus(0); // 默认下架
        product.setSales(0); // 初始销量为0
        product.setDeleted(0); // 未删除
        // 计算总库存
        if (!CollectionUtils.isEmpty(dto.getSkuList())) {
            int totalStock = dto.getSkuList().stream().mapToInt(ProductSkuDTO::getStock).sum();
            product.setStock(totalStock);
        }

        this.save(product);
        Long productId = product.getId();

        // 3. 保存规格和SKU
        saveProductSpecsAndSkus(productId, dto);
        log.info("商品创建成功，商品ID：{}，商品编号：{}", productId, dto.getProductNo());
        return productId;
    }

    /**
     * 修改商品
     *
     * @param dto 修改商品请求DTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateProduct(ProductUpdateDTO dto) {
        // 1. 校验商品是否存在
        Product product = this.getById(dto.getId());
        if (product == null) {
            throw new RuntimeException("商品不存在");
        }
        // 2. 校验分类是否存在
        ProductCategory category = productCategoryMapper.selectById(dto.getCategoryId());
        if (category == null) {
            throw new RuntimeException("商品分类不存在");
        }
        // 3. 校验规格列表是否为空
        if (CollectionUtils.isEmpty(dto.getSpecList())) {
            throw new RuntimeException("商品规格不能为空");
        }
        // 4. 校验SKU列表是否为空
        if (CollectionUtils.isEmpty(dto.getSkuList())) {
            throw new RuntimeException("商品SKU不能为空");
        }

        //更新商品的信息
        product.setCategoryId(dto.getCategoryId());
        product.setName(dto.getName());
        product.setProductMainImage(dto.getProductMainImage());
        product.setProductImage(dto.getProductImage());
        product.setSummary(dto.getSummary());
        product.setDetail(dto.getDetail());
        product.setPaymentType(dto.getPaymentType());
        product.setFreight(dto.getFreight());
        product.setDeliveryTime(dto.getDeliveryTime());
        product.setServicePromise(dto.getServicePromise());
        product.setSaleStartTime(dto.getSaleStartTime());
        product.setSaleEndTime(dto.getSaleEndTime());
        this.updateById(product);
        //更新规格
        updateProductSpecs(product.getId(), dto.getSpecList());
        //更新SKU
        updateProductSkus(product.getId(), dto.getSkuList());
    }

    /**
     * 更新商品规格
     *
     * @param productId 商品ID
     * @param specList  商品规格列表
     */
    public void updateProductSpecs(Long productId, List<ProductSpecDTO> specList) {
        //删除商品规格
        productSpecMapper.delete(new LambdaQueryWrapper<ProductSpec>().eq(ProductSpec::getProductId, productId));
        //删除商品规格值
        productSpecValueMapper.delete(new LambdaQueryWrapper<ProductSpecValue>().eq(ProductSpecValue::getProductId, productId));
        //根据商品ID查询商品编号
        Product product = this.getById(productId);

        //添加商品规格
        for (ProductSpecDTO spec : specList) {
            ProductSpec productSpec = new ProductSpec();
            productSpec.setProductId(productId);
            productSpec.setSpecName(spec.getSpecName());
            productSpec.setSort(spec.getSort());
            productSpec.setProductNo(product.getProductNo());
            productSpecMapper.insert(productSpec);
            //添加商品规格值
            for (ProductSpecValueDTO value : spec.getSpecValues()) {
                ProductSpecValue productSpecValue = new ProductSpecValue();
                productSpecValue.setSpecId(productSpec.getId());
                productSpecValue.setProductId(productId);
                productSpecValue.setProductNo(product.getProductNo());
                productSpecValue.setSpecValue(value.getSpecValue());
                productSpecValue.setSort(value.getSort());
                productSpecValueMapper.insert(productSpecValue);
            }
        }
        /*for (ProductSpecDTO spec : specList) {
            ProductSpec productSpec = new ProductSpec();
            productSpec.setSpecName(spec.getSpecName());
            productSpec.setSort(spec.getSort());
            productSpecMapper.update(productSpec, new LambdaUpdateWrapper<ProductSpec>().eq(ProductSpec::getProductId, productId));

            // 更新商品规格值
            for (ProductSpecValueDTO value : spec.getSpecValues()) {
                ProductSpecValue productSpecValue = new ProductSpecValue();
                productSpecValue.setSpecValue(value.getSpecValue());
                productSpecValue.setSort(value.getSort());
                productSpecValueMapper.update(productSpecValue, new LambdaUpdateWrapper<ProductSpecValue>().eq(ProductSpecValue::getProductId, productId));
            }
        }*/
    }

    /**
     * 更新商品SKU
     */
    public void updateProductSkus(Long productId, List<ProductSkuDTO> skuList) {
        //删除商品SKU
        productSkuMapper.delete(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, productId));
        //添加商品SKU
        for (ProductSkuDTO sku : skuList) {
            ProductSku productSku = new ProductSku();
            productSku.setProductId(productId);
            productSku.setSkuNo(generateSkuNo(productId));
            productSku.setSpecCombo(sku.getSpecCombo());
            productSku.setImage(sku.getImage());
            productSku.setPriceMoney(sku.getPriceMoney());
            productSku.setPricePoint(sku.getPricePoint());
            productSku.setOriginPrice(sku.getOriginPrice());
            productSku.setStock(sku.getStock());
            productSkuMapper.insert(productSku);
        }
    }

    /**
     * 生成商品编号
     * 规则：分类编码 + 当前日期(yyyyMMdd) + 序列号(3位)
     * 示例：AD20260327001
     *
     * @param categoryId 分类ID
     * @return String 生成的商品编号
     */
    @Override
    public String generateProductNo(Long categoryId) {
        // 1. 根据分类ID获取分类信息
        ProductCategory category = productCategoryMapper.selectById(categoryId);
        if (category == null) {
            throw new RuntimeException("商品分类不存在");
        }

        // 2. 获取分类编码
        String categoryCode = category.getCode();
        if (categoryCode == null || categoryCode.trim().isEmpty()) {
            throw new RuntimeException("商品分类编码不存在");
        }
        // 3. 生成商品编号
        return generateProductNoByCategoryCode(categoryCode);
    }


    /**
     * 分页查询商品列表(H5端)-支持排序
     *
     * @param page      分页参数
     * @param product   商品查询参数
     * @param sortField 排序字段（price:价格, sales:销量, comprehensive:综合排序）
     * @param sortOrder 排序方式（asc:升序, desc:降序）
     * @return Page<Product> 分页结果
     */
    @Override
    public Page<H5ProductVo> selectH5Page(Page<H5ProductVo> page, Product product, String name, String sortField, String sortOrder) {
        // 综合排序，需要在Java层计算得分
        if ("comprehensive".equals(sortField)) {
            return selectH5PageWithComprehensiveSort(page, product, name, sortOrder);
        }
        return productMapper.selectH5Page(page, product, name, sortField, sortOrder);
    }

    /**
     * 综合排序查询（H5端）
     * 综合得分 = 0.5 * 销量热度 + 0.3 * 新品系数 + 0.2 * 积分性价比
     *
     * @param page      分页参数
     * @param product   商品查询参数
     * @param name      商品名称
     * @param sortOrder 排序方式（综合排序固定降序）
     * @return Page<H5ProductVo> 分页结果
     */
    private Page<H5ProductVo> selectH5PageWithComprehensiveSort(Page<H5ProductVo> page, Product product, String name, String sortOrder) {
        // 1. 查询近30天各商品销量统计（从订单表）
        List<ProductSalesStats> salesStatsList = productOrderItemMapper.selectLast30DaysSalesStats();
        // 转换为Map：productId -> last30DaysSales
        Map<Long, Long> productSalesMap = salesStatsList.stream()
                .collect(Collectors.toMap(ProductSalesStats::getProductId, ProductSalesStats::getLast30DaysSales, (v1, v2) -> v1));

        // 2. 计算平台近30天总销量
        long totalSales = productSalesMap.values().stream().mapToLong(Long::longValue).sum();

        // 3. 为了支持分页+排序，先查询所有匹配商品（不分页，按综合得分排序后取分页数据）
        Page<H5ProductVo> allDataPage = new Page<>(1, Integer.MAX_VALUE);
        Page<H5ProductVo> allProductsPage = productMapper.selectH5Page(allDataPage, product, name, null, null);

        List<H5ProductVo> allProducts = allProductsPage.getRecords();
        if (allProducts.isEmpty()) {
            return new Page<>(page.getCurrent(), page.getSize());
        }

        // 4. 计算每个商品的综合得分并排序
        List<H5ProductVo> sortedProducts = allProducts.stream()
                .peek(vo -> {
                    // 使用近30天订单销量计算综合得分
                    long last30DaysSales = productSalesMap.getOrDefault(vo.getId(), 0L);
                    BigDecimal comprehensiveScore = calculateComprehensiveScore(last30DaysSales, vo, totalSales);
                    vo.setComprehensiveScore(comprehensiveScore);
                })
                .sorted((p1, p2) -> {
                    // 综合排序：得分高的在前
                    int cmp = p2.getComprehensiveScore().compareTo(p1.getComprehensiveScore());
                    if (cmp != 0) {
                        return cmp;
                    }
                    // 得分相同时，按近30天销量降序作为二级排序
                    Long sales1 = productSalesMap.getOrDefault(p1.getId(), 0L);
                    Long sales2 = productSalesMap.getOrDefault(p2.getId(), 0L);
                    return sales2.compareTo(sales1);
                })
                .collect(Collectors.toList());

        // 5. 计算分页位置并返回
        long current = page.getCurrent();
        long size = page.getSize();
        long fromIndex = (current - 1) * size;
        long toIndex = Math.min(fromIndex + size, sortedProducts.size());

        List<H5ProductVo> pageData = fromIndex < sortedProducts.size()
                ? sortedProducts.subList((int) fromIndex, (int) toIndex)
                : Collections.emptyList();

        Page<H5ProductVo> resultPage = new Page<>(current, size);
        resultPage.setRecords(pageData);
        resultPage.setTotal(sortedProducts.size());
        return resultPage;
    }

    /**
     * 计算商品综合排序得分
     * 综合得分 = 0.5 * 销量热度得分 + 0.3 * 新品系数得分 + 0.2 * 积分性价比得分
     *
     * @param last30DaysSales 商品近30天销量
     * @param vo              商品VO
     * @param totalSales      平台近30天总销量
     * @return BigDecimal 综合得分
     */
    private BigDecimal calculateComprehensiveScore(long last30DaysSales, H5ProductVo vo, long totalSales) {
        // 1. 销量热度得分 (50%权重)
        // 公式：min(1, 当前商品近30天销量 / 平台近30天总销量)
        BigDecimal salesScore = BigDecimal.ZERO;
        if (totalSales > 0) {
            double salesRatio = (double) last30DaysSales / totalSales;
            salesScore = BigDecimal.valueOf(Math.min(1.0, salesRatio));
        }

        // 2. 新品系数得分 (30%权重)
        // 公式：上架前7天=1.0，后续递减 max(0, 1 - (上架天数-7)/23)
        BigDecimal newProductScore = calculateNewProductScore(vo.getSaleStartTime());

        // 3. 积分性价比得分 (20%权重)
        // 公式：积分值 / 商品价值
        BigDecimal pointValueScore = calculatePointValueScore(vo);

        // 综合得分 = 0.5 * 销量热度 + 0.3 * 新品系数 + 0.2 * 积分性价比
        BigDecimal comprehensiveScore = salesScore.multiply(BigDecimal.valueOf(0.5))
                .add(newProductScore.multiply(BigDecimal.valueOf(0.3)))
                .add(pointValueScore.multiply(BigDecimal.valueOf(0.2)));

        // 保留2位小数
        return comprehensiveScore.setScale(2, RoundingMode.HALF_UP);
    }

    /**
     * 计算新品系数得分
     * 上架前7天系数 = 1.0，后续30天递减，系数 = max(0, 1 - (上架天数-7)/23)
     *
     * @param saleStartTime 上架开始时间
     * @return BigDecimal 新品系数得分
     */
    private BigDecimal calculateNewProductScore(LocalDate saleStartTime) {
        if (saleStartTime == null) {
            return BigDecimal.ZERO;
        }

        LocalDate today = LocalDate.now();
        long daysOnSale = ChronoUnit.DAYS.between(saleStartTime, today);

        if (daysOnSale < 0) {
            // 上架时间是未来时间，视为未上架，得分为0
            return BigDecimal.ZERO;
        } else if (daysOnSale <= 7) {
            // 上架前7天，系数为1.0
            return BigDecimal.ONE;
        } else {
            // 第7天起开始递减
            double coefficient = Math.max(0, 1 - (daysOnSale - 7) / 23.0);
            return BigDecimal.valueOf(coefficient);
        }
    }

    /**
     * 计算积分性价比得分
     * 积分值/商品价值，积分值越高、商品价值越低，得分越高
     *
     * @param vo 商品VO
     * @return BigDecimal 积分性价比得分
     */
    private BigDecimal calculatePointValueScore(H5ProductVo vo) {
        Integer pricePoint = vo.getPricePoint();
        BigDecimal originalPrice = vo.getOriginalPrice();

        if (pricePoint == null || pricePoint <= 0) {
            return BigDecimal.ZERO;
        }

        // 如果商品价值（原价值）为空或为0，使用积分价格作为参考（得分较低）
        if (originalPrice == null || originalPrice.compareTo(BigDecimal.ZERO) <= 0) {
            // 积分价格越高，得分越高（但最高不超过0.5）
            // 这里使用一个经验公式：积分价格的对数归一化
            double normalizedScore = Math.min(0.5, Math.log10(pricePoint + 1) / 4.0);
            return BigDecimal.valueOf(normalizedScore);
        }

        // 积分性价比 = 积分值 / 商品价值
        // 为了避免得分过高，使用 min(积分性价比, 1.0) 限制最高为1
        double ratio = (double) pricePoint / originalPrice.doubleValue();
        return BigDecimal.valueOf(Math.min(1.0, ratio));
    }

    /**
     * 根据分类编码生成商品编号
     * 规则：分类编码 + 当前日期(yyyyMMdd) + 序列号(3位)
     *
     * @param categoryCode 分类编码
     * @return String 生成的商品编号
     */
    private String generateProductNoByCategoryCode(String categoryCode) {
        String dateStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String prefix = categoryCode.toUpperCase();

        // 查询当天该分类下最大编号
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.likeRight(Product::getProductNo, prefix + dateStr).orderByDesc(Product::getProductNo).last("LIMIT 1");
        Product lastProduct = this.getOne(wrapper);

        int seq = 1;
        if (lastProduct != null && lastProduct.getProductNo() != null) {
            String lastNo = lastProduct.getProductNo();
            // 从编号中提取序列号（最后3位）
            String seqStr = lastNo.substring(lastNo.length() - 3);
            try {
                seq = Integer.parseInt(seqStr) + 1;
            } catch (NumberFormatException e) {
                log.warn("解析商品编号序列号失败：{}", lastNo);
                seq = 1;
            }
        }
        return prefix + dateStr + String.format("%03d", seq);
    }

    /**
     * 保存商品图片
     *
     * @param productId 商品ID
     * @param imageUrls 图片URL列表
     */
    private void saveProductImages(Long productId, List<String> imageUrls) {
        if (CollectionUtils.isEmpty(imageUrls)) {
            return;
        }
    }

    /**
     * 保存商品规格和SKU
     *
     * @param productId 商品ID
     * @param dto       商品创建DTO
     */
    private void saveProductSpecsAndSkus(Long productId, ProductCreateDTO dto) {
        //根据商品编号更新规格表中的商品ID
        ProductSpec productSpec = new ProductSpec();
        productSpec.setProductId(productId);
        int update = productSpecMapper.update(productSpec, new LambdaQueryWrapper<ProductSpec>().eq(ProductSpec::getProductNo, dto.getProductNo()));
        if (update == 0) {
            throw new RuntimeException("商品规格更新失败");
        }

        //根据商品编号更新规格值表中的商品ID
        ProductSpecValue productSpecValue = new ProductSpecValue();
        productSpecValue.setProductId(productId);
        int update1 = productSpecValueMapper.update(productSpecValue, new LambdaQueryWrapper<ProductSpecValue>().eq(ProductSpecValue::getProductNo, dto.getProductNo()));
        if (update1 == 0) {
            throw new RuntimeException("商品规格值更新失败");
        }

        // 保存规格名和规格值
        AtomicInteger specIndex = new AtomicInteger(0);
        /*for (ProductSpecDTO specDTO : specList) {
            // 保存规格名
            ProductSpec spec = new ProductSpec();
            spec.setProductId(productId);
            spec.setProductNo(dto.getProductNo());
            spec.setSpecName(specDTO.getSpecName());
            spec.setSort(specDTO.getSort() != null ? specDTO.getSort() : specIndex.get() + 1);
            // 插入product_spec表
            productSpecMapper.insert(spec);
            Long specId = spec.getId();

            // 保存规格值
            if (!CollectionUtils.isEmpty(specDTO.getSpecValues())) {
                AtomicInteger valueIndex = new AtomicInteger(0);
                for (ProductSpecValueDTO valueDTO : specDTO.getSpecValues()) {
                    ProductSpecValue specValue = new ProductSpecValue();
                    specValue.setSpecId(specId);
                    specValue.setProductId(productId);
                    specValue.setProductNo(dto.getProductNo());
                    specValue.setSpecValue(valueDTO.getSpecValue());
                    specValue.setSort(valueDTO.getSort() != null ? valueDTO.getSort() : valueIndex.get() + 1);
                    // 插入product_spec_value表
                    productSpecValueMapper.insert(specValue);
                    valueIndex.getAndIncrement();
                }
            }
            specIndex.getAndIncrement();
        }*/
        List<ProductSkuDTO> skuList = dto.getSkuList();
        // 保存SKU
        for (ProductSkuDTO skuDTO : skuList) {
            ProductSku sku = new ProductSku();
            sku.setProductId(productId);
            sku.setSkuNo(generateSkuNo(productId));
            sku.setSpecCombo(skuDTO.getSpecCombo());
            sku.setImage(skuDTO.getImage());
            sku.setPriceMoney(skuDTO.getPriceMoney());
            sku.setPricePoint(skuDTO.getPricePoint());
            sku.setOriginPrice(skuDTO.getOriginPrice());
            sku.setStock(skuDTO.getStock());
            sku.setSales(0);
            sku.setStatus(1);
            productSkuMapper.insert(sku);
        }
    }

    /**
     * 生成SKU编号
     *
     * @param productId 商品ID
     * @return 生成的SKU编号
     */
    private String generateSkuNo(Long productId) {
        return "SKU" + productId + System.currentTimeMillis();
    }

    /**
     * 新增商品规格
     *
     * @param dto 规格设置请求DTO
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void setupSpec(ProductSpecSetupDTO dto) {
        if (StringUtils.isBlank(dto.getProductNo())) {
            throw new RuntimeException("商品编号不能为空");
        }
        //删除商品规格
        productSpecMapper.delete(new LambdaQueryWrapper<ProductSpec>().eq(ProductSpec::getProductNo, dto.getProductNo()));
        //删除商品规格值
        productSpecValueMapper.delete(new LambdaQueryWrapper<ProductSpecValue>().eq(ProductSpecValue::getProductNo, dto.getProductNo()));

        // 保存新的规格
        if (!CollectionUtils.isEmpty(dto.getSpecList())) {
            AtomicInteger specIndex = new AtomicInteger(0);
            for (ProductSpecSetupDTO.SpecItemDTO specItem : dto.getSpecList()) {
                // 根据商品编号检查规格名是否存在，如果存在，则直接通过，不插入
                LambdaQueryWrapper<ProductSpec> specWrapper = new LambdaQueryWrapper<>();
                specWrapper.eq(ProductSpec::getProductNo, dto.getProductNo()).eq(ProductSpec::getSpecName, specItem.getSpecName());
                ProductSpec existingSpec = productSpecMapper.selectOne(specWrapper);
                if (existingSpec != null) {
                    continue;
                }
                // 保存规格名
                ProductSpec spec = new ProductSpec();
                spec.setProductNo(dto.getProductNo());
                spec.setSpecName(specItem.getSpecName());
                spec.setSort(specItem.getSort() != null ? specItem.getSort() : specIndex.get() + 1);
                productSpecMapper.insert(spec);
                Long specId = spec.getId();

                // 保存规格值
                if (!CollectionUtils.isEmpty(specItem.getSpecValues())) {
                    AtomicInteger valueIndex = new AtomicInteger(0);
                    for (ProductSpecSetupDTO.SpecValueItemDTO valueItem : specItem.getSpecValues()) {
                        ProductSpecValue specValue = new ProductSpecValue();
                        specValue.setSpecId(specId);
                        specValue.setProductNo(dto.getProductNo());
                        specValue.setSpecValue(valueItem.getSpecValue());
                        specValue.setSort(valueItem.getSort() != null ? valueItem.getSort() : valueIndex.get() + 1);
                        productSpecValueMapper.insert(specValue);
                        valueIndex.getAndIncrement();
                    }
                }
                specIndex.getAndIncrement();
            }
        }
    }

    /**
     * 获取商品规格组合
     *
     * @param productNo 商品编号
     * @return List<SpecComboVO> 规格组合列表
     */
    @Override
    public List<SpecComboVO> getSpecCombinations(String productNo) {
        // 根据商品编号查询商品的所有规格名
        LambdaQueryWrapper<ProductSpec> specWrapper = new LambdaQueryWrapper<>();
        specWrapper.eq(ProductSpec::getProductNo, productNo).orderByAsc(ProductSpec::getSort);
        List<ProductSpec> specList = productSpecMapper.selectList(specWrapper);

        if (CollectionUtils.isEmpty(specList)) {
            return Collections.emptyList();
        }

        // 获取商品ID
        Long productId = specList.get(0).getProductId();

        // 查询所有规格值
        LambdaQueryWrapper<ProductSpecValue> valueWrapper = new LambdaQueryWrapper<>();
        valueWrapper.eq(ProductSpecValue::getProductNo, productNo).orderByAsc(ProductSpecValue::getSort);
        List<ProductSpecValue> allValues = productSpecValueMapper.selectList(valueWrapper);

        // 按规格ID分组
        Map<Long, List<ProductSpecValue>> valueMap = allValues.stream().collect(Collectors.groupingBy(ProductSpecValue::getSpecId));

        // 构建每个规格的规格值列表
        List<List<SpecComboVO.SpecNameValue>> specValueGroups = new ArrayList<>();
        for (ProductSpec spec : specList) {
            List<ProductSpecValue> values = valueMap.getOrDefault(spec.getId(), Collections.emptyList());
            if (values.isEmpty()) {
                continue;
            }
            List<SpecComboVO.SpecNameValue> nameValueList = new ArrayList<>();
            for (ProductSpecValue value : values) {
                SpecComboVO.SpecNameValue nameValue = new SpecComboVO.SpecNameValue();
                nameValue.setSpecId(spec.getId());
                nameValue.setSpecName(spec.getSpecName());
                nameValue.setSpecValue(value.getSpecValue());
                nameValue.setSort(value.getSort());
                nameValueList.add(nameValue);
            }
            specValueGroups.add(nameValueList);
        }

        // 计算笛卡尔积
        List<List<SpecComboVO.SpecNameValue>> cartesianProduct = cartesianProduct(specValueGroups);
        // 构建返回结果
        List<SpecComboVO> result = new ArrayList<>();
        int index = 1;
        for (List<SpecComboVO.SpecNameValue> combo : cartesianProduct) {
            SpecComboVO vo = new SpecComboVO();
            vo.setIndex(index++);
            List<String> specValues = combo.stream().map(SpecComboVO.SpecNameValue::getSpecValue).collect(Collectors.toList());
            vo.setSpecValues(specValues);

            String join = String.join(",", specValues);
            log.info("规格值文本：{}", join);
            vo.setSpecValueText(join);
            //根据商品ID和规格值查询商品库存
            LambdaQueryWrapper<ProductSku> eq = new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getSpecCombo, join)
                    .eq(ProductSku::getProductId, productId).orderByDesc(ProductSku::getCreateTime).last("limit 1");
            ProductSku sku = productSkuMapper.selectOne(eq);
            if (sku == null) {
                vo.setImage("");
            } else {
                vo.setSkuId(sku.getId());
                vo.setImage(sku.getImage());
                vo.setPriceMoney(sku.getPriceMoney());
                vo.setPricePoint(sku.getPricePoint());
                vo.setOriginPrice(sku.getOriginPrice());
                vo.setStock(sku.getStock());
            }
            vo.setSpecNameValueList(combo);
            result.add(vo);
        }
        return result;
    }

    /**
     * 计算笛卡尔积
     *
     * @param lists 规格值列表列表
     * @return List<List < T>> 笛卡尔积结果
     */
    private <T> List<List<T>> cartesianProduct(List<List<T>> lists) {
        if (lists.isEmpty()) {
            return Collections.emptyList();
        }

        List<List<T>> result = new ArrayList<>();
        result.add(new ArrayList<>());

        for (List<T> list : lists) {
            List<List<T>> temp = new ArrayList<>();
            for (List<T> partial : result) {
                for (T item : list) {
                    List<T> newPartial = new ArrayList<>(partial);
                    newPartial.add(item);
                    temp.add(newPartial);
                }
            }
            result = temp;
        }
        return result;
    }
}
