package com.yc.ship.module.ota.service.distributorproduct;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yc.ship.framework.common.exception.ErrorCode;
import com.yc.ship.framework.common.lang.Asserts;
import com.yc.ship.framework.common.pojo.CommonResult;
import com.yc.ship.framework.common.util.object.BeanUtils;
import com.yc.ship.framework.mybatis.core.util.MyBatisUtils;
import com.yc.ship.framework.tenant.core.aop.TenantIgnore;
import com.yc.ship.framework.tenant.core.context.TenantContextHolder;
import com.yc.ship.module.ota.controller.admin.distributor.vo.DistributorRespVO;
import com.yc.ship.module.ota.controller.admin.distributorproduct.vo.DistributorProductPageReqVO;
import com.yc.ship.module.ota.controller.admin.distributorproduct.vo.DistributorProductRespVO;
import com.yc.ship.module.ota.controller.admin.distributorproduct.vo.DistributorProductSaveReqVO;
import com.yc.ship.module.ota.controller.admin.distributorproduct.vo.DistributorProjectSaveReqVO;
import com.yc.ship.module.ota.controller.admin.distributorproduct.vo.product.InitializeDistributorProductReqVO;
import com.yc.ship.module.ota.controller.admin.distributorproduct.vo.product.ProductGroupRespVO;
import com.yc.ship.module.ota.controller.admin.distributorproduct.vo.product.ProductPageReqVO;
import com.yc.ship.module.ota.controller.admin.distributorproduct.vo.product.ProductRespVO;
import com.yc.ship.module.ota.api.dto.DistributorAgencyPriceDTO;
import com.yc.ship.module.ota.api.dto.DistributorProductRespDTO;
import com.yc.ship.module.ota.dal.dataobject.distributor.DistributorDO;
import com.yc.ship.module.ota.dal.dataobject.distributorproduct.DistributorAgencyPriceDO;
import com.yc.ship.module.ota.dal.dataobject.distributorproduct.DistributorProductDO;
import com.yc.ship.module.ota.dal.dataobject.distributorproduct.DistributorProjectDO;
import com.yc.ship.module.ota.dal.mysql.distributor.DistributorMapper;
import com.yc.ship.module.ota.dal.mysql.distributorproduct.DistributorAgencyPriceMapper;
import com.yc.ship.module.ota.dal.mysql.distributorproduct.DistributorProductMapper;
import com.yc.ship.module.ota.dal.mysql.distributorproduct.DistributorProjectMapper;
import com.yc.ship.module.ota.service.distributor.DistributorService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static com.yc.ship.framework.common.exception.util.ServiceExceptionUtil.exception;

