package cn.iocoder.yudao.module.inspection.service.impl;

import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.inspection.entity.InspectionGoodsSku;
import cn.iocoder.yudao.module.inspection.service.InspectionGoodsSkuService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.iocoder.yudao.util.StringUtils;
import cn.iocoder.yudao.module.inspection.entity.InspectionCategoryTemplate;
import cn.iocoder.yudao.module.inspection.entity.ShopInspectionGoods;
import cn.iocoder.yudao.module.inspection.mapper.ShopInspectionCategoryMapper;
import cn.iocoder.yudao.module.inspection.entity.ShopInspectionCategory;
import cn.iocoder.yudao.module.inspection.service.IInspectionCategoryTemplateService;
import cn.iocoder.yudao.module.inspection.service.IShopInspectionGoodsService;
import cn.iocoder.yudao.module.inspection.service.ShopInspectionCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * (ShopInspectionCategory)表服务实现类
 *
 * @author makejava
 * @since 2023-08-01 19:59:23
 */
@Service("shopInspectionCategoryService")
public class ShopInspectionCategoryServiceImpl extends ServiceImpl<ShopInspectionCategoryMapper, ShopInspectionCategory> implements ShopInspectionCategoryService {

    @Autowired
    private IInspectionCategoryTemplateService templateService;
    @Autowired
    private IShopInspectionGoodsService goodsService;
    @Autowired
    private InspectionGoodsSkuService skuService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveVo(ShopInspectionCategory category) {
        this.save(category);
        List<InspectionCategoryTemplate> templates = category.getTemplates();
        for (InspectionCategoryTemplate template : templates) {
            template.setCategoryId(category.getId());
        }
        templateService.saveBatch(templates);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByIdVo(ShopInspectionCategory category) {
        // 1. 更新分类信息
        this.updateById(category);

        // 2. 删除原有模板 SKU
        templateService.deleteByCategoryId(category.getId());

        // 3. 设置模板的 categoryId
        List<InspectionCategoryTemplate> templates = category.getTemplates();
        LocalDateTime now = LocalDateTime.now();
        for (InspectionCategoryTemplate template : templates) {
            template.setCategoryId(category.getId());
            template.setCreateTime(now);
        }

        // 4. 批量保存模板
        templateService.saveBatch(templates);

        // 5. 查询该分类下所有商品
        List<ShopInspectionGoods> goodsList = goodsService.list(Wrappers.<ShopInspectionGoods>lambdaQuery()
                .eq(ShopInspectionGoods::getGoodsCategoryId, category.getId()));
        if (goodsList.isEmpty()) return;

        // 6. 查询所有商品的现有 SKU
        List<Integer> goodsIds = goodsList.stream().map(ShopInspectionGoods::getId).collect(Collectors.toList());
        List<InspectionGoodsSku> existingSkuList = skuService.list(Wrappers.<InspectionGoodsSku>lambdaQuery()
                .in(InspectionGoodsSku::getGoodsId, goodsIds));

        // 7. 构建“当前应存在”的 SKU key: goodsId + "_" + skuName
        Set<String> currentTemplateKeys = new HashSet<>();
        for (ShopInspectionGoods goods : goodsList) {
            for (InspectionCategoryTemplate template : templates) {
                currentTemplateKeys.add(goods.getId() + "_" + template.getSkuName());
            }
        }

        // 8. 删除多余的 SKU（逻辑删除）
        List<Integer> toDeleteIds = existingSkuList.stream()
                .filter(sku -> !currentTemplateKeys.contains(sku.getGoodsId() + "_" + sku.getSkuName()))
                .map(InspectionGoodsSku::getId)
                .collect(Collectors.toList());

        if (!toDeleteIds.isEmpty()) {
            skuService.update(Wrappers.<InspectionGoodsSku>lambdaUpdate()
                    .in(InspectionGoodsSku::getId, toDeleteIds)
                    .set(InspectionGoodsSku::getDeleted, 1)
                    .set(InspectionGoodsSku::getUpdateTime, now));
        }

        // 9. 分别处理新增和更新
        Map<String, InspectionGoodsSku> existingSkuMap = existingSkuList.stream()
                .collect(Collectors.toMap(sku -> sku.getGoodsId() + "_" + sku.getSkuName(), Function.identity(), (a, b) -> a));

        List<InspectionGoodsSku> toInsert = new ArrayList<>();
        List<InspectionGoodsSku> toUpdate = new ArrayList<>();

        for (ShopInspectionGoods goods : goodsList) {
            for (InspectionCategoryTemplate template : templates) {
                String key = goods.getId() + "_" + template.getSkuName();
                InspectionGoodsSku exist = existingSkuMap.get(key);
                if (exist == null) {
                    // 新增
                    InspectionGoodsSku newSku = new InspectionGoodsSku();
                    newSku.setGoodsId(goods.getId().intValue());
                    newSku.setSkuName(template.getSkuName());
                    newSku.setPrice(template.getSkuPrice());
                    newSku.setCreateTime(now);
                    toInsert.add(newSku);
                } else {
                    // 更新
                    exist.setPrice(template.getSkuPrice());
                    exist.setUpdateTime(now);
                    toUpdate.add(exist);
                }
            }
        }

        if (!toInsert.isEmpty()) {
            skuService.saveBatch(toInsert);
        }
        if (!toUpdate.isEmpty()) {
            skuService.updateBatchById(toUpdate);
        }
    }



    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByIdsVo(List<Long> idList) throws Exception {
        for (Long id : idList) {
            LambdaQueryWrapper<ShopInspectionGoods> queryWrapper =new LambdaQueryWrapper<>();
            queryWrapper.eq(ShopInspectionGoods::getGoodsCategoryId,id);
            long count = goodsService.count(queryWrapper);
            if (count>0){
                throw new Exception("该分类下有商品不可删除");
            }
            this.removeById(id);
            LambdaQueryWrapper<InspectionCategoryTemplate> queryWrapper2 =new LambdaQueryWrapper<>();
            queryWrapper2.eq(InspectionCategoryTemplate::getCategoryId,id);
            templateService.remove(queryWrapper2);
        }


    }

    @Override
    public PageResult<ShopInspectionCategory> listVo(ShopInspectionCategory shopInspectionCategory, PageParam pageParam) {

        QueryWrapper<ShopInspectionCategory> queryWrapper = new QueryWrapper<>();
        if(null!=shopInspectionCategory.getCategoryName()){
            queryWrapper.like("category_name",shopInspectionCategory.getCategoryName());
        }
        queryWrapper.orderByAsc("order_num");
        return baseMapper.selectPage(pageParam,queryWrapper);
    }

    @Override
    public ShopInspectionCategory getByIdVo(Long id) {
        ShopInspectionCategory category = this.getById(id);
        LambdaQueryWrapper<InspectionCategoryTemplate> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(InspectionCategoryTemplate::getCategoryId,id).orderByAsc(InspectionCategoryTemplate::getId);
        List<InspectionCategoryTemplate> list = templateService.list(queryWrapper);
        category.setTemplates(list);
        return category;
    }

}

