package com.ximai.mes.pro.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ximai.common.constant.UserConstants;
import com.ximai.common.core.domain.entity.MdItemType;
import com.ximai.common.exception.ServiceException;
import com.ximai.common.utils.data.ExceptionUtil;
import com.ximai.common.utils.data.StringUtils;
import com.ximai.mes.constant.MdItemConst;
import com.ximai.mes.constant.WorkorderHastily;
import com.ximai.mes.constant.WorkorderStatusEnum;
import com.ximai.mes.md.domain.MdItem;
import com.ximai.mes.md.mapper.ItemTypeMapper;
import com.ximai.mes.md.mapper.MdItemMapper;
import com.ximai.mes.pro.domain.ProCombination;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkOrderDtaRecord;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkOrderSoDirective;
import com.ximai.mes.pro.domain.proWorkOrder.ProWorkorder;
import com.ximai.mes.pro.domain.productionSolution.ProProductionSolutionSpecificationSheet;
import com.ximai.mes.pro.domain.vo.ProWorkorderMateVo;
import com.ximai.mes.pro.mapper.ProCombinationMapper;
import com.ximai.mes.pro.mapper.proWorkOrder.ProWorkOrderSoDirectiveMapper;
import com.ximai.mes.pro.mapper.proWorkOrder.ProWorkorderMapper;
import com.ximai.mes.pro.mapper.productionSolution.ProProductionSolutionMapper;
import com.ximai.mes.pro.service.IProCombinationService;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkOrderDtaRecordService;
import com.ximai.mes.pro.service.proWorkOrder.IProWorkorderService;
import com.ximai.system.strategy.AutoCodeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 生产组合单Service业务层处理
 *
 * @author generator
 * @date 2024-02-28
 */
@Service
public class ProCombinationServiceImpl implements IProCombinationService {
    @Autowired
    private ProCombinationMapper proCombinationMapper;

    @Autowired
    private AutoCodeUtil autoCodeUtil;

    @Autowired
    private ProWorkorderMapper proWorkorderMapper;

    @Autowired
    private IProWorkorderService proWorkorderService;

    @Autowired
    private MdItemMapper mdItemMapper;

    @Resource
    private ProWorkOrderSoDirectiveMapper proWorkOrderSoDirectiveMapper;

    @Autowired
    private IProWorkOrderDtaRecordService proWorkOrderDtoRecordService;

    @Autowired
    private ProProductionSolutionMapper proProductionSolutionMapper;

    @Autowired
    private ItemTypeMapper itemTypeMapper;

    /**
     * 查询生产组合单
     *
     * @param combinationId 生产组合单主键
     * @return 生产组合单
     */
    @Override
    public ProCombination selectProCombinationByCombinationId(Long combinationId) {
        return proCombinationMapper.selectProCombinationByCombinationId(combinationId);
    }

    /**
     * 查询生产组合单列表
     *
     * @param proCombination 生产组合单
     * @return 生产组合单
     */
    @Override
    public List<ProCombination> selectProCombinationList(ProCombination proCombination) {
        return proCombinationMapper.selectProCombinationList(proCombination);
    }


    /**
     * 查询生产组合单列表
     *
     * @param proCombination 生产组合单
     * @return 生产组合单
     */
    @Override
    public List<ProCombination> selectProCombList(ProCombination proCombination) {
        return proCombinationMapper.selectProCombList(proCombination);
    }

    /**
     * 新增生产组合单
     *
     * @param proCombination 生产组合单
     * @return 结果
     */
    @Override
    public int insertProCombination(ProCombination proCombination) {
        proCombination.createAction();
        return proCombinationMapper.insertProCombination(proCombination);
    }

