package com.xisc.pm.app.service.impl;

import com.xisc.pm.api.dto.PmRuntimeContractAppointDTO;
import com.xisc.pm.api.dto.PmRuntimeContractChangeDTO;
import com.xisc.pm.api.dto.PmRuntimeContractLengthDTO;
import com.xisc.pm.api.dto.PmRuntimeContractLineDTO;
import com.xisc.pm.api.dto.PmRuntimeContractLineReqDTO;
import com.xisc.pm.api.dto.PmRuntimeContractMoldDTO;
import com.xisc.pm.api.dto.PmRuntimeContractReqDTO;
import com.xisc.pm.api.dto.PmRuntimeContractResDTO;
import com.xisc.pm.api.dto.PmRuntimeContractThickDTO;
import com.xisc.pm.api.dto.PmRuntimeContractWidthDTO;
import com.xisc.pm.api.dto.PmSpecTableColumnRangeDTO;
import com.xisc.pm.app.service.PmSpecTableColumnService;
import com.xisc.pm.domain.entity.PmContMscTech;
import com.xisc.pm.domain.entity.PmContractLineSpec;
import com.xisc.pm.domain.entity.PmProContProdTtr;
import com.xisc.pm.domain.entity.PmProductionLine;
import com.xisc.pm.domain.entity.PmSpecTableColumn;
import com.xisc.pm.domain.entity.PmSteelTypeGroup;
import com.xisc.pm.domain.repository.PmContMscTechRepository;
import com.xisc.pm.domain.repository.PmContractLineSpecRepository;
import com.xisc.pm.domain.repository.PmProContProdAttrRepository;
import com.xisc.pm.domain.repository.PmProductionLineRepository;
import com.xisc.pm.domain.repository.PmSpecTableColumnRepository;
import com.xisc.pm.domain.repository.PmSteelTypeGroupRepository;
import com.xisc.pm.infra.mapper.PmContMscTechMapper;
import com.xisc.pm.infra.mapper.PmContractLineSpecMapper;
import com.xisc.pm.infra.mapper.PmProContProdTtrMapper;
import com.xisc.pm.infra.mapper.PmSpecTableColumnMapper;
import com.xisc.pm.infra.util.PageUtils;
import io.choerodon.core.domain.Page;
import io.choerodon.core.exception.CommonException;
import io.choerodon.mybatis.pagehelper.domain.PageRequest;
import org.apache.commons.collections.CollectionUtils;
import org.hzero.core.base.BaseConstants;
import org.hzero.mybatis.domian.Condition;
import org.hzero.mybatis.util.Sqls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 合同结构规格表(PmSpecTableColumn)应用服务
 *
 * @author 纪文桃 wentao.ji01@hand-china.com
 * @since 2024-10-12 09:10:24
 */
@Service
public class PmSpecTableColumnServiceImpl implements PmSpecTableColumnService {
    @Autowired
    private PmSpecTableColumnRepository pmSpecTableColumnRepository;


    @Autowired
    private PmSteelTypeGroupRepository pmSteelTypeGroupRepository;

    @Autowired
    private PmContractLineSpecRepository pmContractLineSpecRepository;

    @Autowired
    private PmProductionLineRepository pmProductionLineRepository;

    @Autowired
    private PmSpecTableColumnMapper pmSpecTableColumnMapper;

    @Autowired
    private PmProContProdAttrRepository pmProContProdAttrRepository;

    @Autowired
    private PmContMscTechRepository pmContMscTechRepository;

    @Autowired
    private PmContMscTechMapper pmContMscTechMapper;

    @Autowired
    private PmProContProdTtrMapper pmProContProdTtrMapper;

     @Autowired
    private PmContractLineSpecMapper pmContractLineSpecMapper;