/**
 * 平台产品与分销商关系 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
@Slf4j
public class DistributorProductServiceImpl implements DistributorProductService {

    @Resource
    private DistributorProductMapper distributorProductMapper;
    @Resource
    private DistributorMapper distributorMapper;
    @Resource
    private DistributorService distributorService;
    @Resource
    private DistributorProjectMapper distributorProjectMapper;
    @Resource
    private DistributorAgencyPriceMapper distributorAgencyPriceMapper;

    @Override
    public String createDistributorProduct(DistributorProductSaveReqVO createReqVO) {
        // 插入
        DistributorProductDO distributorProduct = BeanUtils.toBean(createReqVO, DistributorProductDO.class);
        distributorProductMapper.insert(distributorProduct);
        // 返回
        return distributorProduct.getId();
    }

    @Override
    public void updateDistributorProduct(DistributorProductSaveReqVO updateReqVO) {
        //查询是否存在ID
        if (updateReqVO.getId() == null) {
            //初始化
            //查询分销商信息
            DistributorRespVO DistributorVo = distributorMapper.getDistributorById(updateReqVO.getDistributorId());
            if (DistributorVo != null) {
                if (DistributorVo.getType() == 1) {
                    //查询产品规格信息
                    DistributorProductRespVO vo = distributorProductMapper.getProductSku(updateReqVO.getProductSkuId());
                    //查询所有分销商
                    List<DistributorRespVO> distributorRespVOList = distributorService.getOtcDistributor(1);
                    //获取产品规格信息
                    List<ProductGroupRespVO> list = distributorProductMapper.selectProjectType(updateReqVO.getProductId(), 0, vo.getSpecType());
                    //获取产品子票规格数量
                    List<Map<String, Object>> listAll = distributorProductMapper.selectBaseNum(updateReqVO.getProductId(), vo.getSpecType());

                    //初始化分销商绑定产品和规格
                    if (!distributorRespVOList.isEmpty()) {
                        insertDistributorProductSkuInfo(distributorRespVOList, vo, list, listAll, updateReqVO.getIsUse());
                    }
                } else if (DistributorVo.getType() == 2) {
                    //查询产品信息
                    DistributorProductRespVO vo = distributorProductMapper.getProductSpu(updateReqVO.getProductId());
                    //查询所有分销商
                    List<DistributorRespVO> distributorRespVOList = distributorService.getOtcDistributor(2);
                    //获取当前产品的所有规格
                    List<DistributorProductRespVO> list = distributorProductMapper.getProductSkuList(updateReqVO.getProductId());
                    //初始化旅行社绑定产品
                    if (!distributorRespVOList.isEmpty()) {
                        insertDistributorProductSpuInfo(distributorRespVOList, vo, list, updateReqVO.getIsUse());
                    }
                }
            }
        } else {
            // 更新
            LambdaUpdateWrapper<DistributorProductDO> updateWrapper = new LambdaUpdateWrapper<DistributorProductDO>()
                    .eq(DistributorProductDO::getId, updateReqVO.getId())
                    .set(DistributorProductDO::getIsUse, updateReqVO.getIsUse());
            if (updateReqVO.getSalePrice() != null) {
                updateWrapper.set(DistributorProductDO::getSalePrice, updateReqVO.getSalePrice());
            }
            if (updateReqVO.getRoutePlanId() != null) {
                updateWrapper.set(DistributorProductDO::getRoutePlanId, updateReqVO.getRoutePlanId());
            }
            if (updateReqVO.getStartDate() != null) {
                updateWrapper.set(DistributorProductDO::getStartDate, updateReqVO.getStartDate());
            }
            if (updateReqVO.getEndDate() != null) {
                updateWrapper.set(DistributorProductDO::getEndDate, updateReqVO.getEndDate());
            }
            distributorProductMapper.update(updateWrapper);
        }
    }

    @Override
    public void deleteDistributorProduct(String id) {
        // 删除
        distributorProductMapper.deleteById(id);
    }


    @Override
    public DistributorProductDO getDistributorProduct(String id) {
        return distributorProductMapper.selectById(id);
    }

    @Override
    public IPage<DistributorProductRespVO> getDistributorProductPage(DistributorProductPageReqVO pageReqVO) {
        IPage<DistributorProductPageReqVO> iPage = MyBatisUtils.buildPage(pageReqVO);
        IPage<DistributorProductRespVO> pageResult = distributorProductMapper.getPage(iPage, pageReqVO);
        pageResult.getRecords().forEach(vo -> {
            //查询当前产品上级所有分组信息
            List<Map<String, Object>> listMap = distributorProductMapper.selectCategoryList(vo.getCategoryId());
            StringBuilder categoryName = new StringBuilder();
            for (Map<String, Object> map : listMap) {
                String cateName = map.get("cateName").toString();
                categoryName.insert(0, "/" + cateName);
            }
            if (StringUtils.isNotBlank(categoryName.toString())) {
                vo.setCategoryName(categoryName.substring(1));
            } else {
                vo.setCategoryName("-");
            }
            if (pageReqVO.getProductSkuId() != null) {
                //查询所有规格
                vo.setProductGroupList(distributorProductMapper.selectProjectType(vo.getProductId(), 1, vo.getSpecType()));
                //查询当前旅行社选中的基础票规格
                DistributorProjectDO distributorProduct = new DistributorProjectDO();
                distributorProduct.setDistributorProductId(vo.getId());
                distributorProduct.setDistributorId(vo.getDistributorId());
                distributorProduct.setProductId(vo.getProductId());
                List<ProductGroupRespVO> list = distributorProjectMapper.getProductGroupList(distributorProduct);
                for (ProductGroupRespVO productGroupRespVO : vo.getProductGroupList()) {
                    for (ProductGroupRespVO productGroupRespVO1 : list) {
                        if(productGroupRespVO.getProductBaseId().equals(productGroupRespVO1.getProductBaseId())) {
                            productGroupRespVO.setIsUse(productGroupRespVO1.getIsUse());
                            productGroupRespVO.setSelected(productGroupRespVO1.getIsUse());
                        }
                        //必须默认选中
                        if(productGroupRespVO1.getNeedChoose()!=null && productGroupRespVO1.getNeedChoose()==1){
                            productGroupRespVO.setIsUse(1);
                            productGroupRespVO.setSelected(1);
                        }
                    }
                }
            }
        });
        return pageResult;
    }

    @Override
    public void updateStatus(String id, Integer status) {
        // 更新状态
        LambdaUpdateWrapper<DistributorProductDO> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(DistributorProductDO::getId, id);
        wrapper.set(DistributorProductDO::getIsUse, status);
        distributorProductMapper.update(wrapper);
    }

    @Override
    @TenantIgnore
    public void updateStatusOtc(String id, Integer status) {
        Long tenantId = TenantContextHolder.getTenantId();
        DistributorDO distributorDO = distributorMapper.selectOne(DistributorDO::getAccountTenantId, tenantId);
        LambdaUpdateWrapper<DistributorProductDO> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(DistributorProductDO::getProductId, id);
        wrapper.eq(DistributorProductDO::getDistributorId, distributorDO.getId());
        wrapper.set(DistributorProductDO::getIsUseOtc, status);
        distributorProductMapper.update(wrapper);
    }

    @Override
    public void updateStatusList(DistributorProductSaveReqVO updateReqVO) {
        distributorProductMapper.updateListStatus(updateReqVO.getIdList(), updateReqVO.getIsUse());
    }
    @Override
    public void updateStatus2List(DistributorProductSaveReqVO updateReqVO) {
        distributorProductMapper.update2ListStatus(updateReqVO.getIdList(),updateReqVO.getDistributorIds(), updateReqVO.getIsUse());
    }

    @Override
    public void updateStoreProductList(DistributorProductSaveReqVO updateReqVO) {
        try {

        } catch (Exception e) {
            throw exception(new ErrorCode(60_001, "门店产品更新异常"));
        }
    }

    @Override
    public void updateStatusInitList(List<DistributorProductSaveReqVO> updateReqVO) {
        for (DistributorProductSaveReqVO productSaveReqVO : updateReqVO) {
            updateDistributorProduct(productSaveReqVO);
        }
    }

    @Override
    public IPage<ProductRespVO> getProductPage(ProductPageReqVO pageReqVO) {
        IPage<ProductPageReqVO> iPage = MyBatisUtils.buildPage(pageReqVO);
        IPage<ProductRespVO> pageResult = distributorProductMapper.getProductPage(iPage, pageReqVO);
        pageResult.getRecords().forEach(vo -> {
            //查询当前产品上级所有分组信息
            List<Map<String, Object>> list = distributorProductMapper.selectCategoryList(vo.getCategoryId());
            StringBuilder categoryName = new StringBuilder();
            for (Map<String, Object> map : list) {
                String cateName = map.get("cateName").toString();
                categoryName.insert(0, "/" + cateName);
            }
            if (StringUtils.isNotBlank(categoryName.toString())) {
                vo.setCategoryName(categoryName.substring(1));
            } else {
                vo.setCategoryName("-");
            }
        });
        return pageResult;
    }

    @Override
    public IPage<DistributorProductRespVO> pageDistributorProduct(ProductPageReqVO pageReqVO) {
        IPage<ProductRespVO> pageResult = getProductPage(pageReqVO);
        //转对象
        IPage<DistributorProductRespVO> pageResult1 = new Page<>();
        pageResult1.setPages(pageResult.getPages());
        pageResult1.setSize(pageResult.getSize());
        pageResult1.setTotal(pageResult.getTotal());
        pageResult1.setRecords(BeanUtils.toBean(pageResult.getRecords(), DistributorProductRespVO.class));
        pageResult1.getRecords().forEach(productRespVO -> {
            if (pageReqVO.getDistributorId() != null) {
                //查询是否存在分销商绑定信息
                List<DistributorProductRespVO> distributorProductList = distributorProductMapper.getDistributorProductList(
                        pageReqVO.getDistributorId(), productRespVO.getProductId(), productRespVO.getProductSkuId());
                if (!distributorProductList.isEmpty()) {
                    for (DistributorProductRespVO distributorProductRespVO : distributorProductList) {
                        productRespVO.setId(distributorProductRespVO.getId());
                        productRespVO.setIsUse(distributorProductRespVO.getIsUse());
                        productRespVO.setStartDate(distributorProductRespVO.getStartDate());
                        productRespVO.setEndDate(distributorProductRespVO.getEndDate());
                        productRespVO.setSalePrice(distributorProductRespVO.getSalePrice());
                    }
                } else {
                    productRespVO.setIsUse(0);
                }
                productRespVO.setDistributorId(pageReqVO.getDistributorId());

            }
        });
        return pageResult1;
    }

    @Override
    public List<DistributorProductRespVO> distributorProductTree(ProductPageReqVO pageReqVO) {
        List<DistributorProductRespVO> productList = distributorProductMapper.selectDistributorProductList(pageReqVO);
        Set<Long> ids = productList.stream().map(DistributorProductRespVO::getCategoryId).collect(Collectors.toSet());
        return productList;
    }

    @Override
    public List<ProductRespVO> productTree(ProductPageReqVO pageReqVO) {
        Asserts.isTrue(pageReqVO.getChannelType() != null, "分销渠道未知");
        List<ProductRespVO> productList = distributorProductMapper.selectProductList(pageReqVO);
        Set<Long> ids = productList.stream().map(ProductRespVO::getCategoryId).collect(Collectors.toSet());
        return productList;
    }

    @Override
    public void initializeProductDistributorInfo(DistributorProductPageReqVO reqVO) {
        //查询分销商信息
        DistributorRespVO distributorVo = distributorMapper.getDistributorById(reqVO.getDistributorId());
        if (distributorVo != null) {
            //获取产品信息
            ProductPageReqVO pageReqVO = new ProductPageReqVO();
            pageReqVO.setChannelType(distributorVo.getType());
            pageReqVO.setPageSize(-1);
            IPage<ProductPageReqVO> iPage = MyBatisUtils.buildPage(pageReqVO);
            IPage<ProductRespVO> pageResult = distributorProductMapper.getProductPage(iPage, pageReqVO);

            if (distributorVo.getType() == 1) {
                pageResult.getRecords().forEach(productRespVO -> {
                    //查询产品规格信息
                    DistributorProductRespVO vo = distributorProductMapper.getProductSku(productRespVO.getProductSkuId());
                    //查询所有分销商
                    List<DistributorRespVO> distributorRespVOList = Collections.singletonList(distributorVo);
                    //获取产品规格信息
                    List<ProductGroupRespVO> list = distributorProductMapper.selectProjectType(productRespVO.getProductId(), 0, vo.getSpecType());
                    //获取产品子票规格数量
                    List<Map<String, Object>> listAll = distributorProductMapper.selectBaseNum(productRespVO.getProductId(), vo.getSpecType());

                    //初始化分销商绑定产品和规格
                    insertDistributorProductSkuInfo(distributorRespVOList, vo, list, listAll, 0);
                });
            } else if (distributorVo.getType() == 2) {
                pageResult.getRecords().forEach(productRespVO -> {
                    //查询产品信息
                    DistributorProductRespVO vo = distributorProductMapper.getProductSpu(productRespVO.getProductId());
                    //查询所有分销商
                    List<DistributorRespVO> distributorRespVOList = new ArrayList<>();
                    distributorRespVOList.add(distributorVo);
                    //获取当前产品的所有规格
                    List<DistributorProductRespVO> list = distributorProductMapper.getProductSkuList(reqVO.getProductId());
                    //初始化旅行社绑定产品
                    insertDistributorProductSpuInfo(distributorRespVOList, vo, list, 0);
                });
            }
        }
    }

    @Override
    public void initializeDistributorProductInfo(InitializeDistributorProductReqVO reqVO) {
        if (reqVO.getChannelType() == 1) {
            //查询产品规格信息
            DistributorProductRespVO vo = distributorProductMapper.getProductSku(reqVO.getProductSkuId());
            //查询分销商
            List<DistributorRespVO> distributorList = getOtcDistributorByType(reqVO.getChannelType(), reqVO.getDistributorIds());
            //获取产品规格信息
            List<ProductGroupRespVO> list = distributorProductMapper.selectProjectType(reqVO.getProductId(), 0, vo.getSpecType());
            //获取产品子票规格数量
            List<Map<String, Object>> listAll = distributorProductMapper.selectBaseNum(reqVO.getProductId(), vo.getSpecType());
            //初始化分销商绑定产品和规格
            if (!distributorList.isEmpty()) {
                Integer isUse = reqVO.getIsUse() == null ? 0 : reqVO.getIsUse();
                insertDistributorProductSkuInfo(distributorList, vo, list, listAll, isUse);
            }
        } else if (reqVO.getChannelType() == 2) {
            //查询产品信息
            DistributorProductRespVO vo = distributorProductMapper.getProductSpu(reqVO.getProductId());
            //查询分销商
            List<DistributorRespVO> distributorList = getOtcDistributorByType(reqVO.getChannelType(), reqVO.getDistributorIds());
            //获取当前产品的所有规格
            List<DistributorProductRespVO> list = distributorProductMapper.getProductSkuList(reqVO.getProductId());
            //初始化旅行社绑定产品
            if (!distributorList.isEmpty()) {
                Integer isUse = reqVO.getIsUse() == null ? 0 : reqVO.getIsUse();
                insertDistributorProductSpuInfo(distributorList, vo, list, isUse);
            }
        }
    }

    /**
     * 查询分销商
     *
     * @param type           类型 1:ota分销商 2:旅行社
     * @param distributorIds 分销商ids
     * @return list
     */
    private List<DistributorRespVO> getOtcDistributorByType(Integer type, String distributorIds) {
        //查询所有分销商
        List<DistributorRespVO> list = distributorService.getOtcDistributor(type);
        if (!Objects.isNull(distributorIds)) {
            Long[] ids = Convert.toLongArray(distributorIds.split(","));
            List<Long> idList = Arrays.asList(ids);
            list = list.stream().filter(item -> idList.contains(item.getId())).collect(Collectors.toList());
        }
        return list;
    }

    public void insertDistributorProductSkuInfo(List<DistributorRespVO> serverList,
                                                DistributorProductRespVO productRespVO,
                                                List<ProductGroupRespVO> productGroupList,
                                                List<Map<String, Object>> mapList, Integer isUse) {
        //刪除不存在的OTA信息
        List<Long> lst_ota = serverList.stream().map(DistributorRespVO::getId).collect(Collectors.toList());
        distributorProductMapper.deleteDistributor(lst_ota, productRespVO.getProductId(), productRespVO.getProductSkuId());
        //添加票务对应的OTA信息
        DistributorProductDO prvo;
        for (DistributorRespVO ser : serverList) {
            List<DistributorProductDO> list = distributorProductMapper.selectList(new LambdaUpdateWrapper<DistributorProductDO>()
                    .eq(DistributorProductDO::getDistributorId, ser.getId())
                    .eq(DistributorProductDO::getProductId, productRespVO.getProductId())
                    .eq(DistributorProductDO::getSpecType, productRespVO.getSpecType())
            );
            //判断是是否存在关系
            BigDecimal costPrice = BigDecimal.ZERO;
            BigDecimal salePrice = BigDecimal.ZERO;
            for (ProductGroupRespVO productGroupRespVO : productGroupList) {
                for (Map<String, Object> map : mapList) {
                    if (productGroupRespVO.getProductBaseId().equals(map.get("baseId"))) {
                        if (productGroupRespVO.getNeedChoose() == 0 || (Long) map.get("num") > 1) {
                            costPrice = costPrice.add(productGroupRespVO.getCostPrice());
                            salePrice = salePrice.add(productGroupRespVO.getSalePrice());
                        }
                    }
                }
            }
            String id = IdWorker.getIdStr();
            if (list.isEmpty()) {
                prvo = new DistributorProductDO();
                prvo.setId(id);
                prvo.setDistributorId(ser.getId());
                prvo.setIsUse(isUse);
                prvo.setIsUseOtc(1);
                prvo.setProductId(productRespVO.getProductId());
                prvo.setProductSkuId(productRespVO.getProductSkuId());
                prvo.setCostPrice(productRespVO.getCostPrice().add(costPrice));
                prvo.setSalePrice(productRespVO.getSalePrice().add(salePrice));
                prvo.setSalePriceRaw(productRespVO.getSalePrice().add(salePrice));
                prvo.setStock(productRespVO.getStock());
                prvo.setSpecType(productRespVO.getSpecType());
                distributorProductMapper.insert(prvo);
            } else {
                //判断是否skuId发生变化
                if (!list.get(0).getProductSkuId().equals(productRespVO.getProductSkuId())) {
                    list.get(0).setCostPrice(productRespVO.getCostPrice());
                    list.get(0).setProductSkuId(productRespVO.getProductSkuId());
                    list.get(0).setSalePriceRaw(productRespVO.getSalePrice());
                    list.get(0).setStock(productRespVO.getStock());
                    distributorProductMapper.updateById(list.get(0));
                }
                id = list.get(0).getId();
            }
            //查询分销商基础产品规格表子票信息(删除不纯在的子票ID)
            DistributorProjectDO projectDO = new DistributorProjectDO();
            projectDO.setDistributorProductId(id);
            List<DistributorProjectDO> projectList = distributorProjectMapper.getDistributorProjectList(projectDO);
            List<Long> baseIdList = new ArrayList<>();
            for (DistributorProjectDO project : projectList) {
                boolean isExist = false;
                for (ProductGroupRespVO group : productGroupList) {
                    if (project.getProductBaseId().equals(group.getProductBaseId())
                            && project.getSpecificationId().equals(group.getSpecificationId())) {
                        isExist = true;
                        break;
                    }
                }
                if (!isExist) {
                    baseIdList.add(project.getId());
                }
            }
            //删除没有的子票
            for (Long baseId : baseIdList) {
                distributorProjectMapper.deleteById(baseId);
            }

            for (ProductGroupRespVO productGroupRespVO : productGroupList) {
                //判断是否存在规格
                DistributorProjectDO distributorProduct = new DistributorProjectDO();
                distributorProduct.setId(IdWorker.getId());
                distributorProduct.setDistributorProductId(id);
                distributorProduct.setDistributorId(ser.getId());
                distributorProduct.setIsUse(1);
                distributorProduct.setProductId(productRespVO.getProductId());
                distributorProduct.setSpecType(productGroupRespVO.getSpecType());
                distributorProduct.setProductBaseId(productGroupRespVO.getProductBaseId());
                List<DistributorProjectDO> distributorProjectList = distributorProjectMapper.getDistributorProjectList(distributorProduct);
                //判断是是否存在关系
                if (distributorProjectList.isEmpty()) {
                    distributorProduct.setSpecificationId(productGroupRespVO.getSpecificationId());
                    distributorProduct.setCostPrice(productGroupRespVO.getCostPrice());
                    distributorProduct.setSalePrice(productGroupRespVO.getSalePrice());
                    distributorProjectMapper.insert(distributorProduct);
                }
            }
        }
    }

    public void insertDistributorProductSpuInfo(List<DistributorRespVO> serverList, DistributorProductRespVO productRespVO, List<DistributorProductRespVO> productRespVOList, Integer isUse) {
        List<DistributorProductDO> insertBatch = new ArrayList<>();
        List<DistributorAgencyPriceDO> insertPriceBatch = new ArrayList<>();
        List<DistributorAgencyPriceDO> updatePriceBatch = new ArrayList<>();
        Set<Long> baseIdList = new HashSet<>();

        //删除不存在的旅行社  可以考虑做定时任务
        List<Long> lst_ota = serverList.stream().map(DistributorRespVO::getId).collect(Collectors.toList());
        distributorProductMapper.deleteDistributor(lst_ota, productRespVO.getProductId(), productRespVO.getProductSkuId());

        List<DistributorProductDO> list = distributorProductMapper.selectList(new LambdaUpdateWrapper<DistributorProductDO>().eq(DistributorProductDO::getProductId, productRespVO.getProductId()));

        DistributorAgencyPriceDO distributorAgencyPriceDO = new DistributorAgencyPriceDO();
        distributorAgencyPriceDO.setProductId(productRespVO.getProductId());
        List<DistributorAgencyPriceDO> distributorAgencyPriceList = distributorAgencyPriceMapper.getDistributorAgencyPriceList(distributorAgencyPriceDO);

        DistributorAgencyPriceDO agencyPriceDO = new DistributorAgencyPriceDO();
        agencyPriceDO.setProductId(productRespVO.getProductId());
        List<DistributorAgencyPriceDO> priceList = distributorAgencyPriceMapper.getDistributorAgencyPriceList(agencyPriceDO);

        for (DistributorRespVO ser : serverList) {
            List<DistributorProductDO> dlist = list.stream().filter(dis ->dis.getDistributorId().equals(ser.getId())).collect(Collectors.toList());
            //判断是是否存在关系
            String id = IdWorker.getIdStr();
            boolean isExt = false;
            if (dlist.isEmpty()) {
                DistributorProductDO prvo = new DistributorProductDO();
                prvo.setId(id);
                prvo.setDistributorId(ser.getId());
                prvo.setIsUse(isUse);
                prvo.setIsUseOtc(1);
                prvo.setProductId(productRespVO.getProductId());
                prvo.setProductSkuId(productRespVO.getProductSkuId());
                prvo.setCostPrice(productRespVO.getCostPrice());
                prvo.setSalePrice(productRespVO.getSalePrice());
                prvo.setStock(productRespVO.getStock());
                insertBatch.add(prvo);
            } else {
                id = dlist.get(0).getId();
                isExt = true;
            }
            //查询分销商基础产品规格信息(删除不纯在的规格)
            final String nid = id;
//            if(!isExt) {
                agencyPriceDO.setDistributorProductId(Long.parseLong(id));
                List<DistributorAgencyPriceDO> newpriceList = priceList.stream().filter(price -> !price.getDistributorProductId().toString().equals(nid)).collect(Collectors.toList());
                if(!newpriceList.isEmpty()) {
                    for (DistributorAgencyPriceDO price : newpriceList) {
                        boolean isExist = false;
                        for (DistributorProductRespVO distributorProductRespVO : productRespVOList) {
                            if (price.getProductSkuId().equals(distributorProductRespVO.getProductSkuId())) {
                                isExist = true;
                                break;
                            }
                        }
                        if (!isExist) {
                            baseIdList.add(Long.parseLong(price.getId()));
                        }
                    }
                }
//            }

            for (DistributorProductRespVO productGroupRespVO : productRespVOList) {

                List<DistributorAgencyPriceDO> fiterdistributorAgencyPriceList = distributorAgencyPriceList.stream().filter(dis ->
                        dis.getDistributorProductId().toString().equals(nid)
                        &&dis.getDistributorId().equals(ser.getId())
                        &&dis.getSpecType().equals(productGroupRespVO.getSpecType())).collect(Collectors.toList());

                //判断是是否存在关系
                if (fiterdistributorAgencyPriceList.isEmpty()) {
                    DistributorAgencyPriceDO indistributorAgencyPriceDO = new DistributorAgencyPriceDO();
                    indistributorAgencyPriceDO.setId(IdWorker.getIdStr());
                    indistributorAgencyPriceDO.setDistributorProductId(Long.parseLong(id));
                    indistributorAgencyPriceDO.setDistributorId(ser.getId());
                    indistributorAgencyPriceDO.setCostPrice(productGroupRespVO.getCostPrice());
                    indistributorAgencyPriceDO.setSpecType(productGroupRespVO.getSpecType());
                    indistributorAgencyPriceDO.setProductId(productRespVO.getProductId());
                    indistributorAgencyPriceDO.setProductSkuId(productGroupRespVO.getProductSkuId());
                    indistributorAgencyPriceDO.setSalePrice(productGroupRespVO.getSalePrice());
                    indistributorAgencyPriceDO.setStock(productGroupRespVO.getStock());
                    insertPriceBatch.add(indistributorAgencyPriceDO);
                } else {
                    DistributorAgencyPriceDO updatedistributorAgencyPrice = fiterdistributorAgencyPriceList.get(0);
                    if (!Objects.equals(productGroupRespVO.getProductSkuId(), updatedistributorAgencyPrice.getProductSkuId())) {
                        // 产品修改后，同步保存修改的信息
                        updatedistributorAgencyPrice.setCostPrice(productGroupRespVO.getCostPrice());
                        updatedistributorAgencyPrice.setProductSkuId(productGroupRespVO.getProductSkuId());
                        updatedistributorAgencyPrice.setStock(productGroupRespVO.getStock());
                        updatePriceBatch.add(updatedistributorAgencyPrice);
                    }
                }
            }
        }
        if(!baseIdList.isEmpty()) {
            distributorAgencyPriceMapper.deleteBatchIds(baseIdList);
        }
        if(!insertBatch.isEmpty()) {
            distributorProductMapper.insertBatch(insertBatch);
        }
        if(!insertPriceBatch.isEmpty()) {
            distributorAgencyPriceMapper.insertBatch(insertPriceBatch);
        }
        if(!updatePriceBatch.isEmpty()) {
            distributorAgencyPriceMapper.updateBatch(updatePriceBatch);
        }
    }

    @Override
    public CommonResult<List<DistributorProductRespDTO>> getProductListByDistributorId(Long distributorId) {


        return null;
    }

    @Override
    @TenantIgnore
    public CommonResult<Long> getProductById(Long distributorProductId) {
        DistributorProductDO distributorProduct = this.getDistributorProduct(distributorProductId.toString());
        Asserts.isTrue(null != distributorProduct, "分销商产品信息不存在{}", distributorProductId);
        return CommonResult.success(distributorProduct.getProductId());
    }

    @Override
    public CommonResult<DistributorProductRespDTO> getDistributorProductByProductAndDistributor(Long productId, Long distributorId) {
        List<DistributorProductDO> productDOList = distributorProductMapper.selectList(new LambdaQueryWrapper<DistributorProductDO>()
                .eq(DistributorProductDO::getDistributorId, distributorId)
                .eq(DistributorProductDO::getProductId, productId)
                .eq(DistributorProductDO::getIsUse, 1));
        DistributorProductDO productDO = null;
        if (CollUtil.isNotEmpty(productDOList)) {
            productDO = productDOList.get(0);
        }
        return CommonResult.success(BeanUtils.toBean(productDO, DistributorProductRespDTO.class));
    }


    @Override
    @TenantIgnore
    public CommonResult<DistributorProductRespDTO> getDistributorProductById(Long distributorProductId) {

        DistributorProductDO distributorProduct = this.getDistributorProduct(distributorProductId.toString());
        Asserts.isTrue(null != distributorProduct, "分销商产品信息不存在{}", distributorProductId);
        DistributorProductRespDTO respDTO = BeanUtils.toBean(distributorProduct, DistributorProductRespDTO.class);
        if (distributorProduct.getProductSkuId() != null) {
            //说明是分销商产品
            List<DistributorProjectDO> distributorProjectList = distributorProjectMapper.selectList(DistributorProjectDO::getDistributorProductId, distributorProduct.getId(),
                    DistributorProjectDO::getDistributorId, distributorProduct.getDistributorId());
            List<DistributorProductRespDTO.DistributorProjectDTO> distributorProjectDTOList = BeanUtils.toBean(distributorProjectList, DistributorProductRespDTO.DistributorProjectDTO.class);
            respDTO.setDistributorProjectList(distributorProjectDTOList);
        } else {
            //旅行社分销产品价格
            DistributorAgencyPriceDO distributorAgencyPriceDO = new DistributorAgencyPriceDO();
            distributorAgencyPriceDO.setDistributorProductId(distributorProductId);
            List<DistributorAgencyPriceDO> distributorAgencyPriceList = distributorAgencyPriceMapper.getDistributorAgencyPriceList(distributorAgencyPriceDO);
            respDTO.setDistributorAgencyPriceList(BeanUtils.toBean(distributorAgencyPriceList, DistributorAgencyPriceDTO.class));
        }

        return CommonResult.success(respDTO);
    }

    @Override
    public CommonResult<List<DistributorProductRespDTO>> getProductListPageByDistributorId(Long distributorId, int pageIndex, int pageSize) {
        DistributorProductPageReqVO pageReqVO = new DistributorProductPageReqVO();
        pageReqVO.setDistributorId(distributorId);
        IPage<DistributorProductPageReqVO> iPage = new Page<>(pageIndex, pageSize);
        IPage<DistributorProductRespVO> page = distributorProductMapper.getPage(iPage, pageReqVO);
        List<DistributorProductRespVO> distributorProductList = page.getRecords();
        return CommonResult.success(BeanUtils.toBean(distributorProductList, DistributorProductRespDTO.class));
    }

    @Override
    public List<ProductGroupRespVO> selectProjectType(Long productId) {
        return distributorProductMapper.selectProjectType(productId, 1, "");
    }

    @Override
    public List<DistributorAgencyPriceDO> selectAgencyPrice(DistributorAgencyPriceDO vo) {
        return distributorAgencyPriceMapper.getDistributorAgencyPriceList(vo);
    }

    @Override
    public void updateProjectType(DistributorProjectSaveReqVO createReqVO) {
        DistributorProjectDO updateObj = BeanUtils.toBean(createReqVO, DistributorProjectDO.class);

        //查询当前旅行社选中的基础票规格
        DistributorProjectDO distributorProject = new DistributorProjectDO();
        distributorProject.setDistributorProductId(updateObj.getDistributorProductId());
        distributorProject.setDistributorId(updateObj.getDistributorId());
        distributorProject.setProductId(updateObj.getProductId());
        distributorProject.setProductBaseId(updateObj.getProductBaseId());
        List<ProductGroupRespVO> productGroupList = distributorProjectMapper.getProductGroupList(distributorProject);

        //更新平台产品与分销商关系表金额数据
        DistributorProductDO distributorProduct = distributorProductMapper.selectOne(new LambdaUpdateWrapper<DistributorProductDO>()
                .eq(DistributorProductDO::getDistributorId, updateObj.getDistributorId())
                .eq(DistributorProductDO::getProductId, updateObj.getProductId())
                .eq(DistributorProductDO::getProductSkuId, createReqVO.getProductSkuId())
        );
        if (updateObj.getIsUse().equals(productGroupList.get(0).getIsUse()) && updateObj.getSpecificationId().equals(productGroupList.get(0).getSpecificationId())) {
            return;
        }
        //修改对应的值
        UpdateWrapper<DistributorProjectDO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("distributor_id", updateObj.getDistributorId());
        updateWrapper.eq("distributor_product_id", updateObj.getDistributorProductId());
        updateWrapper.eq("product_base_id", updateObj.getProductBaseId());
        updateWrapper.eq("product_id", updateObj.getProductId());
        if (createReqVO.getIsUse().equals(productGroupList.get(0).getIsUse()) && createReqVO.getIsUse() == 1) {
            BigDecimal decimal = distributorProduct.getSalePrice().subtract(productGroupList.get(0).getSalePrice());
            decimal = decimal.add(updateObj.getSalePrice());
            distributorProduct.setSalePrice(decimal);
            distributorProduct.setSalePriceRaw(decimal);
            distributorProductMapper.updateById(distributorProduct);
        } else {
            BigDecimal decimal = distributorProduct.getSalePrice();
            if (createReqVO.getIsUse() == 1) {
                if(updateObj.getSalePrice()!=null) {
                    decimal = decimal.add(updateObj.getSalePrice());
                }
            } else {
                decimal = decimal.subtract(productGroupList.get(0).getSalePrice());
            }
            distributorProduct.setSalePrice(decimal);
            distributorProduct.setSalePriceRaw(decimal);
            distributorProductMapper.updateById(distributorProduct);
        }
        updateWrapper.set("is_use", updateObj.getIsUse());
        updateWrapper.set("specification_id", updateObj.getSpecificationId());
        updateWrapper.set("cost_price", updateObj.getCostPrice());
        updateWrapper.set("sale_price", updateObj.getSalePrice());
        distributorProjectMapper.update(updateWrapper);
    }

    @Override
    public void updateAgencyPrice(DistributorAgencyPriceDO createReqVO) {
        DistributorAgencyPriceDO updateObj = BeanUtils.toBean(createReqVO, DistributorAgencyPriceDO.class);
        UpdateWrapper<DistributorAgencyPriceDO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("distributor_id", updateObj.getDistributorId());
        updateWrapper.eq("distributor_product_id", updateObj.getDistributorProductId());
        updateWrapper.eq("product_sku_id", updateObj.getProductSkuId());
        updateWrapper.eq("product_id", updateObj.getProductId());
        updateWrapper.set("cost_price", updateObj.getCostPrice());
        updateWrapper.set("sale_price", updateObj.getSalePrice());
        updateWrapper.set("stock", updateObj.getStock());
        distributorAgencyPriceMapper.update(updateWrapper);
    }

    @Override
    @TenantIgnore
    public CommonResult<DistributorProductRespDTO> getDistributorCalendarProductById(Long distributorProductId, String useDate) {

        DistributorProductDO distributorProduct = this.getDistributorProduct(distributorProductId.toString());
        Asserts.isTrue(null != distributorProduct, "分销商产品信息不存在{}", distributorProductId);
        DistributorProductRespDTO respDTO = BeanUtils.toBean(distributorProduct, DistributorProductRespDTO.class);
        if (distributorProduct.getProductSkuId() != null) {
            //说明是分销商产品
            getDistributorCalendarProduct(distributorProduct, useDate);
            respDTO.setSalePrice(distributorProduct.getSalePrice());

            List<DistributorProjectDO> distributorProjectList = distributorProjectMapper.selectList(DistributorProjectDO::getDistributorProductId, distributorProduct.getId(),
                    DistributorProjectDO::getDistributorId, distributorProduct.getDistributorId());
            List<DistributorProductRespDTO.DistributorProjectDTO> distributorProjectDTOList = BeanUtils.toBean(distributorProjectList, DistributorProductRespDTO.DistributorProjectDTO.class);
            respDTO.setDistributorProjectList(distributorProjectDTOList);
        } else {
            //旅行社分销产品价格
            DistributorAgencyPriceDO distributorAgencyPriceDO = new DistributorAgencyPriceDO();
            distributorAgencyPriceDO.setDistributorProductId(distributorProductId);
            List<DistributorAgencyPriceDO> distributorAgencyPriceList = distributorAgencyPriceMapper.getDistributorCalendarAgencyPriceList(distributorAgencyPriceDO, useDate);
            respDTO.setDistributorAgencyPriceList(BeanUtils.toBean(distributorAgencyPriceList, DistributorAgencyPriceDTO.class));
        }

        return CommonResult.success(respDTO);
    }

    @TenantIgnore
    @Override
    public CommonResult<DistributorProductRespDTO> getAgencyCalendarRangeProductById(Long distributorProductId, String startDate, String endDate) {

        DistributorProductDO distributorProduct = this.getDistributorProduct(distributorProductId.toString());
        Asserts.isTrue(null != distributorProduct, "分销商产品信息不存在{}", distributorProductId);
        DistributorProductRespDTO respDTO = BeanUtils.toBean(distributorProduct, DistributorProductRespDTO.class);
        Asserts.isTrue(distributorProduct.getProductSkuId() == null,"此方法只用于旅行社分销商");

        //旅行社分销产品价格
        DistributorAgencyPriceDO distributorAgencyPriceDO = new DistributorAgencyPriceDO();
        distributorAgencyPriceDO.setDistributorProductId(distributorProductId);
        List<DistributorAgencyPriceDO> defaulAgencyPriceList = distributorAgencyPriceMapper.getDistributorAgencyPriceList(distributorAgencyPriceDO);
        Asserts.isTrue(CollUtil.isNotEmpty(defaulAgencyPriceList),"旅行社未配置当前产品价格");
        List<DistributorAgencyPriceDO> distributorAgencyPriceList = distributorAgencyPriceMapper.getDistributorCalendarRangeAgencyPriceList(distributorAgencyPriceDO, startDate,endDate);
        Date stDate = DateUtil.parseDate(startDate);
        Date edDate = DateUtil.parseDate(endDate);
        List<DistributorAgencyPriceDTO> agencyPriceDTOList = new ArrayList<>();
        while (stDate.compareTo(edDate)<=0) {
            //获取日历价
            final Date useDate = stDate;
            List<DistributorAgencyPriceDTO> priceList = distributorAgencyPriceList.stream().filter(agencyPriceDO -> {
                if (agencyPriceDO.getStartDate() != null && agencyPriceDO.getEndDate() != null) {
                    return DateUtil.isIn(useDate, agencyPriceDO.getStartDate(), agencyPriceDO.getEndDate());
                }
                return false;
            }).map(item -> {
                DistributorAgencyPriceDTO dto = BeanUtils.toBean(item, DistributorAgencyPriceDTO.class);
                dto.setUseDate(useDate);
                return dto;
            }).collect(Collectors.toList());

            if(CollUtil.isEmpty(priceList)) {
                //默认金额
                priceList = defaulAgencyPriceList.stream().map(item->{
                    DistributorAgencyPriceDTO dto = BeanUtils.toBean(item, DistributorAgencyPriceDTO.class);
                    dto.setUseDate(useDate);
                    return dto;
                }).collect(Collectors.toList());
            }

            agencyPriceDTOList.addAll(priceList);

            stDate = DateUtil.offsetDay(stDate, 1);
        }

        respDTO.setDistributorAgencyPriceList(agencyPriceDTOList);

        return CommonResult.success(respDTO);
    }

    @Override
    @TenantIgnore
    public List<DistributorProductRespDTO.DistributorProjectDTO> getProductByDistributor(Long distributorId, Long productId,String distributorProductId) {
        DistributorProjectDO params = new DistributorProjectDO();
        params.setDistributorId(distributorId);
        params.setProductId(productId);
        params.setDistributorProductId(distributorProductId);
        params.setIsUse(0);
        List<DistributorProjectDO> distributorProducts = distributorProjectMapper.getDistributorProjectList(params);
        if(distributorProducts!=null && distributorProducts.size()>0) {
            return BeanUtils.toBean(distributorProducts, DistributorProductRespDTO.DistributorProjectDTO.class);
        }else{
            return null;
        }
    }

    @Override
    public DistributorProductDO getDistributorCalendarProduct(DistributorProductDO distributorProduct, String useDate) {
        if (useDate == null) {
            return distributorProduct;
        }
        return distributorProduct;
    }

    /**
     * 同步产品
     * @param distributorProductList
     * @return
     */
    @Override
    public CommonResult<String> syncTicketSave(List<DistributorProductSaveReqVO> distributorProductList) {
        Map<String, List<DistributorProductSaveReqVO>> grouped = distributorProductList.stream()
                .collect(Collectors.groupingBy(vo ->
                        vo.getProductId() + "-" + vo.getDistributorId()
                ));

        grouped.forEach((key, vos) -> {
            String[] parts = key.split("-");
            Long productId = Long.parseLong(parts[0]);
            Long distributorId = Long.parseLong(parts[1]);


        });

        return CommonResult.success("同步成功");
    }

    @Override
    public void relationOtaInfo(DistributorProductSaveReqVO updateReqVO) {
        if (CollUtil.isNotEmpty(updateReqVO.getIdList())){
            LambdaUpdateWrapper<DistributorProductDO> updateWrapper =new  LambdaUpdateWrapper<DistributorProductDO>()
                    .in(DistributorProductDO::getId, updateReqVO.getIdList());
//                    .set(DistributorProductDO::getExternalAccountId, updateReqVO.getExternalAccountId())
//                    .set(DistributorProductDO::getExternalPoiIds, updateReqVO.getExternalCategoryId())
//                    .set(DistributorProductDO::getExternalCategoryId, updateReqVO.getExternalCategoryId());

            distributorProductMapper.update(null, updateWrapper);
        }
    }

    @Override
    public CommonResult<?> syncTicketQuery(List<DistributorProductSaveReqVO> distributorProductList) {
        Map<String, List<DistributorProductSaveReqVO>> grouped = distributorProductList.stream()
                .collect(Collectors.groupingBy(vo ->
                        vo.getProductId() + "-" + vo.getDistributorId()
                ));
        AtomicReference<String> resultMsg = new AtomicReference<>("");
        grouped.forEach((key, vos) -> {
            String[] parts = key.split("-");
            Long productId = Long.parseLong(parts[0]);
            Long distributorId = Long.parseLong(parts[1]);


        });
        if (StrUtil.isNotBlank(resultMsg.get())){
            return CommonResult.error(500,StrUtil.removeSuffix(resultMsg.get(), ","));
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult<?> syncTicketCalendarSave(List<DistributorProductSaveReqVO> distributorProductList) {
        // 按 productId + distributorId 分组
        Map<String, List<DistributorProductSaveReqVO>> grouped = distributorProductList.stream()
                .collect(Collectors.groupingBy(vo -> vo.getProductId() + "-" + vo.getDistributorId()));


        // 线程安全的消息收集器
        AtomicReference<String> resultMsg = new AtomicReference<>("");

        ExecutorService executor = ThreadUtil.newExecutor(4);
        List<Future<?>> futures = new ArrayList<>();

        for (Map.Entry<String, List<DistributorProductSaveReqVO>> entry : grouped.entrySet()) {
            String key = entry.getKey();
            List<DistributorProductSaveReqVO> vos = entry.getValue();

            futures.add(executor.submit(() -> {
                try {
                    String[] parts = key.split("-");
                    Long productId = Long.parseLong(parts[0]);
                    Long distributorId = Long.parseLong(parts[1]);

                } catch (Exception e) {
                    synchronized (resultMsg) {
                        resultMsg.set(resultMsg.get() + "处理异常：" + e.getMessage() + ",");
                    }
                }
            }));
        }

        // 等待所有任务完成
        for (Future<?> future : futures) {
            try {
                future.get(); // 可加超时控制
            } catch (InterruptedException | ExecutionException e) {
                Thread.currentThread().interrupt();
                resultMsg.set(resultMsg.get() + "任务执行失败：" + e.getMessage() + ",");
            }
        }

        // 关闭线程池
        safeShutdown(executor,10,TimeUnit.SECONDS);

        // 返回结果
        if (StrUtil.isNotBlank(resultMsg.get())) {
            return CommonResult.error(500, StrUtil.removeSuffix(resultMsg.get(), ","));
        }
        return CommonResult.success(null);
    }

    @Override
    public CommonResult<?> syncProductOperate(List<DistributorProductSaveReqVO> distributorProductList) {
        Map<String, List<DistributorProductSaveReqVO>> grouped = distributorProductList.stream()
                .collect(Collectors.groupingBy(vo ->
                        vo.getProductId() + "-" + vo.getDistributorId()
                ));
        AtomicReference<String> resultMsg = new AtomicReference<>("");
        grouped.forEach((key, vos) -> {
            String[] parts = key.split("-");
            Long productId = Long.parseLong(parts[0]);
            Long distributorId = Long.parseLong(parts[1]);


        });

        if (StrUtil.isNotBlank(resultMsg.get())){
            return CommonResult.error(500,StrUtil.removeSuffix(resultMsg.get(), ","));
        }
        return CommonResult.success(null);
    }

    private void safeShutdown(ExecutorService executor, long timeout, TimeUnit unit) {
        if (executor == null || executor.isTerminated()) {
            return;
        }
        executor.shutdown();
        try {
            // 尝试等待所有任务完成
            if (!executor.awaitTermination(timeout, unit)) {
                // 超时后强制中断正在执行的任务
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            // 中断当前线程
            executor.shutdownNow();
            Thread.currentThread().interrupt(); // 重新设置中断标志
        }
    }
}