    @Override
    public List<String> batchAddProCombination(List<ProCombination> proCombinations) {
        proCombinations.forEach(s -> {
            ProWorkorder proWorkorder = proWorkorderMapper.selectById(s.getWorkorderId());
            if (!WorkorderStatusEnum.PUBLISHED.getValue().equals(proWorkorder.getStatus())) {
                throw new ServiceException(String.format("%s工单未做刀模板具检查，请先执行刀模板检查功能", proWorkorder.getWorkorderCode()));
            }
        });

        Long[] workorderArr = proCombinations.stream()
                .map(ProCombination::getWorkorderId)
                .toArray(Long[]::new);

        List<String> workorderIds = proCombinationMapper.selectProCombinationInWorkorderGroup(workorderArr);
        List<String> combinationCodes = new ArrayList<>();
        if (proCombinations.get(0) != null && proCombinations.get(0).getCombinationCode() != null && !"".equals(proCombinations.get(0).getCombinationCode()) && workorderIds.size() > 1) {
            throw new RuntimeException("不允许组合！");
        }

        if (workorderIds.size() == 0) {
            for (Long l : workorderArr) {
                workorderIds.add(String.valueOf(l));
            }
        }

        for (int i = 0; i < workorderIds.size(); i++) {
            List<Long> workorderIdArr = Arrays.stream(workorderIds.get(i).split(","))
                    .map(Long::valueOf)
                    .collect(Collectors.toList());

            List<ProCombination> matchedCombinations = proCombinations.stream()
                    .filter(combination -> workorderIdArr.contains(combination.getWorkorderId()))
                    .collect(Collectors.toList());

            String combinationCode = "";
            for (int j = 0; j < matchedCombinations.size(); j++) {
                ProCombination proCombination = matchedCombinations.get(j);
                ProWorkorder proWorkorder = proWorkorderMapper.selectById(proCombination.getWorkorderId());
                if (!WorkorderStatusEnum.PUBLISHED.getValue().equals(proWorkorder.getStatus())) {
                    throw new ServiceException(String.format("%s工单未做刀模板具检查，请先执行刀模板检查功能", proWorkorder.getWorkorderCode()));
                }

                if (proCombination.getCombinationCode() == null) {
                    if (Objects.equals(combinationCode, "")) {
                        combinationCode = autoCodeUtil.genSerialCode(UserConstants.COMBINATION_CODE, "");
                    }
                    proCombination.setCombinationCode(combinationCode);
                    if (!combinationCodes.contains(combinationCode)) {
                        combinationCodes.add(combinationCode);
                    }
                }

                proWorkorderMapper.updateWorkorderStatus(proCombination.getWorkorderId(), WorkorderStatusEnum.COMBINED.getValue());
                if (proCombination.getCombinationId() == null) {
                    this.insertProCombination(proCombination);
                    proWorkorder.setCombinationStartTime(proCombination.getCreateTime());

                    createDtaRecord(proWorkorder);
                } else {
                    this.updateProCombination(proCombination);
                }
            }
        }
        return combinationCodes;

    }