    @Override
    public PmRuntimeContractResDTO selectList(PmRuntimeContractReqDTO dto, Long tenantId) {
        PmRuntimeContractResDTO result = new PmRuntimeContractResDTO();
        // 据选择的STEEL_GROUP_CODE，关联表pm_steel_type_group.STEEL_GROUP_CODE，获取ST_NO，
        if (CollectionUtils.isNotEmpty(dto.getSteelGroupCodeList())) {
            List<PmSteelTypeGroup> pmSteelTypeGroupList = pmSteelTypeGroupRepository.selectByCondition(Condition.builder(PmSteelTypeGroup.class)
                    .andWhere(Sqls.custom().andIn(PmSteelTypeGroup.FIELD_STEEL_GROUP_CODE, dto.getSteelGroupCodeList(), true))
                    .andWhere(Sqls.custom().andEqualTo(PmSteelTypeGroup.FIELD_TENANT_ID, tenantId))
                    .build());
            if (CollectionUtils.isNotEmpty(pmSteelTypeGroupList)) {
                List<String> stNoList = pmSteelTypeGroupList.stream().map(PmSteelTypeGroup::getStNo).distinct().collect(Collectors.toList());
                dto.getStNoList().addAll(stNoList);
            }
        }

        // 查询合同结构规格表
        List<PmSpecTableColumn> pmSpecTableColumnList = pmSpecTableColumnRepository.selectByCondition(Condition.builder(PmSpecTableColumn.class)
                .andWhere(Sqls.custom().andEqualTo(PmSpecTableColumn.FIELD_TENANT_ID, tenantId))
                .build());
        if (CollectionUtils.isEmpty(pmSpecTableColumnList)) {
            return result;
        }
        Optional<PmSpecTableColumn> widthOptional = pmSpecTableColumnList.stream().filter(item -> item.getWidFrom() == null || item.getWidTo() == null).findFirst();
        if (widthOptional.isPresent()) {
            throw new CommonException("pm.spec_table_column_003");
        }

        // 查询符合条件的合同号
        List<String> orderNoList =  pmSpecTableColumnMapper.selectOrderNoList(dto, tenantId);
        if (CollectionUtils.isEmpty(orderNoList)) {
            return result;
        }
        // 根据返回的合同号查询生产合同产品属性表数据
        List<PmProContProdTtr> pmProContProdTtrList = pmProContProdTtrMapper.queryList(orderNoList, tenantId);
        // 根据合同号查询对应钢种数据
        List<PmContMscTech> pmContMscTechList = pmContMscTechMapper.queryList(orderNoList, tenantId, null);
        // 获取合同和钢种的对应关系
        Map<String, String> pmContMscTechMap = pmContMscTechList.stream()
                .collect(Collectors.toMap(PmContMscTech::getOrderNo, PmContMscTech::getStNo, (v1, v2) -> v1));
        result.setStNoList(pmContMscTechList.stream().map(PmContMscTech::getStNo).distinct().collect(Collectors.toList()));

        // 按照厚度分组
        Map<String, List<PmSpecTableColumn>> pmLengthTableColumnMap = pmSpecTableColumnList.stream()
                .collect(Collectors.groupingBy(item -> item.getThickFrom() + item.getThickTo().toString()));

        List<PmRuntimeContractThickDTO> thickList = new ArrayList<>(pmSpecTableColumnList.size());
        for (Map.Entry<String, List<PmSpecTableColumn>> entry : pmLengthTableColumnMap.entrySet()) {
            // 每一组厚度信息
            PmRuntimeContractThickDTO thickDTO = new PmRuntimeContractThickDTO();
            thickDTO.setThickthFrom(entry.getValue().get(0).getThickFrom());
            thickDTO.setThickthTo(entry.getValue().get(0).getThickTo());
            thickList.add(thickDTO);

            Map<String, List<PmSpecTableColumn>> pmWidthColumnMap = entry.getValue().stream()
                    .collect(Collectors.groupingBy(item -> item.getWidFrom() + item.getWidTo().toString()));

            // 每一组厚度的宽度信息
            List<PmRuntimeContractWidthDTO> widthList = new ArrayList<>(entry.getValue().size());
            for (Map.Entry<String, List<PmSpecTableColumn>> widthEntry : pmWidthColumnMap.entrySet()) {

                PmRuntimeContractWidthDTO contractWidthDTO = new PmRuntimeContractWidthDTO();
                contractWidthDTO.setWidthFrom(widthEntry.getValue().get(0).getWidFrom());
                contractWidthDTO.setWidthTo(widthEntry.getValue().get(0).getWidTo());
                widthList.add(contractWidthDTO);

                // 是否勾选长度
                if (BaseConstants.FlagChar.YES.equals(dto.getIsLenth())) {
                    Optional<PmSpecTableColumn> lengthOptional = pmSpecTableColumnList.stream().filter(item -> item.getLengthFrom() == null || item.getLengthTo() == null).findFirst();
                    if (lengthOptional.isPresent()) {
                        throw new CommonException("m.spec_table_column_004");
                    }
                    List<PmRuntimeContractLengthDTO> lengthList = new ArrayList<>();
                    Map<String, PmSpecTableColumn> pmLengthColumnMap = widthEntry.getValue().stream()
                            .collect(Collectors.toMap(item -> item.getLengthFrom().toString() + item.getLengthTo().toString(), Function.identity()));
                    // 长度范围
                    for (Map.Entry<String, PmSpecTableColumn> lengthEntry : pmLengthColumnMap.entrySet()) {
                        PmRuntimeContractLengthDTO lengthDTO = new PmRuntimeContractLengthDTO();
                        lengthDTO.setLengthFrom(lengthEntry.getValue().getLengthFrom());
                        lengthDTO.setLengthTo(lengthEntry.getValue().getLengthTo());
                        lengthList.add(lengthDTO);

                        // 统计在该厚-宽-长范围内的合同重量
                        List<PmProContProdTtr> filterContProdTtrList = pmProContProdTtrList.stream().filter(item ->
                                item.getOrderThick().compareTo(lengthEntry.getValue().getThickFrom()) >= 0 &&
                                        item.getOrderThick().compareTo(lengthEntry.getValue().getThickTo()) <= 0 &&
                                        item.getOrderLen().compareTo(lengthEntry.getValue().getLengthFrom()) >= 0 &&
                                        item.getOrderLen().compareTo(lengthEntry.getValue().getLengthTo()) <= 0 &&
                                        item.getOrderWidth().compareTo(lengthEntry.getValue().getWidFrom()) >= 0 &&
                                        item.getOrderWidth().compareTo(lengthEntry.getValue().getWidTo()) <= 0).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(filterContProdTtrList)) {
                            Map<String, BigDecimal> filterContProdTtrMap = filterContProdTtrList.stream()
                                    .collect(Collectors.toMap(PmProContProdTtr::getOrderNo, PmProContProdTtr::getOrderWt));
                            Map<String, BigDecimal> stNoWtMap = new HashMap<>(filterContProdTtrList.size());
                            // 根据合同号替换对应的钢种号
                            for (Map.Entry<String, BigDecimal> trrEntry : filterContProdTtrMap.entrySet()) {
                                // 统计每个钢种的合同重量
                                String stNo = pmContMscTechMap.get(trrEntry.getKey());
                                BigDecimal wt = stNoWtMap.getOrDefault(stNo, BigDecimal.ZERO);
                                stNoWtMap.put(stNo, wt.add(trrEntry.getValue()));
                            }
                            lengthDTO.setOrderTotalWtMap(stNoWtMap);
                        }
                    }
                    contractWidthDTO.setLengthList(lengthList.stream().sorted(Comparator.comparing(PmRuntimeContractLengthDTO::getLengthFrom))
                            .collect(Collectors.toList()));
                } else {
                    List<PmProContProdTtr> filterContProdTtrList = pmProContProdTtrList.stream().filter(item ->
                                item.getOrderThick().compareTo(widthEntry.getValue().get(0).getThickFrom()) >= 0 &&
                                        item.getOrderThick().compareTo(widthEntry.getValue().get(0).getThickTo()) <= 0 &&
                                        item.getOrderWidth().compareTo(widthEntry.getValue().get(0).getWidFrom()) >= 0 &&
                                        item.getOrderWidth().compareTo(widthEntry.getValue().get(0).getWidTo()) <= 0)
                            .collect(Collectors.toList());
                    if (CollectionUtils.isNotEmpty(filterContProdTtrList)) {
                        Map<String, BigDecimal> filterContProdTtrMap = filterContProdTtrList.stream()
                                .collect(Collectors.toMap(PmProContProdTtr::getOrderNo, PmProContProdTtr::getOrderWt));
                        Map<String, BigDecimal> stNoWtMap = new HashMap<>(filterContProdTtrList.size());
                        // 根据合同号替换对应的钢种号
                        for (Map.Entry<String, BigDecimal> trrEntry : filterContProdTtrMap.entrySet()) {
                            // 统计每个钢种的合同重量
                            String stNo = pmContMscTechMap.get(trrEntry.getKey());
                            BigDecimal wt = stNoWtMap.getOrDefault(stNo, BigDecimal.ZERO);
                            stNoWtMap.put(stNo, wt.add(trrEntry.getValue()));
                        }
                        contractWidthDTO.setOrderTotalWtMap(stNoWtMap);
                    }
                }
            }
            thickDTO.setWidthList(widthList.stream().sorted(Comparator.comparing(PmRuntimeContractWidthDTO::getWidthFrom)).collect(Collectors.toList()));
        }
        result.setThickList(thickList.stream().sorted(Comparator.comparing(PmRuntimeContractThickDTO::getThickthFrom)).collect(Collectors.toList()));
        return result;
    }

    @Override
    public Page<PmRuntimeContractLineReqDTO> listLine(PmRuntimeContractLineDTO dto, Long tenantId, PageRequest pageRequest) {
        // 条件查询合同范围
        // 查询对应合同号
        List<String> orderNoList =  pmSpecTableColumnMapper.selectLineList(dto, tenantId);
        if (CollectionUtils.isEmpty(orderNoList)) {
            return new Page<>();
        }
        // 获取合同对应数据
        List<PmProContProdTtr> pmProContProdTtrList = pmProContProdTtrMapper.queryList(orderNoList, tenantId);
        // 根据合同号查询对应钢种数据
        List<PmContMscTech> pmContMscTechList = pmContMscTechMapper.queryList(orderNoList, tenantId, dto.getDesignProdLineCodeList());
        // 获取合同和钢种的对应关系
        Map<String, List<PmContMscTech>> pmContMscTechMap = pmContMscTechList.stream()
                .collect(Collectors.groupingBy(PmContMscTech::getOrderNo));
        List<PmContractLineSpec> pmContractLineSpecList  = pmContractLineSpecMapper.queryList(orderNoList, tenantId);
        Map<String, List<PmContractLineSpec>> pmRuntimeContractMap = new HashMap<>(pmProContProdTtrList.size());
        Map<Long, String> pmProductionLineMap = new HashMap<>(pmProContProdTtrList.size());
        if (CollectionUtils.isNotEmpty(pmContractLineSpecList)) {
            pmRuntimeContractMap = pmContractLineSpecList.stream()
                    .collect(Collectors.groupingBy(PmContractLineSpec::getOrderNo));

            // 获取产线编码
            List<Long> idList = pmContractLineSpecList.stream().map(PmContractLineSpec::getAssignedProdLineId).collect(Collectors.toList());
            List<PmProductionLine> pmProductionLineList = pmProductionLineRepository.selectByCondition(Condition.builder(PmProductionLine.class)
                    .andWhere(Sqls.custom().andIn(PmProductionLine.FIELD_PROD_LINE_ID, idList))
                    .andWhere(Sqls.custom().andEqualTo(PmProductionLine.FIELD_TENANT_ID, tenantId))
                    .build());
            if (CollectionUtils.isNotEmpty(pmProductionLineList)) {
                pmProductionLineMap = pmProductionLineList.stream().collect(Collectors
                        .toMap(PmProductionLine::getProdLineId, PmProductionLine::getProdLineCode));
            }
        }
        // 组装数据
        List<PmRuntimeContractLineReqDTO> resultList = new ArrayList<>();
        for (PmProContProdTtr pmProContProdTtr : pmProContProdTtrList) {
            PmRuntimeContractLineReqDTO result = new PmRuntimeContractLineReqDTO();
            result.setOrderNo(pmProContProdTtr.getOrderNo());
            result.setOrderTypeCode(pmProContProdTtr.getOrderTypeCode());
            result.setDelivyDate(pmProContProdTtr.getDelivyDate());
            result.setSgSign(pmProContProdTtr.getSgSign());
            result.setNeedLecquering(pmProContProdTtr.getNeedLecquering());
            result.setOrderThick(pmProContProdTtr.getOrderThick());
            result.setOrderWidth(pmProContProdTtr.getOrderWidth());
            result.setOrderLen(pmProContProdTtr.getOrderLen());
            result.setOrderNum(pmProContProdTtr.getOrderQty());
            result.setOrderWt(pmProContProdTtr.getOrderWt());
            result.setConsignCustCname(pmProContProdTtr.getConsignCustCname());
            result.setDelivyPlaceName(pmProContProdTtr.getDelivyPlaceName());
            result.setOrderCustCname(pmProContProdTtr.getOrderCustCname());
            result.setHullSectionNo(pmProContProdTtr.getHullSectionNo());
            if (pmContMscTechMap.containsKey(pmProContProdTtr.getOrderNo())) {
                String mscLineNo = pmContMscTechMap.get(pmProContProdTtr.getOrderNo()).stream().map(PmContMscTech::getMscLineNo)
                        .collect(Collectors.joining(","));
                result.setDesignProdLineCode(mscLineNo);
                result.setUltCode(pmContMscTechMap.get(pmProContProdTtr.getOrderNo()).get(0).getUltCode());
                result.setHeatTreatMode(pmContMscTechMap.get(pmProContProdTtr.getOrderNo()).get(0).getHeatTreatMode());
            }
            resultList.add(result);
            if (pmRuntimeContractMap.containsKey(pmProContProdTtr.getOrderNo())) {
                StringBuilder prodLineCodeBuilder = new StringBuilder();
                StringBuilder moldBuilder = new StringBuilder();
                List<PmContractLineSpec> contractLineSpecList = pmRuntimeContractMap.get(pmProContProdTtr.getOrderNo());
                // map用作去重
                Map<String, String> prodLineCodeMap = new HashMap<>(16);
                Map<String, String> moldMap = new HashMap<>(16);
                for (PmContractLineSpec lineSpec : contractLineSpecList) {
                    if (pmProductionLineMap.containsKey(lineSpec.getAssignedProdLineId())) {
                        if (prodLineCodeBuilder.length() > 0) {
                            prodLineCodeBuilder.append(",");
                        }
                        if (!prodLineCodeMap.containsKey(pmProductionLineMap.get(lineSpec.getAssignedProdLineId()))) {
                            prodLineCodeBuilder.append(pmProductionLineMap.get(lineSpec.getAssignedProdLineId()));
                            prodLineCodeMap.put(pmProductionLineMap.get(lineSpec.getAssignedProdLineId()), "1");
                        }
                    }

                    // 断面
                    if (moldBuilder.length() > 0) {
                        moldBuilder.append(",");
                    }
                    if (lineSpec.getMoldThick() != null && lineSpec.getMoldWid() != null) {
                        if (!moldMap.containsKey(lineSpec.getMoldThick() + "*" + lineSpec.getMoldWid())) {
                            moldMap.put(lineSpec.getMoldThick() + "*" + lineSpec.getMoldWid(), "1");
                            moldBuilder.append(lineSpec.getMoldThick() + "*" + lineSpec.getMoldWid());
                        }
                    }
                }
                result.setProdLineCode(prodLineCodeBuilder.toString());
                result.setMold(moldBuilder.toString());
            }
        }
        return  PageUtils.convertListToPage(resultList, pageRequest);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void manualExecution(List<String> stNoList, Long tenantId) {
        // todo 调用【请求参数维护】

    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void chage(PmRuntimeContractChangeDTO dtoList, Long tenantId) {
        List<PmSpecTableColumn> pmSpecTableColumnList = pmSpecTableColumnRepository.selectByCondition(Condition.builder(PmSpecTableColumn.class)
                .andWhere(Sqls.custom().andEqualTo(PmSpecTableColumn.FIELD_TENANT_ID, tenantId))
                .build());
        Map<String, PmSpecTableColumn> thickTableColumnMap = new HashMap<>(pmSpecTableColumnList.size());
        Map<String, PmSpecTableColumn> widthTableColumnMap = new HashMap<>(pmSpecTableColumnList.size());
        Map<String, PmSpecTableColumn> lengthTableColumnMap = new HashMap<>(pmSpecTableColumnList.size());
        if (CollectionUtils.isNotEmpty(pmSpecTableColumnList)) {
            // 按照厚度分组
            thickTableColumnMap = pmSpecTableColumnList.stream().filter(item -> item.getThickFrom() != null && item.getThickTo() != null)
                    .collect(Collectors.toMap(item -> item.getThickFrom().toString() + item.getThickTo().toString(), Function.identity(), (k, v) -> k));
            // 按照宽度分组
            widthTableColumnMap = pmSpecTableColumnList.stream().filter(item -> item.getWidFrom() != null && item.getWidTo() != null)
                    .collect(Collectors.toMap(item -> item.getWidFrom().toString() + item.getWidTo().toString(), Function.identity(), (k, v) -> k));
            // 按照长度分组
            lengthTableColumnMap = pmSpecTableColumnList.stream().filter(item -> item.getLengthFrom() != null && item.getLengthTo() != null)
                    .collect(Collectors.toMap(item -> item.getLengthFrom().toString() + item.getLengthTo().toString(), Function.identity(), (k, v) -> k));
        }
        List<PmSpecTableColumn> insertList = new ArrayList<>();
        // 新增厚度
        if (CollectionUtils.isNotEmpty(dtoList.getThickRangeList())) {
            // 遍历厚度
            for (PmSpecTableColumnRangeDTO thinkRange : dtoList.getThickRangeList()) {
                if (widthTableColumnMap.isEmpty()) {
                    PmSpecTableColumn insertColumn = new PmSpecTableColumn();
                    insertColumn.setThickFrom(thinkRange.getFrom());
                    insertColumn.setThickTo(thinkRange.getTo());
                    insertColumn.setTenantId(tenantId);
                    insertList.add(insertColumn);
                } else {
                    // 遍历宽度
                    for (Map.Entry<String, PmSpecTableColumn> widthEntry : widthTableColumnMap.entrySet()) {
                        // 遍历长度
                        for (Map.Entry<String, PmSpecTableColumn> lengthEntry : lengthTableColumnMap.entrySet()) {
                            PmSpecTableColumn insertColumn = new PmSpecTableColumn();
                            insertColumn.setThickFrom(thinkRange.getFrom());
                            insertColumn.setThickTo(thinkRange.getTo());
                            insertColumn.setWidFrom(widthEntry.getValue().getWidFrom());
                            insertColumn.setWidTo(widthEntry.getValue().getWidTo());
                            insertColumn.setLengthFrom(lengthEntry.getValue().getLengthFrom());
                            insertColumn.setLengthTo(lengthEntry.getValue().getLengthTo());
                            insertColumn.setTenantId(tenantId);
                            insertList.add(insertColumn);
                        }
                    }
                }
            }
        } else if (CollectionUtils.isNotEmpty(dtoList.getWidthRangeList())) {
            // 宽度
            // 遍历厚度
            if (thickTableColumnMap.isEmpty()) {
                throw new CommonException("pm.spec_table_column_001");
            }
            for (Map.Entry<String, PmSpecTableColumn> thickEntry : thickTableColumnMap.entrySet()) {
                // 遍历宽度
                for (PmSpecTableColumnRangeDTO widthRange : dtoList.getWidthRangeList()) {
                    // 遍历长度
                    if (lengthTableColumnMap.isEmpty()) {
                        PmSpecTableColumn insertColumn = new PmSpecTableColumn();
                        insertColumn.setThickFrom(thickEntry.getValue().getThickFrom());
                        insertColumn.setThickTo(thickEntry.getValue().getThickTo());
                        insertColumn.setWidFrom(widthRange.getFrom());
                        insertColumn.setWidTo(widthRange.getTo());
                        insertColumn.setTenantId(tenantId);
                        insertList.add(insertColumn);
                    } else {
                        for (Map.Entry<String, PmSpecTableColumn> lengthEntry : lengthTableColumnMap.entrySet()) {
                            PmSpecTableColumn insertColumn = new PmSpecTableColumn();
                            insertColumn.setThickFrom(thickEntry.getValue().getThickFrom());
                            insertColumn.setThickTo(thickEntry.getValue().getThickTo());
                            insertColumn.setWidFrom(widthRange.getFrom());
                            insertColumn.setWidTo(widthRange.getTo());
                            insertColumn.setLengthFrom(lengthEntry.getValue().getLengthFrom());
                            insertColumn.setLengthTo(lengthEntry.getValue().getLengthTo());
                            insertColumn.setTenantId(tenantId);
                            insertList.add(insertColumn);
                    }
                    }
                }
            }

        } else if (CollectionUtils.isNotEmpty(dtoList.getLenthRangeList())) {
            // 遍历厚度
            if (thickTableColumnMap.isEmpty()) {
                throw new CommonException("pm.spec_table_column_001");
            }
             if (widthTableColumnMap.isEmpty()) {
                throw new CommonException("pm.spec_table_column_002");
            }
             // 长度
            for (Map.Entry<String, PmSpecTableColumn> thickEntry : thickTableColumnMap.entrySet()) {
                // 遍历宽度
                for (Map.Entry<String, PmSpecTableColumn> widthEntry : widthTableColumnMap.entrySet()) {
                    // 遍历长度
                    for (PmSpecTableColumnRangeDTO lengthRange : dtoList.getLenthRangeList()) {
                        PmSpecTableColumn insertColumn = new PmSpecTableColumn();
                        insertColumn.setThickFrom(thickEntry.getValue().getThickFrom());
                        insertColumn.setThickTo(thickEntry.getValue().getThickTo());
                        insertColumn.setWidFrom(widthEntry.getValue().getWidFrom());
                        insertColumn.setWidTo(widthEntry.getValue().getWidTo());
                        insertColumn.setLengthFrom(lengthRange.getFrom());
                        insertColumn.setLengthTo(lengthRange.getTo());
                        insertColumn.setTenantId(tenantId);
                        insertList.add(insertColumn);
                    }
                }
            }
        }

        // 对 insertList 进行排序
        List<PmSpecTableColumn> sortedInsertList = insertList.stream().sorted(Comparator.comparing(PmSpecTableColumn::getThickFrom)
                        .thenComparing(PmSpecTableColumn::getWidFrom).thenComparing(PmSpecTableColumn::getLengthFrom))
                .collect(Collectors.toList());
        // 赋值表头列号
        Long seq = 1L;
        for (PmSpecTableColumn specTableColumn : sortedInsertList) {
            specTableColumn.setHeaderColumnNum(seq++);
        }
        // 删除表
        pmSpecTableColumnRepository.batchDeleteByPrimaryKey(pmSpecTableColumnList);
        // 插入表
        pmSpecTableColumnRepository.batchInsertSelective(sortedInsertList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void appoint(PmRuntimeContractAppointDTO dto, Long tenantId) {
        // 获取合同号已存在的数据
        List<PmContractLineSpec> pmContractLineSpecList = pmContractLineSpecRepository.selectByCondition(Condition.builder(PmContractLineSpec.class)
                .andWhere(Sqls.custom().andIn(PmContractLineSpec.FIELD_ORDER_NO, dto.getOrderNoList()))
                .andWhere(Sqls.custom().andEqualTo(PmContractLineSpec.FIELD_TENANT_ID, tenantId))
                .build());

        List<PmContractLineSpec> insertList = new ArrayList<>();
        for (String orderNo : dto.getOrderNoList()) {
            for (Long prodLineId : dto.getProdLineIdList()) {
                if (CollectionUtils.isEmpty(dto.getMoldList())) {
                    PmContractLineSpec pmContractLineSpec = new PmContractLineSpec();
                    pmContractLineSpec.setOrderNo(orderNo);
                    pmContractLineSpec.setAssignedProdLineId(prodLineId);
                    pmContractLineSpec.setMoldThick(null);
                    pmContractLineSpec.setMoldWid(null);
                    pmContractLineSpec.setTenantId(tenantId);
                    insertList.add(pmContractLineSpec);
                } else {
                    for (PmRuntimeContractMoldDTO pmRuntimeContractMoldDTO : dto.getMoldList()) {
                        PmContractLineSpec pmContractLineSpec = new PmContractLineSpec();
                        pmContractLineSpec.setOrderNo(orderNo);
                        pmContractLineSpec.setAssignedProdLineId(prodLineId);
                        pmContractLineSpec.setMoldThick(pmRuntimeContractMoldDTO.getMoldThick());
                        pmContractLineSpec.setMoldWid(pmRuntimeContractMoldDTO.getMoldWid());
                        pmContractLineSpec.setTenantId(tenantId);
                        insertList.add(pmContractLineSpec);
                    }
                }
            }
        }
        // 删除
        pmContractLineSpecRepository.batchDeleteByPrimaryKey(pmContractLineSpecList);
        // 新增
        pmContractLineSpecRepository.batchInsertSelective(insertList);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void cancelAppoint(List<String> orderNoList, Long tenantId) {
        List<PmContractLineSpec> pmContractLineSpecList = pmContractLineSpecRepository.selectByCondition(Condition.builder(PmContractLineSpec.class)
                .andWhere(Sqls.custom().andIn(PmContractLineSpec.FIELD_ORDER_NO,orderNoList))
                .andWhere(Sqls.custom().andEqualTo(PmContractLineSpec.FIELD_TENANT_ID, tenantId))
                .build());
        pmContractLineSpecRepository.batchDeleteByPrimaryKey(pmContractLineSpecList);
    }
}