    @Transactional
    @Override
    public List<String> batchAddProCombinationV2(List<ProCombination> proCombinations) {
        proCombinations.forEach(proCombination -> {
            ExceptionUtil.checkTrueThrowException(proCombination != null && proCombination.getCombinationCode() != null && !"".equals(proCombination.getCombinationCode()), "已经组合,不允许操作！");

            ProWorkorder proWorkorder = proWorkorderMapper.selectById(proCombination.getWorkorderId());
            ExceptionUtil.checkTrueThrowException(!WorkorderStatusEnum.PUBLISHED.getValue().equals(proWorkorder.getStatus()), String.format("工单:%s,未做刀模版具检查，请先执行刀模版检查功能", proWorkorder.getWorkorderCode()));
        });
        List<String> combinationCodes = new ArrayList<>();
        if(proCombinations.size()==1){
            String s = autoCodeUtil.genSerialCode(UserConstants.COMBINATION_CODE, "");
            Long i=1L;
            for (ProCombination combination : proCombinations) {
                ProWorkorder proWorkorder = proWorkorderMapper.selectById(combination.getWorkorderId());
                ExceptionUtil.checkTrueThrowException(!WorkorderStatusEnum.PUBLISHED.getValue().equals(proWorkorder.getStatus()), String.format("工单:%s,未做刀模版具检查，请先执行刀模版检查功能", proWorkorder.getWorkorderCode()));
                combination.setCombinationSort(i);
                combination.setCombinationCode(s);
                this.insertProCombination(combination);
                proWorkorder.setCombinationStartTime(combination.getCreateTime());
                createDtaRecord(proWorkorder);
                proWorkorderMapper.updateWorkorderStatus(combination.getWorkorderId(), WorkorderStatusEnum.COMBINED.getValue());
            }
            combinationCodes.add(s);
        }else{
            //急单
            List<ProCombination> proCombinationWorry  = new ArrayList<>();
            //不急单
            List<ProCombination> proCombination1  = new ArrayList<>();
            //获取生产工单的匹配数据和印张数
            for (ProCombination proCombinationsa : proCombinations) {
                ProWorkorderMateVo proWorkorderMateVo = proWorkorderMapper.selectproWorkOrderSoDirective(proCombinationsa.getWorkorderId());
                ProWorkorder proWorkorder = proWorkorderMapper.selectById(proCombinationsa);
                ProProductionSolutionSpecificationSheet specificationSheet = proProductionSolutionMapper.selectModule(proWorkorderMateVo.getGroupCounter());
                Long modules = specificationSheet.getModule();
                BigDecimal module = new BigDecimal(modules);
                ExceptionUtil.checkTrueThrowException(StringUtils.isEmpty(module)|| module.compareTo(BigDecimal.ZERO)<=0 ,String.format("组键值:%s,的模数值错误", proWorkorderMateVo.getGroupCounter()));
                BigDecimal quantity = proWorkorderMateVo.getQuantity();
                BigDecimal divide = quantity.divide(module, 2, RoundingMode.HALF_UP);
                proWorkorderMateVo.setQuantity(BigDecimal.ZERO);
                proCombinationsa.setMatching(proWorkorderMateVo);
                proCombinationsa.setFrame(divide);
                proCombinationsa.setRequestDate(proWorkorder.getRequestDate());
                String rushOrder = proCombinationsa.getMatching().getRushOrder();
                if(!rushOrder.equals(WorkorderHastily.HASTILY)){
                    proCombination1.add(proCombinationsa);
                }else{
                    proCombinationWorry.add(proCombinationsa);
                }
            }
            //不急单数据处理
            int sort2 = 1;
            for (ProCombination proCombination : proCombination1) {
                List<ProCombination> combina = new ArrayList<>();
                if(StringUtils.isNotEmpty(proCombination.getCombinationCode())){
                    sort2++;
                    continue;
                }
                BigDecimal big = BigDecimal.ZERO;
                proCombination.setX(0);
                combina.add(proCombination);
                String s = autoCodeUtil.genSerialCode(UserConstants.COMBINATION_CODE, "");
                big=big.add(proCombination.getFrame());
                for(int i = sort2 ; i<proCombination1.size(); i++){
                    ProWorkorderMateVo matching = proCombination1.get(i).getMatching();
                    ProWorkorderMateVo matching1 = proCombination.getMatching();
                    ExceptionUtil.checkTrueThrowException(StringUtils.isEmpty(matching.getTypeNo())&&StringUtils.isEmpty(matching.getColorNo())&&StringUtils.isEmpty(matching.getProdUsage()),String.format("工单:%s,的型体号、配色号、产品用途数据为空", proCombination1.get(i).getWorkorderCode()));
                    ExceptionUtil.checkTrueThrowException(StringUtils.isEmpty(matching1.getTypeNo())&&StringUtils.isEmpty(matching1.getColorNo())&&StringUtils.isEmpty(matching1.getProdUsage()),String.format("工单:%s,的型体号、配色号、产品用途数据为空", proCombination.getWorkorderCode()));
                    if(matching.equals(matching1)){
                        big = big.add(proCombination1.get(i).getFrame());
                        MdItem mdItem = mdItemMapper.selectMdItemBySapItemCode(matching.getProductCode());
                        MdItemType mdItemType = itemTypeMapper.selectItemTypeCode(mdItem.getItemTypeCode());
                        BigDecimal MaximumSingle = null;
                        if(StringUtils.isNotEmpty(mdItemType.getMaximumMeters()) && mdItemType.getMaximumMeters().compareTo(BigDecimal.ZERO)>0){
                            ProProductionSolutionSpecificationSheet printingPaperlenths = proProductionSolutionMapper.selectModule(matching.getGroupCounter());
                            BigDecimal printingPaperlenth = printingPaperlenths.getPrintingPaperlenth();
                            ExceptionUtil.checkTrueThrowException(StringUtils.isEmpty(printingPaperlenth)|| printingPaperlenth.compareTo(BigDecimal.ZERO)<=0 ,String.format("组键值:%s,的印张长度值错误", matching.getGroupCounter()));
                            MaximumSingle = mdItemType.getMaximumMeters().divide(printingPaperlenth, 2, RoundingMode.HALF_UP);
                        }else{
                            ExceptionUtil.checkTrueThrowException(StringUtils.isEmpty(mdItemType.getMaximumSingle())|| mdItemType.getMaximumSingle().compareTo(BigDecimal.ZERO)<=0 ,String.format("物料分类:(%s)  的最大米数、最大印张数没有设置，请在物料分类界面修的改功能上设置", mdItemType.getItemTypeName()));
                            MaximumSingle =  mdItemType.getMaximumSingle();
                        }
                        if(big.compareTo(MaximumSingle)<=0){
                            proCombination1.get(i).setX(i);
                            combina.add(proCombination1.get(i));
                        }else{
                            big = big.subtract(proCombination1.get(i).getFrame());
                        }
                    }
                }
                Long i=1L;
                for (ProCombination combination : combina) {
                    ProWorkorder proWorkorder = proWorkorderMapper.selectById(combination.getWorkorderId());
                    ExceptionUtil.checkTrueThrowException(!WorkorderStatusEnum.PUBLISHED.getValue().equals(proWorkorder.getStatus()), String.format("工单:%s,未做刀模版具检查，请先执行刀模版检查功能", proWorkorder.getWorkorderCode()));
                    combination.setCombinationSort(i);
                    combination.setCombinationCode(s);
                    proCombination1.get(combination.getX()).setCombinationCode(s);
                    this.insertProCombination(combination);
                    proWorkorder.setCombinationStartTime(combination.getCreateTime());
                    createDtaRecord(proWorkorder);
                    proWorkorderMapper.updateWorkorderStatus(combination.getWorkorderId(), WorkorderStatusEnum.COMBINED.getValue());
                    i++;
                }
                combinationCodes.add(s);
                sort2++;
            }

            //急单数据处理
            int sort3 = 1;
            for (ProCombination proCombination : proCombinationWorry) {
                List<ProCombination> combina = new ArrayList<>();
                if(StringUtils.isNotEmpty(proCombination.getCombinationCode())){
                    sort3++;
                    continue;
                }
                BigDecimal big = BigDecimal.ZERO;
                proCombination.setX(0);
                combina.add(proCombination);
                String s = autoCodeUtil.genSerialCode(UserConstants.COMBINATION_CODE, "");
                big=big.add(proCombination.getFrame());
                for(int i = sort3 ; i<proCombinationWorry.size(); i++){
                    boolean a=true;
                    ProWorkorderMateVo matching = proCombinationWorry.get(i).getMatching();
                    ProWorkorderMateVo matching1 = proCombination.getMatching();
                    //截取日期
                    Date requestDate = proCombinationWorry.get(i).getRequestDate();
                    Date requestDate1 = proCombination.getRequestDate();
                    LocalTime localTime2 = requestDate.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
                    LocalTime localTime3 = requestDate1.toInstant().atZone(ZoneId.systemDefault()).toLocalTime();
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    String format = simpleDateFormat.format(requestDate);
                    String format1 = simpleDateFormat.format(requestDate1);
                    ExceptionUtil.checkTrueThrowException(StringUtils.isEmpty(matching.getTypeNo())&&StringUtils.isEmpty(matching.getColorNo())&&StringUtils.isEmpty(matching.getProdUsage()),String.format("工单:%s,的型体号、配号、产品用途数据为空", proCombinationWorry.get(i).getWorkorderCode()));
                    ExceptionUtil.checkTrueThrowException(StringUtils.isEmpty(matching1.getTypeNo())&&StringUtils.isEmpty(matching1.getColorNo())&&StringUtils.isEmpty(matching1.getProdUsage()),String.format("工单:%s,的型体号、配号、产品用途数据为空", proCombination.getWorkorderCode()));
                    if(matching.equals(matching1)){
                        big = big.add(proCombinationWorry.get(i).getFrame());
                        MdItem mdItem = mdItemMapper.selectMdItemBySapItemCode(matching.getProductCode());
                        MdItemType mdItemType = itemTypeMapper.selectItemTypeCode(mdItem.getItemTypeCode());
                        BigDecimal MaximumSingle = null;
                        if(StringUtils.isNotEmpty(mdItemType.getMaximumMeters()) && mdItemType.getMaximumMeters().compareTo(BigDecimal.ZERO)>0){
                            ProProductionSolutionSpecificationSheet printingPaperlenths = proProductionSolutionMapper.selectModule(matching.getGroupCounter());
                            BigDecimal printingPaperlenth = printingPaperlenths.getPrintingPaperlenth();
                            ExceptionUtil.checkTrueThrowException(StringUtils.isEmpty(printingPaperlenth)|| printingPaperlenth.compareTo(BigDecimal.ZERO)<=0 ,String.format("组键值:%s,的印张长度值错误", matching.getGroupCounter()));
                            MaximumSingle = mdItemType.getMaximumMeters().divide(printingPaperlenth, 2, RoundingMode.HALF_UP);
                        }else{
                            ExceptionUtil.checkTrueThrowException(StringUtils.isEmpty(mdItemType.getMaximumSingle())|| mdItemType.getMaximumSingle().compareTo(BigDecimal.ZERO)<=0 ,String.format("物料分类:%s 、的最大米数、最大印张数没有设置，请在物料分类界面修的改功能上设置", mdItemType.getItemTypeName()));
                            MaximumSingle =  mdItemType.getMaximumSingle();
                        }
                        if(big.compareTo(MaximumSingle)<=0){
                            //判断是否同一天
                            if(format.equals(format1)){
                                //7.30-10.00
                                LocalTime localTime = LocalTime.of(7, 30);
                                LocalTime localTime1 = LocalTime.of(10, 0);
                                if( ChronoUnit.MINUTES.between(localTime, localTime2) >= 0 &&
                                        ChronoUnit.MINUTES.between(localTime2, localTime1) >= 0) {
                                    if (ChronoUnit.MINUTES.between(localTime, localTime3) >= 0 &&
                                            ChronoUnit.MINUTES.between(localTime3, localTime1) >= 0) {
                                        proCombinationWorry.get(i).setX(i);
                                        combina.add(proCombinationWorry.get(i));
                                        a=false;
                                    }
                                }

                                //10.00-16.00
                                LocalTime localTimea = LocalTime.of(10, 0);
                                LocalTime localTimea1 = LocalTime.of(16, 0);
                                if( ChronoUnit.MINUTES.between(localTimea, localTime2) >= 0 &&
                                        ChronoUnit.MINUTES.between(localTime2, localTimea1) >= 0) {

                                    if (ChronoUnit.MINUTES.between(localTimea, localTime3) >= 0 &&
                                            ChronoUnit.MINUTES.between(localTime3, localTimea1) >= 0) {

                                        proCombinationWorry.get(i).setX(i);
                                        combina.add(proCombinationWorry.get(i));
                                        a=false;
                                    }
                                }

                                //16.00-19.00
                                LocalTime localTimeas = LocalTime.of(16, 0);
                                LocalTime localTimeas1 = LocalTime.of(19, 0);
                                if( ChronoUnit.MINUTES.between(localTimeas, localTime2) >= 0 &&
                                        ChronoUnit.MINUTES.between(localTime2, localTimeas1) >= 0) {

                                    if (ChronoUnit.MINUTES.between(localTimeas, localTime3) >= 0 &&
                                            ChronoUnit.MINUTES.between(localTime3, localTimeas1) >= 0) {

                                        proCombinationWorry.get(i).setX(i);
                                        combina.add(proCombinationWorry.get(i));
                                        a=false;
                                    }
                                }


                            }
                        }
                        if(a){
                            //扣减数量
                            big = big.subtract(proCombinationWorry.get(i).getFrame());
                        }
                    }
                }
                Long i=1L;
                for (ProCombination combination : combina) {
                    ProWorkorder proWorkorder = proWorkorderMapper.selectById(combination.getWorkorderId());
                    ExceptionUtil.checkTrueThrowException(!WorkorderStatusEnum.PUBLISHED.getValue().equals(proWorkorder.getStatus()), String.format("工单:%s,未做刀模版具检查，请先执行刀模版检查功能", proWorkorder.getWorkorderCode()));
                    combination.setCombinationSort(i);
                    combination.setCombinationCode(s);
                    proCombinationWorry.get(combination.getX()).setCombinationCode(s);
                    this.insertProCombination(combination);
                    proWorkorder.setCombinationStartTime(combination.getCreateTime());
                    createDtaRecord(proWorkorder);
                    proWorkorderMapper.updateWorkorderStatus(combination.getWorkorderId(), WorkorderStatusEnum.COMBINED.getValue());
                    i++;
                }
                combinationCodes.add(s);
                sort3++;
            }
        }







        //============老组合逻辑====================
        // 数据分组
//        Long[] workorderArr = proCombinations.stream()
//                .map(ProCombination::getWorkorderId)
//                .toArray(Long[]::new);
//        List<String> workorderIdsStr = proCombinationMapper.selectProCombinationInWorkorderGroup(workorderArr);
//        Map<Integer, List<List<Long>>> map = new HashMap<>();
//        List<List<Long>> IdCollList = new ArrayList<>();
//        if (CollectionUtil.isNotEmpty(workorderIdsStr)) {
//            Set<String> disIdss = new HashSet<>();
//            for (String s : workorderIdsStr) {
//                List<Long> ids = Arrays.stream(s.split(","))
//                        .map(Long::valueOf)
//                        .sorted()
//                        .collect(Collectors.toList());
//                String idsStr = ids.stream().map(x -> DataUtil.getNormalData(x, String.class)).filter(StringUtils::isNotEmpty).collect(Collectors.joining());
//                if (disIdss.add(idsStr)) {
//                    int size = ids.size();
//                    if (size > 1) {
//                        IdCollList.add(ids);
//                    }
//                }
//            }
//        }
//
//        for (List<Long> allId : IdCollList) {
//            int size = allId.size();
//            List<List<Long>> lists = map.get(size);
//            if (lists == null) {
//                lists = new ArrayList<>();
//                lists.add(allId);
//            } else {
//                lists.add(allId);
//            }
//
//            map.put(size, lists);
//        }
//
//
//        Set<Long> level1Set1 = proCombinations.stream().map(ProCombination::getWorkorderId).filter(Objects::nonNull).collect(Collectors.toSet());
//        Set<Long> level1Set2 = new HashSet<>();
//        if (CollectionUtil.isNotEmpty(map)) {
//            for (Long l : level1Set1) {
//                for (Map.Entry<Integer, List<List<Long>>> entry : map.entrySet()) {
//                    List<List<Long>> value = entry.getValue();
//                    boolean flag = false;
//
//                    for (List<Long> longs : value) {
//                        if (longs.contains(l)) {
//                            flag = true;
//                            break;
//                        }
//                    }
//
//                    if (!flag) {
//                        level1Set2.add(l);
//                    }
//                }
//            }
//
//            for (Long l : level1Set2) {
//                List<List<Long>> lists = map.get(1);
//                if (lists == null) {
//                    lists = new ArrayList<>();
//                }
//
//                List<Long> objects = new ArrayList<>();
//                objects.add(l);
//                lists.add(objects);
//                map.put(1, lists);
//            }
//        } else {
//            for (Long l : level1Set1) {
//
//                List<List<Long>> lists = map.get(1);
//                if (lists == null) {
//                    lists = new ArrayList<>();
//                }
//
//                List<Long> objects = new ArrayList<>();
//                objects.add(l);
//                lists.add(objects);
//                map.put(1, lists);
//            }
//        }


//        ExceptionUtil.throwExcetion("error");

//        List<String> combinationCodes = new ArrayList<>();
//        for (Map.Entry<Integer, List<List<Long>>> entry : map.entrySet()) {
//            List<List<Long>> combinationList = entry.getValue();
//            for (List<Long> combinationIds : combinationList) {
//                List<ProCombination> matchedCombinations = proCombinations.stream()
//                        .filter(combination -> combinationIds.contains(combination.getWorkorderId()))
//                        .collect(Collectors.toList());
//
//                String combinationCode = "";
//                Long sort = 1L;
//                for (ProCombination proCombination : matchedCombinations) {
//                    ProWorkorder proWorkorder = proWorkorderMapper.selectById(proCombination.getWorkorderId());
//                    ExceptionUtil.checkTrueThrowException(!WorkorderStatusEnum.PUBLISHED.getValue().equals(proWorkorder.getStatus()), String.format("工单:%s,未做刀模版具检查，请先执行刀模版检查功能", proWorkorder.getWorkorderCode()));
//
//
//                    if (proCombination.getCombinationCode() == null) {
//                        if (Objects.equals(combinationCode, "")) {
//                            combinationCode = autoCodeUtil.genSerialCode(UserConstants.COMBINATION_CODE, "");
//                        }
//
//                        proCombination.setCombinationCode(combinationCode);
//                        if (!combinationCodes.contains(combinationCode)) {
//                            combinationCodes.add(combinationCode);
//                        }
//                    }
//
//
//                    if (proCombination.getCombinationId() == null) {
//                        proCombination.setCombinationSort(sort);
//                        this.insertProCombination(proCombination);
//                        proWorkorder.setCombinationStartTime(proCombination.getCreateTime());
//
//                        createDtaRecord(proWorkorder);
//                        sort++;
//                    } else {
//                        this.updateProCombination(proCombination);
//                    }
//
//                    proWorkorderMapper.updateWorkorderStatus(proCombination.getWorkorderId(), WorkorderStatusEnum.COMBINED.getValue());
//                }
//            }
//        }

        return combinationCodes;
    }


    // 根据item 生成dta记录
    private void createDtaRecord(ProWorkorder proWorkorder) {
        ExceptionUtil.checkTrueThrowException(proWorkorder.getProductId() == null, "当前工单无法找到物料信息");

        Long productId = proWorkorder.getProductId();
        QueryWrapper<MdItem> qw1 = new QueryWrapper<>();
        qw1.eq("item_id", productId);
        List<MdItem> mdItems = mdItemMapper.selectListByQw(qw1);
        ExceptionUtil.checkTrueThrowException(CollectionUtil.isEmpty(mdItems), "当前工单无法找到物料信息");

        MdItem mdItem = mdItems.get(0);

        if (Objects.equals(mdItem.getDta(), MdItemConst.TURN_ON_DTO_LAYOUT)) {
            QueryWrapper<ProWorkOrderSoDirective> qw2 = new QueryWrapper<>();
            qw2.eq("workorder_id", proWorkorder.getWorkorderId());
            List<ProWorkOrderSoDirective> proWorkOrderSoDirectives = proWorkOrderSoDirectiveMapper.selectListByQw(qw2);
            // 多指令号是固定工单,不需要考虑dta排版
            if (proWorkOrderSoDirectives.size() == 1) {
                ProWorkOrderDtaRecord proWorkOrderDtaRecord = new ProWorkOrderDtaRecord();
                proWorkOrderDtaRecord.setWorkorderId(proWorkorder.getWorkorderId());
                proWorkOrderDtaRecord.setWorkorderCode(proWorkorder.getWorkorderCode());
                proWorkOrderDtaRecord.setSaleCode(proWorkOrderSoDirectives.get(0).getSalesVoucher());
                proWorkOrderDtaRecord.setItemId(mdItem.getItemId());
                proWorkOrderDtaRecord.setSapItemCode(mdItem.getSapItemCode());
                proWorkOrderDtaRecord.setItemName(mdItem.getItemName());
                proWorkOrderDtaRecord.setStartTime(proWorkorder.getCombinationStartTime());
                proWorkOrderDtaRecord.setEndTime(null);
                proWorkOrderDtoRecordService.insertProWorkOrderDtoRecord(proWorkOrderDtaRecord);
            }
        }
    }

    /**
     * 修改生产组合单
     *
     * @param proCombination 生产组合单
     * @return 结果
     */
    @Override
    public int updateProCombination(ProCombination proCombination) {
        return proCombinationMapper.updateProCombination(proCombination);
    }

    /**
     * 批量删除生产组合单
     *
     * @param workorderIds 需要删除的生产组合单主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteProCombinationByWorkorderIds(Long[] workorderIds) {
        List<Long> list = Arrays.asList(workorderIds);
        ExceptionUtil.checkTrueThrowException(CollectionUtil.isEmpty(list), JSON.toJSONString(list) + ",工单非已组合，不能进行取消组合操作");
        List<ProWorkorder> proWorkorders = proWorkorderMapper.selectListByQw(new QueryWrapper<ProWorkorder>().in("workorder_id", list));

        Set<String> collect = new HashSet<>();
        Set<String> error = new HashSet<>();
        if (CollectionUtil.isNotEmpty(proWorkorders)) {
            for (ProWorkorder proWorkorder : proWorkorders) {
                if (Objects.equals(proWorkorder.getStatus(), WorkorderStatusEnum.COMBINED.getValue())) {
                    proWorkorder.setStatus(WorkorderStatusEnum.PUBLISHED.getValue());
                    proWorkorder.setCombinationCode(null);
                    proWorkorder.setCombinationStartTime(null);
                    proWorkorderService.updateProWorkorder(proWorkorder);
                    collect.add(proWorkorder.getWorkorderCode());
                } else {
                    error.add(proWorkorder.getWorkorderCode());
                }
            }
            ExceptionUtil.checkTrueThrowException(collect.size() != proWorkorders.size(), JSON.toJSONString(error) + ",工单非已组合，不能进行取消组合操作");
        }

        proCombinationMapper.deleteProCombination(new QueryWrapper<ProCombination>().in("workorder_code", collect));
        return 1;
    }

    /**
     * 删除生产组合单信息
     *
     * @param combinationId 生产组合单主键
     * @return 结果
     */
    @Override
    public int deleteProCombinationByCombinationId(Long combinationId) {
        ProCombination proCombination = proCombinationMapper.selectProCombinationByCombinationId(combinationId);
        proWorkorderMapper.updateWorkorderStatus(proCombination.getWorkorderId(), WorkorderStatusEnum.PUBLISHED.getValue());
        return proCombinationMapper.deleteProCombinationByCombinationId(combinationId);
    }
}
