package com.cf.imes.module.plan.service.orderImport.factory;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.cf.imes.framework.common.exception.ErrorCode;
import com.cf.imes.framework.common.exception.util.ServiceExceptionUtil;
import com.cf.imes.framework.common.pojo.CommonResult;
import com.cf.imes.framework.id.core.util.SnowflakeIdWorker3rd;
import com.cf.imes.framework.mybatis.core.generator.SnowFlakeGenerator;
import com.cf.imes.framework.mybatis.core.injector.BaseBatchMapper;
import com.cf.imes.framework.security.core.util.SecurityFrameworkUtils;
import com.cf.imes.module.executor.enums.OrderItemTypeEnum;
import com.cf.imes.module.plan.controller.admin.orderImport.webcad.vo.WebCadDataBlockRemarkVO;
import com.cf.imes.module.plan.controller.admin.orderImport.webcad.vo.WebCadDataBlockReqVO;
import com.cf.imes.module.plan.controller.admin.orderImport.webcad.vo.WebCadDataDoubleRoomTreeReqVO;
import com.cf.imes.module.plan.controller.admin.orderImport.webcad.vo.WebCadDataGroupInfoReqVO;
import com.cf.imes.module.plan.controller.admin.orderImport.webcad.vo.WebCadDataMaterialReqVO;
import com.cf.imes.module.plan.controller.admin.orderImport.webcad.vo.WebCadDataPartsReqVO;
import com.cf.imes.module.plan.controller.admin.orderImport.webcad.vo.WebCadDataProcessGroupReqVO;
import com.cf.imes.module.plan.controller.admin.orderImport.webcad.vo.WebCadDataReqVO;
import com.cf.imes.module.plan.dal.dataobject.goods.GoodsDO;
import com.cf.imes.module.plan.dal.dataobject.order.OrderDO;
import com.cf.imes.module.plan.dal.dataobject.orderBody.OrderBodyDO;
import com.cf.imes.module.plan.dal.dataobject.orderGroup.OrderGroupDO;
import com.cf.imes.module.plan.dal.dataobject.orderItem.OrderItemDO;
import com.cf.imes.module.plan.dal.dataobject.orderParts.OrderPartsDO;
import com.cf.imes.module.plan.dal.dataobject.ordermodel.OrderModelDO;
import com.cf.imes.module.plan.dal.dataobject.plate.PlateDO;
import com.cf.imes.module.plan.dal.dataobject.rawgoods.RawGoodsDO;
import com.cf.imes.module.plan.dal.elasticsearch.HoleDetail;
import com.cf.imes.module.plan.dal.elasticsearch.IContourData;
import com.cf.imes.module.plan.dal.elasticsearch.IOriginModelingData;
import com.cf.imes.module.plan.dal.elasticsearch.ModelDetail;
import com.cf.imes.module.plan.dal.elasticsearch.OffSetList;
import com.cf.imes.module.plan.dal.elasticsearch.Point;
import com.cf.imes.module.plan.dal.elasticsearch.PointDetail;
import com.cf.imes.module.plan.dal.elasticsearch.PointList;
import com.cf.imes.module.plan.dal.mysql.goods.GoodsMapper;
import com.cf.imes.module.plan.dal.mysql.order.OrderMapper;
import com.cf.imes.module.plan.dal.mysql.orderBody.OrderBodyMapper;
import com.cf.imes.module.plan.dal.mysql.plate.PlateMapper;
import com.cf.imes.module.plan.dal.mysql.rawgoods.RawGoodsMapper;
import com.cf.imes.module.plan.enums.ErrorCodeConstants;
import com.cf.imes.module.plan.service.customplateno.CustomPlateNoGenerateService;
import com.cf.imes.module.plan.service.customplateno.vo.CustomPlateNoGenerateConfigVO;
import com.cf.imes.module.plan.service.order.OrderInputProcessor;
import com.cf.imes.module.system.api.systemconfig.SystemConfigApi;
import com.cf.imes.module.system.api.systemconfig.dto.SystemConfigRespDTO;
import com.cf.imes.module.system.api.systemconfig.dto.SystemConfigSealEdgeRespDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

import static com.cf.imes.module.plan.enums.ErrorCodeConstants.WEBCAD_ORDER_IMPORT_GET_ORG_SEALEDGE_ERROR;
import static com.cf.imes.module.plan.enums.ErrorCodeConstants.WEBCAD_ORDER_IMPORT_ORDER_PLATENUM_CHECK_ERROR;
import static com.cf.imes.module.plan.enums.ErrorCodeConstants.WEBCAD_ORDER_IMPORT_ORDER_PLATENUM_REACH_THRESHOLD_ERROR;
import static com.cf.imes.module.plan.enums.ErrorCodeConstants.WEBCAD_ORDER_IMPORT_ORG_SEALEDGE_ANALYZE_ERROR;
import static com.cf.imes.module.plan.service.order.OrderInputProcessor.ORDER_PLATE_MODEL;

/**
 * webcad导入生产单工厂服务
 *
 * @author Gqr
 * @since 2025/3/8 14:39
 */
@Slf4j
public class WebCadOrderImportFactory {
    /**
     * 批量操作阈值
     */
    private static final int BATCH_THRESHOLD_NUMBER = 999;

    private SnowFlakeGenerator snowFlakeGenerator;

    private OrderMapper orderMapper;

    private OrderBodyMapper orderBodyMapper;

    private PlateMapper plateMapper;

    private SnowflakeIdWorker3rd idWorker;

    private OrderInputProcessor orderInputProcessor;

    private SystemConfigApi systemConfigApi;

    private GoodsMapper goodsMapper;

    private RawGoodsMapper rawGoodsMapper;

    private CustomPlateNoGenerateService customPlateNoGenerateService;

    private JdbcTemplate jdbcTemplate;

    private Long organId;

    // 批次id
    private Long batchId;

    private Long orderId;

    private OrderDO orderDO;

    // 是否入库的第一块板件
    private boolean isFirstPlate;

    // 是否有插入es数据
    private boolean esInsert;

    private CustomPlateNoGenerateConfigVO plateNoGenerateConfigVO;

    // 操作人
    private String operatorName;

    private LocalDateTime now;

    // 柜体成倍信息缓存：{ 房间名+柜体名：count }
    private Map<String, Integer> roomBodyMap = new HashMap<>();

    // 柜体缓存
    private Map<String, OrderBodyDO> bodyMap = new HashMap<>();

    // 房间名+柜体名+加工组名：加工组
    private Map<String, OrderGroupDO> orderGroupMap = new HashMap<>();

    // 板材缓存：{商品编号：GoodsDO}
    private Map<String, GoodsDO> materialMap = new HashMap<>();

    // 已存在房间缓存：{ roomName: roomId }
    private Map<String, Long> existRoomIdMap = new HashMap<>();

    // IsComposite+ObjectType+Factory+Model+Spec+height+width+depth+unit+brand：orderPartId
    private Map<String, Long> orderPartMap = new HashMap<>();

    // 加工组缓存
    private Map<Integer, WebCadDataGroupInfoReqVO> processGroupMap = new HashMap<>();

    private List<PlateDO> plateDOS = new ArrayList<>();
    private List<OrderItemDO> orderItemDOS = new ArrayList<>();
    private List<OrderPartsDO> orderPartsDOS = new ArrayList<>();
    private List<OrderModelDO> orderModelDOS = ListUtils.newArrayListWithExpectedSize(BATCH_THRESHOLD_NUMBER);
    private List<RawGoodsDO> rawGoodsDOS = new ArrayList<>();
    private List<GoodsDO> goodsDOS = new ArrayList<>();
    private List<SystemConfigSealEdgeRespDTO> sealEdgeConfigList;


    private static final String PART_CATEGORY_ONE = "封边条";
    private static final String PART_CATEGORY_TWO = "五金";
    private static final String PART_CATEGORY_THREE = "组件";
    private static final String EMPTY_STRING = new String();

    // 当前拆单导入的板件数量（初始包含前n次导入的板件总数）
    private int currentPlateNum;

    private BigDecimal currentPlateArea = new BigDecimal(0);

    // cad拆单板件数量阈值
    private int cadImportPlateNumThreshold;

    // 板件数量是否已达到阈值
    private boolean plateNumReachThreshold = false;

    public WebCadOrderImportFactory(Long organId,
                                    OrderDO orderDO,
                                    SnowFlakeGenerator snowFlakeGenerator,
                                    OrderMapper orderMapper,
                                    OrderBodyMapper orderBodyMapper,
                                    PlateMapper plateMapper,
                                    SnowflakeIdWorker3rd idWorker,
                                    OrderInputProcessor orderInputProcessor,
                                    GoodsMapper goodsMapper,
                                    RawGoodsMapper rawGoodsMapper,
                                    CustomPlateNoGenerateService customPlateNoGenerateService,
                                    SystemConfigApi systemConfigApi,
                                    int cadImportPlateNumThreshold,
                                    JdbcTemplate jdbcTemplate) {
        this.organId = organId;
        this.orderDO = orderDO;
        this.orderId = orderDO.getId();
        this.snowFlakeGenerator = snowFlakeGenerator;
        this.orderMapper = orderMapper;
        this.orderBodyMapper = orderBodyMapper;
        this.plateMapper = plateMapper;
        this.idWorker = idWorker;
        this.orderInputProcessor = orderInputProcessor;
        this.goodsMapper = goodsMapper;
        this.rawGoodsMapper = rawGoodsMapper;
        this.customPlateNoGenerateService = customPlateNoGenerateService;
        this.systemConfigApi = systemConfigApi;
        operatorName = SecurityFrameworkUtils.getLoginUser().getNickname();
        now = LocalDateTime.now();
        batchId = (Long) snowFlakeGenerator.nextId(null);
        sealEdgeConfigList = new ArrayList<>();
        this.cadImportPlateNumThreshold = cadImportPlateNumThreshold;
        this.jdbcTemplate = jdbcTemplate;
    }

    public void analyzeTempData(WebCadDataReqVO webCadDataReqVO) {
        try {
            log.debug("====================【cad拆单校验板件数量开始】====================");
            // 校验板件数量
            analyzePlateNum();
            log.debug("====================【cad拆单校验板件数量结束】====================");

            log.debug("====================【cad拆单解析板材开始】====================");
            // 板材id对应板件
            analyzeMaterials(webCadDataReqVO.getMaterials());
            log.debug("====================【cad拆单解析板材结束】====================");

            log.debug("====================【cad拆单解析加工组开始】====================");
            // 解析加工组类型
            analyzeGroups(webCadDataReqVO.getProcessGroup());
            log.debug("====================【cad拆单解析加工组结束】====================");

            log.debug("====================【cad拆单解析成倍柜体开始】====================");
            // 缓存柜体成倍信息
            analyzeRoomBody(webCadDataReqVO.getDouleRoomTree());
            log.debug("====================【cad拆单解析成倍柜体结束】====================");

            log.debug("====================【cad拆单解析板件开始】====================");
            // 解析板件列表
            analyzeBlockList(webCadDataReqVO.getBlocks());
            log.debug("====================【cad拆单解析板件结束】====================");

            log.debug("====================【cad拆单解析配件开始】====================");
            // 解析配件列表
            analyzeParts(webCadDataReqVO.getParts());
            log.debug("====================【cad拆单解析配件结束】====================");

            orderItemBatchInsertWithinThreshold(orderItemDOS, true);
            log.debug("====================【cad拆单全局保存开始】====================");
            // 保存数据柜体、加工组
            saveData();
            log.debug("====================【cad拆单全局保存结束】====================");

            // 新增/更新order_goods
            insertOrUpdatePlateNumGoods();

            // 更新生产单板件数量
            updateOrderPlateNum();

            // 所有自定义板编号生成完成后更新配置到生产单
            customPlateNoGenerateService.updateCustomPlateNoGenerateConfig(plateNoGenerateConfigVO, orderDO);

            if (plateNumReachThreshold) {
                log.warn(ServiceExceptionUtil.exception(WEBCAD_ORDER_IMPORT_ORDER_PLATENUM_REACH_THRESHOLD_ERROR, orderId, cadImportPlateNumThreshold).getMessage());
            }

        } catch (Exception e) {
            if (esInsert) {
                CompletableFuture.runAsync(() -> {
                    // 数据库数据回滚，同步删除 ES 里当前批次的数据
                    orderInputProcessor.deleteByOrderIdBatch(orderId, batchId, ORDER_PLATE_MODEL);
                });
            }
            throw e;
        } finally {
            // 清理数据
            clearAll();
        }
    }

    /**
     * 获取组织封边条对应配置
     */
    private void getOrgSealEdgeConfig() {
        CommonResult<List<SystemConfigRespDTO>> orgSealEdgeConfig = systemConfigApi.getOrgSealEdgeConfig();
        boolean success = orgSealEdgeConfig.isSuccess();
        if (success) {
            try {
                List<SystemConfigRespDTO> orgSealEdgeConfigCheckedData = orgSealEdgeConfig.getCheckedData();
                if (CollUtil.isNotEmpty(orgSealEdgeConfigCheckedData)) {
                    // 默认取第一条为配置
                    SystemConfigRespDTO sealEdgeConfig = orgSealEdgeConfigCheckedData.get(0);
                    String setting = sealEdgeConfig.getSetting();
                    // 封边对应配置转列表
                    JSONArray jsonArray = JSON.parseArray(setting);
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        String widthMin = jsonObject.getString("widthMin");
                        String widthMax = jsonObject.getString("widthMax");
                        String widthValue = jsonObject.getString("widthValue");

                        if (StringUtils.isNotEmpty(widthMin) && StringUtils.isNotEmpty(widthMax) && StringUtils.isNotEmpty(widthValue)) {
                            sealEdgeConfigList.add(new SystemConfigSealEdgeRespDTO(NumberUtil.parseDouble(widthMin), NumberUtil.parseDouble(widthMax), NumberUtil.parseDouble(widthValue)));
                        }
                    }
                }
            } catch (Exception e) {
                ErrorCode webcadOrderImportOrgSealedgeAnalyzeError = WEBCAD_ORDER_IMPORT_ORG_SEALEDGE_ANALYZE_ERROR;
                log.error(webcadOrderImportOrgSealedgeAnalyzeError.getMsg(), e);
                throw ServiceExceptionUtil.exception(webcadOrderImportOrgSealedgeAnalyzeError);
            }
        } else {
            throw ServiceExceptionUtil.exception(WEBCAD_ORDER_IMPORT_GET_ORG_SEALEDGE_ERROR);
        }
    }

    /**
     * 解析生产单信息
     *
     * @param
     */
    private void analyzePlateNum() {
        // 解析已有生产单下板件数量，超过两万不再导入
        Long existPlateCount = plateMapper.selectCount(new LambdaQueryWrapper<PlateDO>()
                .eq(PlateDO::getOrderId, orderId)
                .eq(PlateDO::getOrganId, organId)
                .eq(PlateDO::getDeleted, false)
        );
        // cadImportPlateNumThreshold万片阻止继续拆单
        if (existPlateCount >= cadImportPlateNumThreshold) {
            throw ServiceExceptionUtil.exception(WEBCAD_ORDER_IMPORT_ORDER_PLATENUM_CHECK_ERROR, orderId, cadImportPlateNumThreshold);
        } else {
            currentPlateNum = existPlateCount.intValue();
            // 统计当前板件总面积
            List<Map<String, Object>> orderPlateSumResult = plateMapper.selectMaps(new QueryWrapper<PlateDO>()
                    .select("sum(area) as area")
                    .eq("organ_id", organId)
                    .eq("order_id", orderId)
                    .eq("deleted", false));
            if (CollUtil.isNotEmpty(orderPlateSumResult)) {
                Map<String, Object> resultMap = orderPlateSumResult.get(0);
                if(ObjectUtil.isNotNull(resultMap)) {
                    currentPlateArea = (BigDecimal) resultMap.get("area");
                }
            }
        }
    }

    /**
     * 板材id赋值对应板材
     *
     * @param materialReqVOS
     */
    private void analyzeMaterials(List<WebCadDataMaterialReqVO> materialReqVOS) {
        if (CollUtil.isEmpty(materialReqVOS)) {
            return;
        }

        // 检查生产单下是否已经有goodsId下的order_goods，有不再创建
        materialMap = goodsMapper.selectMaps(
                        new QueryWrapper<GoodsDO>()
                                .select("goods_id ,MIN(id) as id, plate_num, planned_plate_num, area, planned_plate_area, version")
                                .eq("order_id", orderId)
                                .eq("organ_id", organId)
                                .eq("deleted", false)
                                .in("goods_id", materialReqVOS.stream().map(WebCadDataMaterialReqVO::getGoodsId).collect(Collectors.toList()))
                                .groupBy("goods_id, plate_num, planned_plate_num, area, planned_plate_area, version")).stream()
                .collect(Collectors.toMap(
                        m -> String.valueOf(m.get("goods_id")),
                        m -> {
                            GoodsDO goodsDO = new GoodsDO();
                            goodsDO.setId(NumberUtil.parseLong(String.valueOf(m.get("id"))));
                            goodsDO.setExist(true);
                            goodsDO.setPlateNum(NumberUtil.parseInt(String.valueOf(m.get("plate_num"))));
                            goodsDO.setPlannedPlateNum(NumberUtil.parseInt(String.valueOf(m.get("planned_plate_num"))));
                            goodsDO.setArea(NumberUtil.parseDouble(String.valueOf(m.get("area"))));
                            goodsDO.setPlannedPlateArea(NumberUtil.parseDouble(String.valueOf(m.get("planned_plate_area"))));
                            goodsDO.setVersion(NumberUtil.parseInt(String.valueOf(m.get("version"))));
                            return goodsDO;
                        }
                ));

        for (WebCadDataMaterialReqVO materialReqVO : materialReqVOS) {
            String plateGoodsGoodsId = materialReqVO.getGoodsId();

            GoodsDO existOrderGoods = materialMap.get(plateGoodsGoodsId);
            if (ObjectUtil.isNull(existOrderGoods)) {
                // 创建设计端商品
                Long rawGoodsId = (Long) snowFlakeGenerator.nextId(null);
                RawGoodsDO rawGoodsDO = RawGoodsDO.builder()
                        .id(rawGoodsId)
                        .orderId(orderId)
                        .rawGoodsId(plateGoodsGoodsId)
                        .goodsName(materialReqVO.getName())
                        .material(materialReqVO.getMaterial())
                        .texture(materialReqVO.getTexture())
                        .color(materialReqVO.getColor())
                        .colorBlack(EMPTY_STRING)
                        .thickness(materialReqVO.getThickness())
                        .spec(getEmpty(materialReqVO.getSpec()))
                        .brand(getEmpty(materialReqVO.getBrand()))
                        .price(0.00)
                        .deleted(false)
                        .organId(organId)
                        .build();
                Long orderGoodsId = (Long) snowFlakeGenerator.nextId(null);

                // 创建生产单商品
                GoodsDO goodsDO = GoodsDO.builder()
                        .id(orderGoodsId)
                        .orderId(orderId)
                        .rawGoodsId(String.valueOf(rawGoodsId))
                        .goodsId(plateGoodsGoodsId)
                        .goodsName(materialReqVO.getName())
                        .material(materialReqVO.getMaterial())
                        .texture(materialReqVO.getTexture())
                        .color(materialReqVO.getColor())
                        .colorBlack(EMPTY_STRING)
                        .width(BigDecimal.valueOf(getZeroDouble(materialReqVO.getWidth())))
                        .height(BigDecimal.valueOf(getZeroDouble(materialReqVO.getHeight())))
                        .thickness(BigDecimal.valueOf(materialReqVO.getThickness()))
                        .spec(getEmpty(materialReqVO.getSpec()))
                        .brand(getEmpty(materialReqVO.getBrand()))
                        .remark(EMPTY_STRING)
                        .planId(0L)
                        .price(0.00)
                        .deleted(false)
                        .organId(organId)
                        .exist(false)
                        .plateNum(0)
                        .plannedPlateNum(0)
                        .area(0.00)
                        .plannedPlateArea(0.00)
                        .version(0)
                        .build();

                goodsDOS.add(goodsDO);
                rawGoodsDOS.add(rawGoodsDO);

                // 缓存goodCode和orderGoodsId的对应关系
                materialMap.put(plateGoodsGoodsId, goodsDO);
            }
        }
        orderInfoBatchInsertWithinThreshold(rawGoodsMapper, rawGoodsDOS, true);
    }

    /**
     * 缓存加工组类型
     *
     * @param processGroupList
     */
    private void analyzeGroups(List<WebCadDataProcessGroupReqVO> processGroupList) {
        if (CollUtil.isNotEmpty(processGroupList)) {
            for (WebCadDataProcessGroupReqVO processGroup : processGroupList) {
                String groupTypeName = processGroup.getType();
                List<WebCadDataProcessGroupReqVO.ProjectsDTO> projects = processGroup.getProjects();
                if (CollUtil.isNotEmpty(projects)) {
                    for (WebCadDataProcessGroupReqVO.ProjectsDTO project : projects) {
                        // 缓存加工组信息
                        WebCadDataGroupInfoReqVO processGroupInfo = new WebCadDataGroupInfoReqVO();
                        processGroupInfo.setGroupName(project.getProjName());
                        processGroupInfo.setGroupTypeName(groupTypeName);
                        processGroupInfo.setHeight(project.getBoxSize().getHeight());
                        processGroupInfo.setWidth(project.getBoxSize().getWidth());
                        processGroupInfo.setDepth(project.getBoxSize().getDepth());
                        processGroupMap.put(project.getGroupID(), processGroupInfo);
                    }
                }
            }
        }
    }

    /**
     * 生成并缓存成倍房间柜体信息
     *
     * @param douleRoomTree
     */
    private void analyzeRoomBody(List<WebCadDataDoubleRoomTreeReqVO> douleRoomTree) {
        if (CollUtil.isEmpty(douleRoomTree)) {
            return;
        }
        for (WebCadDataDoubleRoomTreeReqVO room : douleRoomTree) {
            String roomName = room.getName();
            List<WebCadDataDoubleRoomTreeReqVO.ChildrenDTO> bodys = room.getChildren();
            if (CollUtil.isNotEmpty(bodys)) {
                for (WebCadDataDoubleRoomTreeReqVO.ChildrenDTO body : bodys) {
                    String bodyName = body.getName();
                    // 缓存柜体成倍信息
                    roomBodyMap.put(roomName + bodyName, body.getCount());
                }
            }
        }
    }

    /**
     * 解析生产单信息板材列表
     *
     * @param douleRoomTree
     */
    private void analyzeBlockList(List<WebCadDataDoubleRoomTreeReqVO> douleRoomTree) {
        if (CollUtil.isEmpty(douleRoomTree)) {
            return;
        }
        // 获取自定义板编号配置
        plateNoGenerateConfigVO = customPlateNoGenerateService.getPlateNoGenerateConfig(orderId);

        // 所有房间名
        List<String> roomNames = douleRoomTree.stream().map(WebCadDataDoubleRoomTreeReqVO::getName).collect(Collectors.toList());

        // 查询当前生产单的所有房间
        existRoomIdMap = orderBodyMapper.selectMaps(
                        new QueryWrapper<OrderBodyDO>()
                                .select("room_name,MIN(room_id) as room_id")
                                .eq("order_id", orderId)
                                .eq("organ_id", organId)
                                .eq("deleted", false)
                                .in("room_name", roomNames)
                                .groupBy("room_name")).stream()
                .collect(Collectors.toMap(
                        m -> String.valueOf(m.get("room_name")),
                        m -> ((Number) m.get("room_id")).longValue()
                ));

        for (WebCadDataDoubleRoomTreeReqVO room : douleRoomTree) {
            // 房间名
            String roomName = room.getName();

            // 同步房间直接使用roomId
            Long roomId;
            Long existRoomId = existRoomIdMap.get(roomName);
            if (ObjectUtil.isNotNull(existRoomId)) {
                roomId = existRoomId;
            } else {
                roomId = (Long) snowFlakeGenerator.nextId(null);
                existRoomIdMap.put(roomName, roomId);
            }

            // 柜体列表
            List<WebCadDataDoubleRoomTreeReqVO.ChildrenDTO> roomBoxs = room.getChildren();
            for (WebCadDataDoubleRoomTreeReqVO.ChildrenDTO box : roomBoxs) {
                String boxName = box.getName();

                // 柜体下的板件
                List<WebCadDataBlockReqVO> listBody = box.getBlockList();

                String roomNameKey = roomName + boxName;
                // 获取缓存中的成本数量
                Integer count = roomBodyMap.get(roomNameKey);

                // 成倍创建
                multiCreateBodyPlate(count, roomId, roomName, boxName, listBody);
            }
        }
        orderPlateBatchInsertWithinThreshold(plateDOS, true);
        // 批量插入造型数据
        orderModelsBatchInsertWithinThreshold(true);
    }

    /**
     * 成倍创建柜体板件
     *
     * @param count
     * @param roomId
     * @param roomName
     * @param listBody
     */
    private void multiCreateBodyPlate(Integer count, Long roomId, String roomName, String boxName, List<WebCadDataBlockReqVO> listBody) {
        for (int i = 0; i < count; i++) {
            Long bodyId = (Long) snowFlakeGenerator.nextId(null);
            OrderBodyDO orderBodyDO = OrderBodyDO.builder().id(bodyId).orderId(orderId).organId(organId)
                    .roomId(roomId).roomName(roomName).name(boxName).width(0.0).height(0.0)
                    .depth(0.0).multiNum(0).plateNum(0).unregularNum(0).filename("无").remark("无").deleted(false).build();
            orderBodyDO.setCreator(operatorName);
            orderBodyDO.setUpdater(operatorName);
            orderBodyDO.setCreateTime(now);
            orderBodyDO.setUpdateTime(now);

            // 缓存成倍的柜体信息
            String multiRoomBodyName = roomName + boxName + i;
            orderBodyDO.setMultiRoomBodyName(multiRoomBodyName);
            bodyMap.put(multiRoomBodyName, orderBodyDO);

            // 达到阈值了不再创建板件
            if (plateNumReachThreshold) {
                continue;
            }

            for (WebCadDataBlockReqVO block : listBody) {
                if (!plateNumReachThreshold) {
                    // 创建板件相关数据：order_plate、order_item、es.orderModels
                    createPlate(orderBodyDO, block);
                } else {
                    // 达到阈值了跳出循环，不再创建板件
                    break;
                }
            }
        }
    }

    /**
     * 创建板件数据
     *
     * @param orderBodyDO
     * @param block
     */
    private void createPlate(OrderBodyDO orderBodyDO, WebCadDataBlockReqVO block) {
        // 是否异形
        Boolean isSpecialShape = block.isSpecialShape();
        // 是否侧面造型
        boolean sideModel = block.isSideModel();
        // 是否有二维刀路
        boolean has2DModel = block.isHas2DModel();
        // 是否有侧面二维刀路
        boolean hasSide2DModel = block.isHasSide2DModel();
        // 是否造型
        boolean isModel = block.isModel() || sideModel || has2DModel || hasSide2DModel || block.isHas3DModel();
        // 是否排孔
        boolean isRawHole = (block.getFrontHoleCount() + block.getBackHoleCount()) > 0;
        Double area = block.getArea();

        // 柜体长宽深
        orderBodyDO.setWidth(block.getCabinetWidth());
        orderBodyDO.setHeight(block.getCabinetHeight());
        orderBodyDO.setDepth(block.getCabinetDepth());

        Long plateId = (Long) snowFlakeGenerator.nextId(null);
        long plateNo = idWorker.nextId();
        long obtainingTime = idWorker.obtainingTime();

        // 从info.remarks中获取备注相关
        WebCadDataBlockRemarkVO plateRemark = getPlateRemark(block);
        List<String> remarks = plateRemark.getRemarks();
        StringBuilder remark = new StringBuilder();
        if (CollUtil.isNotEmpty(remarks)) {
            for (String remarkStr : remarks) {
                remark.append(remarkStr).append(",");
            }
            remark.deleteCharAt(remark.length() - 1);
        }

        // 累加goods的板件总数
        GoodsDO goodsDO = materialMap.get(block.getGoodsCode());
        goodsDO.setPlateNum(goodsDO.getPlateNum() + 1);
        goodsDO.setArea(goodsDO.getArea() + area);


        String splitHeight = block.getSpliteHeight();
        String spliteWidth = block.getSpliteWidth();
        // 创建order_plate
        PlateDO plateDO = PlateDO.builder()
                .id(plateId)
                .orderId(orderId)
                .name(block.getName())
                .plateNo(obtainingTime + Long.toString(plateNo).substring(2))
                .type(block.getType())
                .goodsId(goodsDO.getId())
                .width(BigDecimal.valueOf(block.getWidth()))
                .height(BigDecimal.valueOf(block.getHeight()))
                .thickness(BigDecimal.valueOf(block.getThickness()))
                .splitHeight(BigDecimal.valueOf(NumberUtil.parseDouble(StringUtils.isNotEmpty(splitHeight) ? splitHeight : String.valueOf(block.getKaiLiaoHeight()))))
                .splitThickness(BigDecimal.valueOf(NumberUtil.parseDouble(block.getSpliteThickness())))
                .splitWidth(BigDecimal.valueOf(NumberUtil.parseDouble(StringUtils.isNotEmpty(spliteWidth) ? spliteWidth : String.valueOf(block.getKaiLiaoWidth()))))
                .area(BigDecimal.valueOf(area))
                .texture(block.getTexture())
                .holeFace(block.getHoleFace())
                .isDoor(block.getIsDoor())
                .openDoorType(block.getOpenDoorType())
                .isSpecialShaped(isSpecialShape)
                .isSculpt(isModel)
                .isSideSculpt(sideModel)
                .is2v(has2DModel)
                .isSide2v(hasSide2DModel)
                .isRowHole(isRawHole)
                .customPlateNoBuilder(new StringBuilder())
                .holeArrange(block.getHoleArrange())
                .unregularPointCount(block.getUnregularPointCount())
                .frontHoleCount(block.getFrontHoleCount())
                .backHoleCount(block.getBackHoleCount())
                .sideHoleCount(block.getSideHoleCount())
                .frontModelCount(block.getFrontModelCount())
                .backModelCount(block.getBackModelCount())
                .offsetX(BigDecimal.valueOf(block.getOffsetX()))
                .offsetY(BigDecimal.valueOf(block.getOffsetY()))
                .isArcAcross(getDefaultFalse(block.getIsArcBase()))
                .moduleTypeId(0L)
                .isOptimized(false)
                .isCutted(0)
                .isCancel(false)
                .filterType(EMPTY_STRING)
                .sealLeft(BigDecimal.valueOf(block.getSealLeft()))
                .sealRight(BigDecimal.valueOf(block.getSealRight()))
                .sealUp(BigDecimal.valueOf(block.getSealUp()))
                .sealDown(BigDecimal.valueOf(block.getSealDown()))
                .remark(remark.toString())
                .deleted(false)
                .organId(organId)
                .planId(0L)
                .build();
        plateDO.setCreator(operatorName);
        plateDO.setUpdater(operatorName);
        plateDO.setCreateTime(now);
        plateDO.setUpdateTime(now);

        //批量保存板件
        // 达到板件数量阈值，停止入库，更新全局参数停止后续入库
        currentPlateNum += 1;
        currentPlateArea.add(BigDecimal.valueOf(area));
        if (currentPlateNum > cadImportPlateNumThreshold) {
            plateNumReachThreshold = true;
            return;
        }
        // 生成自定义板编号
        generateCustomPlateNo(plateDO, block.getCustBlockNo());

        // 更新房间下板件和异形的数量
        orderBodyDO.setPlateNum(orderBodyDO.getPlateNum() + 1);
        orderBodyDO.setUnregularNum(orderBodyDO.getUnregularNum() + BooleanUtil.toInt(isSpecialShape));

        plateDOS.add(plateDO);
        orderPlateBatchInsertWithinThreshold(plateDOS, false);

        // 创建es造型数据
        createModel(plateDO, block, plateRemark);
        // 批量插入造型数据
        orderModelsBatchInsertWithinThreshold(false);

        // 遍历加工组信息，生成对应的加工组和item
        analyzeBlockProcessGroup(orderBodyDO, block, plateId);
    }

    /**
     * 创建板件造型es数据
     */
    private void createModel(PlateDO plateDO, WebCadDataBlockReqVO block, WebCadDataBlockRemarkVO plateRemark) {
        // 点阵信息
        WebCadDataBlockReqVO.PointInfoDTO pointInfo = block.getPointInfo();

        OrderModelDO orderModelDO = OrderModelDO.builder()
                .orderId(orderId)
                .plateId(plateDO.getId())
                .batchId(batchId)
                .texture(block.getTexture())
                .typographicFace(block.getHoleArrange())
                .openDoorType(block.getOpenDoorType())
                .splitLength(BigDecimal.valueOf(block.getKaiLiaoHeight()))
                .splitWidth(BigDecimal.valueOf(block.getKaiLiaoWidth()))
                .offsetX(BigDecimal.valueOf(block.getOffsetX()))
                .offsetY(BigDecimal.valueOf(block.getOffsetY()))
                .pointDetail(getPointDetail(pointInfo.getPointDetail()))
                .rawPointDetail(getRawPointDetail(pointInfo.getOrgPointDetail()))
                .holeDetail(getHoleDetail(pointInfo.getHoleDetail()))
                .sideHoleDetail(getSideHoleDetail(pointInfo.getSideHoleDetail()))
                .contourDetail(getContourDetail(pointInfo.getModelDetail()))
                .sideDetail(getSideDetail(pointInfo.getSideModelDetail(), pointInfo.getSide2DModelDetail()))
                .sideRemark(getSideRemark(plateRemark.getRemarks()))
                .boardType(block.getBoardTypeName())
                .has2DModel(block.isHas2DModel())
                .has3DModel(block.isHas3DModel())
                .build();

        // 处理备注信息
        JSONObject plateExtraRemark = new JSONObject();
        JSONObject extraObject = plateRemark.getExtraObject();
        if (ObjectUtil.isNotNull(extraObject)) {
            plateExtraRemark.put("extra", extraObject);
        }

        JSONArray drillsObj = plateRemark.getDrillsObj();
        if (ObjectUtil.isNotNull(drillsObj)) {
            plateExtraRemark.put("drills", drillsObj);
        }
        orderModelDO.setPlateExtraRemark(plateExtraRemark);

        orderModelDO.setGoodsId(block.getGoodsCode());
        orderModelDO.setPlateGoodsId(plateDO.getGoodsId());
        orderModelDO.setOrganId(organId);
        orderModelDOS.add(orderModelDO);
        if (!esInsert) {
            esInsert = true;
        }
    }

    /**
     * 获取生产封边备注
     *
     * @param remarks
     * @return
     */
    private Map<String, String> getSideRemark(List<String> remarks) {
        if (CollUtil.isNotEmpty(remarks)) {
            Map<String, String> sideRemarkMap = new HashMap<>();
            for (int i = 1; i <= remarks.size(); i++) {
                sideRemarkMap.put("Remark" + i, remarks.get(i - 1));
            }
            return sideRemarkMap;
        }
        return null;
    }

    /**
     * 获取板件点明细
     *
     * @param cadPointDetailList
     * @return
     */
    private List<PointDetail> getPointDetail(List<WebCadDataBlockReqVO.PointInfoDTO.PointDetailDTO> cadPointDetailList) {
        if (CollUtil.isNotEmpty(cadPointDetailList)) {
            List<PointDetail> pointDetails = new ArrayList<>();
            for (WebCadDataBlockReqVO.PointInfoDTO.PointDetailDTO cadPointDetail : cadPointDetailList) {
                PointDetail pointDetail = new PointDetail();
                pointDetail.setId(String.valueOf(cadPointDetail.getPointID()));
                pointDetail.setPointX(cadPointDetail.getPointX());
                pointDetail.setPointY(cadPointDetail.getPointY());
                pointDetail.setCurve(cadPointDetail.getCurve());
                pointDetails.add(pointDetail);
            }
            return pointDetails;
        }
        return null;
    }

    /**
     * 获取板件原始点明细
     *
     * @param orgPointDetail
     * @return
     */
    private List<PointDetail> getRawPointDetail(List<WebCadDataBlockReqVO.PointInfoDTO.OrgPointDetailDTO> orgPointDetail) {
        if (CollUtil.isNotEmpty(orgPointDetail)) {
            List<PointDetail> pointDetails = new ArrayList<>();
            for (WebCadDataBlockReqVO.PointInfoDTO.OrgPointDetailDTO cadPointDetail : orgPointDetail) {
                PointDetail pointDetail = new PointDetail();
                pointDetail.setId(String.valueOf(cadPointDetail.getPointID()));
                pointDetail.setPointX(cadPointDetail.getPointX());
                pointDetail.setPointY(cadPointDetail.getPointY());
                pointDetail.setCurve(cadPointDetail.getCurve());
                pointDetail.setSealSize(BigDecimal.valueOf(cadPointDetail.getSealSize()));
                pointDetails.add(pointDetail);
            }
            return pointDetails;
        }
        return null;
    }


    /**
     * 获取板件孔明细列表
     *
     * @param cadHoleDetailList
     * @return
     */
    private List<HoleDetail> getHoleDetail(List<WebCadDataBlockReqVO.PointInfoDTO.HoleDetailDTO> cadHoleDetailList) {
        if (CollUtil.isNotEmpty(cadHoleDetailList)) {
            List<HoleDetail> holeDetails = new ArrayList<>();
            for (WebCadDataBlockReqVO.PointInfoDTO.HoleDetailDTO cadHoleDetail : cadHoleDetailList) {
                HoleDetail holeDetail = new HoleDetail();
                holeDetail.setId(String.valueOf(cadHoleDetail.getHoleID()));
                holeDetail.setFaceType(cadHoleDetail.getFace());
                holeDetail.setHoleType(cadHoleDetail.getHoleType());
                holeDetail.setStartX(cadHoleDetail.getPointX());
                holeDetail.setStartY(cadHoleDetail.getPointY());
                holeDetail.setRadius(cadHoleDetail.getRadius());
                holeDetail.setDepth(cadHoleDetail.getDepth());
                holeDetails.add(holeDetail);
            }
            return holeDetails;
        }
        return null;
    }

    /**
     * 获取侧面孔明细
     *
     * @param cadSideHoleDetailList
     * @return
     */
    private List<HoleDetail> getSideHoleDetail(List<WebCadDataBlockReqVO.PointInfoDTO.SideHoleDetailDTO> cadSideHoleDetailList) {
        if (CollUtil.isNotEmpty(cadSideHoleDetailList)) {
            List<HoleDetail> holeDetails = new ArrayList<>();
            for (WebCadDataBlockReqVO.PointInfoDTO.SideHoleDetailDTO cadHoleDetail : cadSideHoleDetailList) {
                HoleDetail holeDetail = new HoleDetail();
                holeDetail.setId(String.valueOf(cadHoleDetail.getHoleID()));
                holeDetail.setFaceType(cadHoleDetail.getFace());
                holeDetail.setStartX(cadHoleDetail.getPointX());
                holeDetail.setStartY(cadHoleDetail.getPointY());
                holeDetail.setStartZ(cadHoleDetail.getPointZ());
                holeDetail.setRadius(cadHoleDetail.getRadius());
                holeDetail.setEndX(cadHoleDetail.getPointX2());
                holeDetail.setEndY(cadHoleDetail.getPointY2());
                holeDetail.setEndZ(cadHoleDetail.getPointZ());
                holeDetail.setDepth(cadHoleDetail.getDepth());
                holeDetails.add(holeDetail);
            }
            return holeDetails;
        }
        return null;
    }

    /**
     * 获取造型明细
     *
     * @param cadModelDetailList
     * @return
     */
    private List<ModelDetail> getContourDetail(List<WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO> cadModelDetailList) {
        if (CollUtil.isNotEmpty(cadModelDetailList)) {
            List<ModelDetail> modelDetails = new ArrayList<>();
            for (WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO cadModelDetail : cadModelDetailList) {
                ModelDetail modelDetail = new ModelDetail();
                modelDetail.setModelID(cadModelDetail.getModelID());
                modelDetail.setLineID(cadModelDetail.getLineID());
                modelDetail.setFaceType(cadModelDetail.getFace());
                modelDetail.setDepth(cadModelDetail.getDepth());
                modelDetail.setKnifeName(cadModelDetail.getKnifeName());
                modelDetail.setKnifeRadius(cadModelDetail.getKnifeRadius());

                WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.OriginModelingDTO cadOriginModeling = cadModelDetail.getOriginModeling();
                if (ObjectUtil.isNotNull(cadOriginModeling)) {
                    IOriginModelingData originModelingData = new IOriginModelingData();
                    originModelingData.setAddLen(cadOriginModeling.getAddLen());
                    originModelingData.setAddWidth(cadOriginModeling.getAddWidth());
                    originModelingData.setAddDepth(cadOriginModeling.getAddDepth());

                    WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.OriginModelingDTO.OutlineDTO cadOutline = cadOriginModeling.getOutline();
                    originModelingData.setOutline(getOriginModelingOutlineList(cadOutline));

                    originModelingData.setHoles(getModelingHoles(cadOriginModeling.getHoles()));

                    modelDetail.setOriginModeling(originModelingData);
                }
                List<WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.PointListDTO> pointList = cadModelDetail.getPointList();
                modelDetail.setPointList(getModelDetailPointList(pointList));

                List<WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.OffSetListDTO> offSetList = cadModelDetail.getOffSetList();
                modelDetail.setOffSetList(getModelDetailOffsetList(offSetList));

                modelDetails.add(modelDetail);
            }
            return modelDetails;
        }
        return null;
    }

    /**
     * 获取造型偏移量列表
     *
     * @param cadOffSetList
     * @return
     */
    private List<OffSetList> getModelDetailOffsetList(List<WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.OffSetListDTO> cadOffSetList) {
        if (CollUtil.isNotEmpty(cadOffSetList)) {
            List<OffSetList> offSetLists = new ArrayList<>();
            for (WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.OffSetListDTO cadOffset : cadOffSetList) {
                OffSetList offSet = new OffSetList();
                offSet.setValue(cadOffset.getValue());
                offSet.setDepth(cadOffset.getDeep());
                offSet.setAngle(cadOffset.getAngle());
                offSet.setName(cadOffset.getName());
                offSet.setRadius(cadOffset.getRadius());

                offSetLists.add(offSet);
            }
            return offSetLists;
        }
        return null;
    }

    /**
     * 获取造型点列表
     *
     * @param cadPointList
     * @return
     */
    private List<PointList> getModelDetailPointList(List<WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.PointListDTO> cadPointList) {
        if (CollUtil.isNotEmpty(cadPointList)) {
            List<PointList> pointList = new ArrayList<>();
            for (WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.PointListDTO cadPoint : cadPointList) {
                PointList point = new PointList();
                point.setLineId(cadPoint.getLineID());
                point.setPointId(cadPoint.getPointID());
                point.setPointX(cadPoint.getPointX());
                point.setPointY(cadPoint.getPointY());
                point.setCurve(cadPoint.getCurve());
                point.setDepth(cadPoint.getDepth());
                point.setRadius(cadPoint.getRadius());

                pointList.add(point);
            }
            return pointList;
        }
        return null;
    }

    /**
     * 获取造型轮廓
     *
     * @param cadOutline
     * @return
     */
    private List<IContourData> getOriginModelingOutlineList(WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.OriginModelingDTO.OutlineDTO cadOutline) {
        if (ObjectUtil.isNull(cadOutline)) {
            return null;
        }
        List<Double> buls = cadOutline.getBuls();
        List<WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.OriginModelingDTO.OutlineDTO.PtsDTO> pts = cadOutline.getPts();
        if (CollUtil.isNotEmpty(pts) && CollUtil.isNotEmpty(buls)) {
            List<IContourData> outlineList = new ArrayList<>();
            for (int i = 0; i < pts.size(); i++) {
                IContourData iContourData = new IContourData();
                Point point = new Point();
                point.setX(pts.get(i).getX());
                point.setY(pts.get(i).getY());
                iContourData.setPts(point);
                iContourData.setBuls(buls.get(i));
                outlineList.add(iContourData);
            }
            return outlineList;
        }
        return null;
    }

    /**
     * 获取侧面造型明细
     *
     * @param cadSideModelDetailList
     * @return
     */
    private List<ModelDetail> getSideDetail(List<WebCadDataBlockReqVO.PointInfoDTO.SideModelDetailDTO> cadSideModelDetailList, List<WebCadDataBlockReqVO.PointInfoDTO.SideModelDetailDTO> cadSide2DModelDetail) {
        // 合并侧面2v刀路列表
        cadSideModelDetailList.addAll(cadSide2DModelDetail);
        if (CollUtil.isNotEmpty(cadSideModelDetailList)) {
            List<ModelDetail> modelDetails = new ArrayList<>();
            // 侧面造型和侧面2v刀路合并，序号从头计算不使用cad的
            int modelId = 1;
            for (WebCadDataBlockReqVO.PointInfoDTO.SideModelDetailDTO cadSideModelDetail : cadSideModelDetailList) {
                ModelDetail modelDetail = new ModelDetail();
                modelDetail.setModelID(modelId++);
                modelDetail.setLineID(cadSideModelDetail.getLineID());
                modelDetail.setFaceType(cadSideModelDetail.getFace());
                modelDetail.setDepth(cadSideModelDetail.getDepth());
                modelDetail.setKnifeName(cadSideModelDetail.getKnifeName());
                modelDetail.setKnifeRadius(cadSideModelDetail.getKnifeRadius());

                WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.OriginModelingDTO cadSideOriginModeling = cadSideModelDetail.getOriginModeling();
                if (ObjectUtil.isNotNull(cadSideOriginModeling)) {
                    IOriginModelingData originModelingData = new IOriginModelingData();
                    originModelingData.setAddLen(cadSideOriginModeling.getAddLen());
                    originModelingData.setAddWidth(cadSideOriginModeling.getAddWidth());
                    originModelingData.setAddDepth(cadSideOriginModeling.getAddDepth());
                    originModelingData.setThickness(cadSideOriginModeling.getThickness());
                    originModelingData.setDir(cadSideOriginModeling.getDir());
                    originModelingData.setKnifeRadius(cadSideOriginModeling.getKnifeRadius());

                    originModelingData.setOutline(getOriginModelingOutlineList(cadSideOriginModeling.getOutline()));

                    originModelingData.setHoles(getModelingHoles(cadSideOriginModeling.getHoles()));

                    modelDetail.setOriginModeling(originModelingData);
                }
                modelDetail.setPointList(getModelDetailPointList(cadSideModelDetail.getPointList()));

                modelDetail.setOffSetList(getModelDetailOffsetList(cadSideModelDetail.getOffSetList()));

                modelDetails.add(modelDetail);
            }
            return modelDetails;
        }
        return null;
    }

    /**
     * 获取孤岛造型
     *
     * @param cadSideHoles
     * @return
     */
    private List<List<IContourData>> getModelingHoles(List<WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.OriginModelingDTO.HolesDTO> cadSideHoles) {
        if (CollUtil.isNotEmpty(cadSideHoles)) {
            List<List<IContourData>> icontourDataList = new ArrayList<>();
            for (WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.OriginModelingDTO.HolesDTO sideHole : cadSideHoles) {
                List<IContourData> contourDatas = new ArrayList<>();
                List<WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.OriginModelingDTO.HolesDTO.PtsDTO> pts = sideHole.getPts();
                List<Double> buls = sideHole.getBuls();
                for (int i = 0; i < pts.size(); i++) {
                    IContourData iContourData = new IContourData();
                    WebCadDataBlockReqVO.PointInfoDTO.ModelDetailDTO.OriginModelingDTO.HolesDTO.PtsDTO ptsDTO = pts.get(i);
                    Double bul = buls.get(i);
                    iContourData.setBuls(bul);
                    iContourData.setPts(new Point(ptsDTO.getX(), ptsDTO.getY(), 0.0));
                    contourDatas.add(iContourData);
                }
                icontourDataList.add(contourDatas);
            }
            return icontourDataList;
        }
        return null;
    }

    /**
     * 获取板件备注
     *
     * @param block
     * @return
     */
    private WebCadDataBlockRemarkVO getPlateRemark(WebCadDataBlockReqVO block) {
        WebCadDataBlockRemarkVO blockRemark = new WebCadDataBlockRemarkVO();

        List<List<String>> remarks = block.getAllRemarkList();
        if (CollUtil.isEmpty(remarks)) {
            return blockRemark;
        }

        List<String> blockRemarkList = new ArrayList<>();
        for (List<String> remark : remarks) {
            if (CollUtil.isNotEmpty(remark) && remark.size() == 2) {
                String key = remark.get(0);
                String value = remark.get(1);

                if ("#extra".equals(key)) {
                    blockRemark.setExtraObject(JSON.parseObject(value));
                } else if ("#drills".equals(key)) {
                    blockRemark.setDrillsObj(JSON.parseArray(value));
                } else {
                    blockRemarkList.add(value);
                }
            }
        }
        blockRemark.setRemarks(blockRemarkList);
        return blockRemark;
    }

    /**
     * 生成自定义板编号
     *
     * @param plateDO
     * @param cadCustBlockNo cad板号
     */
    private void generateCustomPlateNo(PlateDO plateDO, Integer cadCustBlockNo) {
        if (!isFirstPlate) {
            isFirstPlate = true;
        }
        // 配置不为空时，生成自定义板编号
        if (ObjectUtil.isNotNull(plateNoGenerateConfigVO)) {
            customPlateNoGenerateService.generateCustomPlateNo(orderId, plateDO, plateNoGenerateConfigVO, isFirstPlate);
        } else {
            // 配置为空的时候，使用cad的板编号
            if (ObjectUtil.isNotNull(cadCustBlockNo)) {
                plateDO.setCustomPlateNo(String.valueOf(cadCustBlockNo));
            }
        }
    }

    /**
     * 解析板件加工组
     *
     * @param orderBodyDO
     * @param block
     * @param plateId
     */
    private void analyzeBlockProcessGroup(OrderBodyDO orderBodyDO, WebCadDataBlockReqVO block, Long plateId) {
        Long bodyId = orderBodyDO.getId();
        Long roomId = orderBodyDO.getRoomId();

        List<Integer> groupIds = block.getGroupIds();
        if (CollUtil.isNotEmpty(groupIds)) {
            // 加工组缓存存在，一个加工组一个orderGroup+orderItem
            for (Integer groupId : groupIds) {
                WebCadDataGroupInfoReqVO groupInfo = processGroupMap.get(groupId);
                String groupMapKey = orderBodyDO.getMultiRoomBodyName() + groupInfo.getGroupName();
                OrderGroupDO orderGroupDO = orderGroupMap.get(groupMapKey);
                // 房间+柜体+加工组名称存在累加板件和异形数量，不存在新增groupDO和orderGroupMap缓存
                if (ObjectUtil.isNull(orderGroupDO)) {
                    Long orderGroupId = (Long) snowFlakeGenerator.nextId(null);
                    orderGroupDO = OrderGroupDO
                            .builder()
                            .id(orderGroupId)
                            .organId(organId)
                            .orderId(orderId)
                            .bodyId(bodyId)
                            .groupTypeId((Long) snowFlakeGenerator.nextId(null))
                            .groupTypeName(groupInfo.getGroupTypeName())
                            .name(groupInfo.getGroupTypeName())
                            .width(groupInfo.getWidth())
                            .height(groupInfo.getHeight())
                            .depth(groupInfo.getDepth())
                            .multiNum(0)
                            .plateNum(0)
                            .unregularNum(0)
                            .filename("无")
                            .remark("无")
                            .deleted(false)
                            .build();
                    orderGroupDO.setCreator(operatorName);
                    orderGroupDO.setUpdater(operatorName);
                    orderGroupDO.setCreateTime(now);
                    orderGroupDO.setUpdateTime(now);

                    orderGroupMap.put(groupMapKey, orderGroupDO);
                } else {
                    orderGroupDO.setPlateNum(orderGroupDO.getPlateNum() + 1);
                    orderGroupDO.setUnregularNum(orderGroupDO.getUnregularNum() + BooleanUtil.toInt(block.isSpecialShape()));
                }

                OrderItemDO orderItemDO = OrderItemDO
                        .builder()
                        .id((Long) snowFlakeGenerator.nextId(null))
                        .orderId(orderId)
                        .type(OrderItemTypeEnum.PLATE_ITEM.getStatus())
                        .roomId(roomId)
                        .bodyId(bodyId)
                        .groupId(orderGroupDO.getId())
                        .plateId(plateId)
                        .packageId(0L)
                        .partsId(0L)
                        .num(1.0)
                        .organId(organId)
                        .build();
                orderItemDOS.add(orderItemDO);
                orderItemBatchInsertWithinThreshold(orderItemDOS, false);
            }
        } else {
            // 没有归属的加工组，只创建一个orderItem
            OrderItemDO orderItemDO = OrderItemDO
                    .builder()
                    .id((Long) snowFlakeGenerator.nextId(null))
                    .orderId(orderId)
                    .type(OrderItemTypeEnum.PLATE_ITEM.getStatus())
                    .roomId(roomId)
                    .bodyId(bodyId)
                    .plateId(plateId)
                    .packageId(0L)
                    .partsId(0L)
                    .num(1.0)
                    .organId(organId)
                    .build();
            orderItemDOS.add(orderItemDO);
            orderItemBatchInsertWithinThreshold(orderItemDOS, false);
        }
    }

    /**
     * 解析配件列表
     *
     * @param parts
     */
    private void analyzeParts(List<WebCadDataDoubleRoomTreeReqVO> parts) {
        if (ObjectUtil.isNull(parts)) {
            return;
        }
        log.debug("====================【cad拆单获取封边配置开始】====================");
        // 获取系统配置-封边对应配置
        getOrgSealEdgeConfig();
        log.debug("====================【cad拆单获取封边配置结束】====================");

        for (WebCadDataDoubleRoomTreeReqVO room : parts) {
            // 房间名
            String roomName = room.getName();

            // 同步房间直接使用roomId
            Long roomId;
            Long existRoomId = existRoomIdMap.get(roomName);

            if (ObjectUtil.isNotNull(existRoomId)) {
                roomId = existRoomId;
            } else {
                // 可能有配件房间柜体不在板件的情况，再查一次
                // 查询当前生产单的所有房间
                List<String> roomNames = parts.stream().map(WebCadDataDoubleRoomTreeReqVO::getName).collect(Collectors.toList());

                Map<String, Long> existPartsRoomIdMap = orderBodyMapper.selectMaps(
                                new QueryWrapper<OrderBodyDO>()
                                        .select("room_name,MIN(room_id) as room_id")
                                        .eq("order_id", orderId)
                                        .eq("organ_id", organId)
                                        .eq("deleted", false)
                                        .in("room_name", roomNames)
                                        .groupBy("room_name")).stream()
                        .collect(Collectors.toMap(
                                m -> String.valueOf(m.get("room_name")),
                                m -> ((Number) m.get("room_id")).longValue()
                        ));
                Long existPartRoomId = existPartsRoomIdMap.get(roomName);
                if (ObjectUtil.isNotNull(existPartRoomId)) {
                    roomId = existPartRoomId;
                } else {
                    roomId = (Long) snowFlakeGenerator.nextId(null);
                    existRoomIdMap.put(roomName, roomId);
                }
            }

            // 柜体列表
            List<WebCadDataDoubleRoomTreeReqVO.ChildrenDTO> roomBoxs = room.getChildren();
            for (WebCadDataDoubleRoomTreeReqVO.ChildrenDTO box : roomBoxs) {
                String boxName = box.getName();

                // 柜体下的板件
                List<WebCadDataPartsReqVO.BlockObjectListDTO> listBody = box.getObjList();

                String roomNameKey = roomName + boxName;
                // 获取缓存中的成本数量
                Integer count = roomBodyMap.get(roomNameKey);

                if (ObjectUtil.isNull(count)) {
                    // 房间+柜体不在成倍缓存中, 再检查bodyMap, 再没有创建房间，缓存房间到bodyMap
                    createPartsUnknownBody(roomId, roomName, boxName, listBody);
                } else {
                    multipleCreateProcessGroup(count, roomNameKey, listBody);
                }
            }
        }
        orderPartBatchInsertWithinThreshold(orderPartsDOS, true);
    }

    /**
     * 成倍创建配件加工组和item
     *
     * @param count
     * @param roomNameKey
     * @param listBody
     */
    private void multipleCreateProcessGroup(Integer count, String roomNameKey, List<WebCadDataPartsReqVO.BlockObjectListDTO> listBody) {
        // 成倍数量
        for (int j = 0; j < count; j++) {
            // 获取板材已经创建的柜体，缓存key：房间名+柜体名+成倍序号
            OrderBodyDO orderBodyDO = bodyMap.get(roomNameKey + j);
            if (ObjectUtil.isNull(orderBodyDO)) {
                return;
            }
            // 解析配件的加工组，创建对应的orderItem
            for (WebCadDataPartsReqVO.BlockObjectListDTO part : listBody) {
                analyzePartProcessGroup(orderBodyDO, part);
            }
        }
    }

    /**
     * 创建不需要成倍的房间柜体以及其下的板件
     *
     * @param roomName
     * @param bodyName
     * @param listBody
     */
    private void createPartsUnknownBody(Long roomId, String roomName, String bodyName, List<WebCadDataPartsReqVO.BlockObjectListDTO> listBody) {
        String roomBodyKey = roomName + bodyName;
        OrderBodyDO orderBodyDO = bodyMap.get(roomBodyKey);
        if (ObjectUtil.isNull(orderBodyDO)) {
            Long bodyId = (Long) snowFlakeGenerator.nextId(null);
            orderBodyDO = OrderBodyDO.builder().id(bodyId).orderId(orderId).organId(organId)
                    .roomId(roomId).roomName(roomName).name(bodyName).width(0.0).height(0.0)
                    .depth(0.0).multiNum(0).plateNum(0).unregularNum(0).filename("无").remark("无").deleted(false).build();
            orderBodyDO.setCreator(operatorName);
            orderBodyDO.setUpdater(operatorName);
            orderBodyDO.setCreateTime(now);
            orderBodyDO.setUpdateTime(now);

            // 缓存成倍的柜体信息
            bodyMap.put(roomBodyKey, orderBodyDO);
        }

        for (WebCadDataPartsReqVO.BlockObjectListDTO part : listBody) {
            analyzePartProcessGroup(orderBodyDO, part);
        }
    }

    private void analyzePartProcessGroup(OrderBodyDO orderBodyDO, WebCadDataPartsReqVO.BlockObjectListDTO part) {
        Long bodyId = orderBodyDO.getId();
        Long roomId = orderBodyDO.getRoomId();

        // 获取orderPart
        analyzeOrderPart(part);

        // 遍历加工组信息，生成对应的orderItem
        List<Integer> groupIds = part.getGroupIds();
        if (CollUtil.isNotEmpty(groupIds)) {
            Double partNum = 0.0;
            // 带加工组的配件增加item只记录配件id和数量
            partNum += part.getNum();
            for (Integer groupId : groupIds) {
                WebCadDataGroupInfoReqVO groupInfo = processGroupMap.get(groupId);
                String groupMapKey = orderBodyDO.getMultiRoomBodyName() + groupInfo.getGroupName();
                OrderGroupDO orderGroupDO = orderGroupMap.get(groupMapKey);
                // 房间+柜体+加工组名称存在累加配件item，不存在新增groupDO和orderGroupMap缓存
                if (ObjectUtil.isNull(orderGroupDO)) {
                    Long orderGroupId = (Long) snowFlakeGenerator.nextId(null);
                    orderGroupDO = OrderGroupDO
                            .builder()
                            .id(orderGroupId)
                            .organId(organId)
                            .orderId(orderId)
                            .bodyId(bodyId)
                            .groupTypeId((Long) snowFlakeGenerator.nextId(null))
                            .groupTypeName(groupInfo.getGroupTypeName())
                            .name(groupInfo.getGroupTypeName())
                            .width(groupInfo.getWidth())
                            .height(groupInfo.getHeight())
                            .depth(groupInfo.getDepth())
                            .multiNum(0)
                            .plateNum(0)
                            .unregularNum(0)
                            .filename("无")
                            .remark("无")
                            .deleted(false)
                            .build();
                    orderGroupDO.setCreator(operatorName);
                    orderGroupDO.setUpdater(operatorName);
                    orderGroupDO.setCreateTime(now);
                    orderGroupDO.setUpdateTime(now);

                    orderGroupMap.put(groupMapKey, orderGroupDO);
                }

                OrderItemDO orderItemDO = OrderItemDO
                        .builder()
                        .id((Long) snowFlakeGenerator.nextId(null))
                        .orderId(orderId)
                        .type(OrderItemTypeEnum.PLATE_ITEM.getStatus())
                        .roomId(roomId)
                        .bodyId(bodyId)
                        .groupId(orderGroupDO.getId())
                        .partsId(part.getImesPartsId())
                        .packageId(0L)
                        .plateId(0L)
                        .num(part.getNum())
                        .organId(organId)
                        .build();
                orderItemDOS.add(orderItemDO);
                orderItemBatchInsertWithinThreshold(orderItemDOS, false);
            }
            OrderItemDO orderItemDO = OrderItemDO
                    .builder()
                    .id((Long) snowFlakeGenerator.nextId(null))
                    .orderId(orderId)
                    .type(OrderItemTypeEnum.PLATE_ITEM.getStatus())
                    .roomId(roomId)
                    .bodyId(bodyId)
                    .partsId(part.getImesPartsId())
                    .packageId(0L)
                    .plateId(0L)
                    .num(partNum)
                    .organId(organId)
                    .build();
            orderItemDOS.add(orderItemDO);
            orderItemBatchInsertWithinThreshold(orderItemDOS, false);
        } else {
            OrderItemDO orderItemDO = OrderItemDO
                    .builder()
                    .id((Long) snowFlakeGenerator.nextId(null))
                    .orderId(orderId)
                    .type(OrderItemTypeEnum.PLATE_ITEM.getStatus())
                    .roomId(roomId)
                    .bodyId(bodyId)
                    .partsId(part.getImesPartsId())
                    .packageId(0L)
                    .plateId(0L)
                    .num(part.getNum())
                    .organId(organId)
                    .build();
            orderItemDOS.add(orderItemDO);
            orderItemBatchInsertWithinThreshold(orderItemDOS, false);
        }
    }

    /**
     * 分组配件解析出orderParts，id回显到cad配件
     *
     * @param part
     */
    private void analyzeOrderPart(WebCadDataPartsReqVO.BlockObjectListDTO part) {
        boolean composite = part.getIsComposite();
        String partType = part.getType();
        String factory = part.getFactory();
        String model = part.getModel();
        String spec = part.getSpec();
        String height = part.getHeight();
        String width = part.getWidth();
        String thickness = part.getThickness();
        String unit = part.getUnit();
        String brand = part.getBrand();

        // 分类配件的键组合
        String groupKey = composite + partType + factory + model + spec + height + width + thickness + unit + brand;

        Long orderPartId = orderPartMap.get(groupKey);
        if (ObjectUtil.isNull(orderPartId)) {
            Long partId = (Long) snowFlakeGenerator.nextId(null);

            String color = null;
            String material = null;
            if (PART_CATEGORY_ONE.equals(partType)) {
                WebCadDataPartsReqVO.BlockObjectListDTO.GroupDataDTO partGroupData = part.getGroupData();
                color = partGroupData.getColor();
                material = partGroupData.getMaterial();
                // 封边条宽度从系统配置中获取宽度对应
                sealEdgeWidthMatch(part);
                // 规格可能修改，再获取一次
                spec = part.getSpec();
            } else if (PART_CATEGORY_THREE.equals(partType)) {
                color = getFieldFromSpec(part.getSpec(), 2);
                material = getFieldFromSpec(part.getSpec(), 1);
            }

            String type = changePartType(partType, part.getIsComposite());
            // todo remark、备注信息到es
            OrderPartsDO orderPartsDO = OrderPartsDO.builder()
                    .id(partId)
                    .orderId(orderId)
                    .color(getEmpty(color))
                    .category(type)
                    .type(type)
                    .goodsId(EMPTY_STRING)
                    .length(NumberUtil.parseDouble(part.getHeight()))
                    .width(NumberUtil.parseDouble(part.getWidth()))
                    .thickness(NumberUtil.parseDouble(part.getThickness()))
                    .isComposite(part.getIsComposite())
                    .name(part.getName())
                    .material(getEmpty(material))
                    .model(getEmpty(model))
                    .spec(getEmpty(spec))
                    .brand(getEmpty(brand))
                    .factory(getEmpty(factory))
                    .unit(part.getUnit())
                    .price(0.0)
                    .subparts(EMPTY_STRING)
                    .remark(getEmpty(part.getRemark()))
                    .organId(organId)
                    .deleted(false)
                    .build();
            orderPartsDO.setCreator(operatorName);
            orderPartsDO.setUpdater(operatorName);
            orderPartsDO.setCreateTime(now);
            orderPartsDO.setUpdateTime(now);
            orderPartsDOS.add(orderPartsDO);
            orderPartBatchInsertWithinThreshold(orderPartsDOS, false);

            // orderpart id回显到配件
            part.setImesPartsId(partId);

            orderPartMap.put(groupKey, partId);
        } else {
            // orderpart id回显到配件
            part.setImesPartsId(orderPartId);
        }
    }

    /**
     * 从规格中获取属性，例：material、color
     *
     * @return
     */
    private String getFieldFromSpec(String spec, int index) {
        if (StringUtils.isNotEmpty(spec)) {
            String[] specSplit = spec.split("\\|");
            if (specSplit.length > index) {
                return specSplit[index];
            }
        }
        return null;
    }


    /**
     * 封边条宽度匹配，获取厚度
     *
     * @param part
     */
    private void sealEdgeWidthMatch(WebCadDataPartsReqVO.BlockObjectListDTO part) {
        // 获取宽度、厚度
        WebCadDataPartsReqVO.BlockObjectListDTO.GroupDataDTO partGroupData = part.getGroupData();

        if (ObjectUtil.isNotNull(partGroupData)) {
            part.setThickness(String.valueOf(partGroupData.getSize()));
            Integer thickness = partGroupData.getThickness();

            // 是否匹配上系统配置的封边条宽度配置，对应上了需要同步修改spec的中的内容
            boolean sealEdgeConfigMatch = false;
            String matchWidth = null;
            for (SystemConfigSealEdgeRespDTO configSealEdgeRespDTO : sealEdgeConfigList) {
                // 宽度处于配置范围，宽取值作为最终配件宽度
                if (thickness >= configSealEdgeRespDTO.getWidthMin() && thickness <= configSealEdgeRespDTO.getWidthMax()) {
                    matchWidth = String.valueOf(configSealEdgeRespDTO.getWidthValue());
                    part.setWidth(matchWidth);
                    sealEdgeConfigMatch = true;
                    break;
                }
            }
            if (sealEdgeConfigMatch) {
                part.setSpec(modifySealEdgeSpec(part.getSpec(), matchWidth));
            } else {
                // 没有匹配的对应直接使用板厚做宽度
                part.setWidth(String.valueOf(thickness));
            }
        }
    }

    /**
     * 根据对应的宽度修改spec规格中的第二段宽度
     *
     * @param spec
     * @param width
     * @return
     */
    private String modifySealEdgeSpec(String spec, String width) {
        if (StringUtils.isNotEmpty(spec)) {
            String[] specSplit = spec.split("-");
            // 例：15mm-18mm
            if (specSplit.length == 2) {
                return specSplit[0] + "-" + width + "mm";
            }
            // 例：9mm-18mm-经典檀木
            if (specSplit.length == 3) {
                return specSplit[0] + "-" + width + "mm-" + specSplit[2];
            }
        }
        return spec;
    }

    /**
     * value为空返回EMPTY_STRING
     *
     * @param value
     * @return
     */
    private String getEmpty(String value) {
        return StringUtils.defaultIfEmpty(value, EMPTY_STRING);
    }

    /**
     * value为空返回0.0
     *
     * @param value
     * @return
     */
    private double getZeroDouble(Double value) {
        return ObjectUtil.defaultIfNull(value, 0.0);
    }

    /**
     * value为空返回false
     *
     * @param value
     * @return
     */
    private Boolean getDefaultFalse(Boolean value) {
        return ObjectUtil.defaultIfNull(value, false);
    }

    /**
     * 配件类型转换
     *
     * @param objectType
     * @param isComposite
     * @return
     */
    private String changePartType(String objectType, boolean isComposite) {
        if (PART_CATEGORY_ONE.equals(objectType)) {
            return PART_CATEGORY_ONE;
        } else {
            if (isComposite) {
                return PART_CATEGORY_THREE;
            } else {
                return PART_CATEGORY_TWO;
            }
        }
    }

    /**
     * 每达到阈值就批量插入一次
     *
     * @param baseBatchMapper
     * @param list
     * @param isLast          是否最后一次插入，不是就需要清理list
     */
    private void orderInfoBatchInsertWithinThreshold(BaseBatchMapper baseBatchMapper, List list, boolean isLast) {
        // 达到批量的阈值就做一次插入
        if (CollUtil.isNotEmpty(list) && (list.size() >= BATCH_THRESHOLD_NUMBER || isLast)) {
            baseBatchMapper.insertBatchSomeColumn(list);
            if (!isLast) {
                // 存储完成清理 list
                list.clear();
            }
        }
    }

    private void orderPlateBatchInsertWithinThreshold(List<PlateDO> list, boolean isLast) {
        // 达到批量的阈值就做一次插入
        if (CollUtil.isNotEmpty(list) && (list.size() >= BATCH_THRESHOLD_NUMBER || isLast)) {
            String sql = "INSERT INTO order_plate  (id,organ_id,order_id,name,plate_no,type,goods_id,width,height,thickness,split_width,split_height,split_thickness,seal_left,seal_right,seal_up,seal_down,area,texture,hole_face,hole_arrange,unregular_point_count,front_hole_count,back_hole_count,side_hole_count,front_model_count,back_model_count,is_door,open_door_type,offset_x,offset_y,is_arc_across,module_type_id,is_special_shaped,is_sculpt,is_side_sculpt,is_2v,is_side_2v,is_row_hole,is_optimized,is_cutted,filter_type,remark,is_cancel,deleted,custom_plate_no,create_time,update_time,creator,updater) VALUES    (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int index) throws SQLException {
                    PlateDO item = list.get(index);
                    ps.setLong(1, item.getId());
                    ps.setLong(2, item.getOrganId());
                    ps.setLong(3, item.getOrderId());
                    ps.setString(4, item.getName());
                    ps.setString(5, item.getPlateNo());
                    ps.setInt(6, item.getType());
                    ps.setLong(7, item.getGoodsId());
                    ps.setBigDecimal(8, item.getWidth());
                    ps.setBigDecimal(9, item.getHeight());
                    ps.setBigDecimal(10, item.getThickness());
                    ps.setBigDecimal(11, item.getSplitWidth());
                    ps.setBigDecimal(12, item.getSplitHeight());
                    ps.setBigDecimal(13, item.getSplitThickness());
                    ps.setBigDecimal(14, item.getSealLeft());
                    ps.setBigDecimal(15, item.getSealRight());
                    ps.setBigDecimal(16, item.getSealUp());
                    ps.setBigDecimal(17, item.getSealDown());
                    ps.setBigDecimal(18, item.getArea());
                    ps.setInt(19, item.getTexture());
                    ps.setInt(20, item.getHoleFace());
                    ps.setInt(21, item.getHoleArrange());
                    ps.setInt(22, item.getUnregularPointCount());
                    ps.setInt(23, item.getFrontHoleCount());
                    ps.setInt(24, item.getBackHoleCount());
                    ps.setInt(25, item.getSideHoleCount());
                    ps.setInt(26, item.getFrontModelCount());
                    ps.setInt(27, item.getBackModelCount());
                    ps.setBoolean(28, item.getIsDoor());
                    ps.setInt(29, item.getOpenDoorType());
                    ps.setBigDecimal(30, item.getOffsetX());
                    ps.setBigDecimal(31, item.getOffsetY());
                    ps.setBoolean(32, item.getIsArcAcross());
                    ps.setLong(33, item.getModuleTypeId());
                    ps.setBoolean(34, item.getIsSpecialShaped());
                    ps.setBoolean(35, item.getIsSculpt());
                    ps.setBoolean(36, item.getIsSideSculpt());
                    ps.setBoolean(37, item.getIs2v());
                    ps.setBoolean(38, item.getIsSide2v());
                    ps.setBoolean(39, item.getIsRowHole());
                    ps.setBoolean(40, item.getIsOptimized());
                    ps.setInt(41, item.getIsCutted());
                    ps.setString(42, item.getFilterType());
                    ps.setString(43, item.getRemark());
                    ps.setBoolean(44, item.getIsCancel());
                    ps.setBoolean(45, item.getDeleted());
                    ps.setString(46, item.getCustomPlateNo());
                    ps.setTimestamp(47, Timestamp.valueOf(item.getCreateTime()));
                    ps.setTimestamp(48, Timestamp.valueOf(item.getUpdateTime()));
                    ps.setString(49, item.getCreator());
                    ps.setString(50, item.getUpdater());
                }

                @Override
                public int getBatchSize() {
                    return list.size();
                }
            });


            if (!isLast) {
                // 存储完成清理 list
                clearPlate();
            }
        }
    }

    private void clearPlate(){
        plateDOS =  ListUtils.newArrayListWithExpectedSize(BATCH_THRESHOLD_NUMBER);
    }

    private void orderItemBatchInsertWithinThreshold(List<OrderItemDO> list, boolean isLast) {
        // 达到批量的阈值就做一次插入
        if (CollUtil.isNotEmpty(list) && (list.size() >= BATCH_THRESHOLD_NUMBER || isLast)) {

            String sql = "INSERT INTO order_item (id,order_id,type,room_id,body_id,package_id,group_id,plate_id,parts_id,num,organ_id) VALUES    (?,?,?,?,?,?,?,?,?,?,?)";
            jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int index) throws SQLException {
                    OrderItemDO item = list.get(index);
                    ps.setLong(1, item.getId());
                    ps.setLong(2, item.getOrderId());
                    ps.setInt(3, item.getType());
                    ps.setLong(4, item.getRoomId());
                    ps.setLong(5, item.getBodyId());
                    ps.setLong(6, item.getPackageId());
                    if (item.getGroupId() != null) {
                        ps.setLong(7, item.getGroupId());
                    } else {
                        ps.setNull(7, Types.BIGINT);
                    }
                    ps.setLong(8, item.getPlateId());
                    ps.setLong(9, item.getPartsId());
                    ps.setDouble(10, item.getNum());
                    ps.setLong(11, item.getOrganId());
                }

                @Override
                public int getBatchSize() {
                    return list.size();
                }
            });


            if (!isLast) {
                // 存储完成清理 list
                clearItem();
            }
        }
    }

    private void clearItem(){
        orderItemDOS =  ListUtils.newArrayListWithExpectedSize(BATCH_THRESHOLD_NUMBER);
    }

    private void orderPartBatchInsertWithinThreshold(List<OrderPartsDO> list, boolean isLast) {
        // 达到批量的阈值就做一次插入
        if (CollUtil.isNotEmpty(list) && (list.size() >= BATCH_THRESHOLD_NUMBER || isLast)) {

            String sql = "INSERT INTO order_parts (id,organ_id,order_id,goods_id,name,color,material,category,type,width,length,thickness,model,spec,brand,factory,unit,price,is_composite,subparts,remark,deleted,create_time,update_time,creator,updater) VALUES    (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
            jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int index) throws SQLException {
                    OrderPartsDO item = list.get(index);
                    ps.setLong(1, item.getId());
                    ps.setLong(2, item.getOrganId());
                    ps.setLong(3, item.getOrderId());
                    ps.setString(4, item.getGoodsId());
                    ps.setString(5, item.getName());
                    ps.setString(6, item.getColor());
                    ps.setString(7, item.getMaterial());
                    ps.setString(8, item.getCategory());
                    ps.setString(9, item.getType());
                    ps.setDouble(10, item.getWidth());
                    ps.setDouble(11, item.getLength());
                    ps.setDouble(12, item.getThickness());
                    ps.setString(13, item.getModel());
                    ps.setString(14, item.getSpec());
                    ps.setString(15, item.getBrand());
                    ps.setString(16, item.getFactory());
                    ps.setString(17, item.getUnit());
                    ps.setDouble(18, item.getPrice());
                    ps.setBoolean(19, item.getIsComposite());
                    ps.setString(20, item.getSubparts());
                    ps.setString(21, item.getRemark());
                    ps.setBoolean(22, item.getDeleted());
                    ps.setTimestamp(23, Timestamp.valueOf(item.getCreateTime()));
                    ps.setTimestamp(24, Timestamp.valueOf(item.getUpdateTime()));
                    ps.setString(25, item.getCreator());
                    ps.setString(26, item.getUpdater());
                }

                @Override
                public int getBatchSize() {
                    return list.size();
                }
            });


            if (!isLast) {
                // 存储完成清理 list
                clearPart();
            }
        }
    }

    private void clearPart(){
        orderPartsDOS =  ListUtils.newArrayListWithExpectedSize(BATCH_THRESHOLD_NUMBER);
    }

    /**
     * 每达到阈值就批量插入一次生产单造型数据和压缩数据
     *
     * @param isLast 是否最后一次插入，不是就需要清理list
     */
    private void orderModelsBatchInsertWithinThreshold(boolean isLast) {
        // 达到批量的阈值就做一次插入
        if (CollUtil.isNotEmpty(orderModelDOS) && (orderModelDOS.size() >= BATCH_THRESHOLD_NUMBER || isLast)) {
            // 保存生产单造型数据
            orderInputProcessor.batchAsyncSaveModel(orderModelDOS);
            if (!isLast) {
                // 存储完成清理 list
                orderModelDOS = ListUtils.newArrayListWithExpectedSize(BATCH_THRESHOLD_NUMBER);
            }
        }
    }

    /**
     * 保存数据
     * orderBody、orderGroup
     */
    private void saveData() {
        // 分成1000一组
        List<List<OrderBodyDO>> bodyList = batchProcess(bodyMap.values().stream().toList());
        List<List<OrderGroupDO>> groupList = batchProcess(orderGroupMap.values().stream().toList());

        // 保存
        saveBody(bodyList);
        saveGroup(groupList);
    }

    /**
     * 插入柜体
     *
     * @param bodyList
     */
    private void saveBody(List<List<OrderBodyDO>> bodyList) {
        for (List<OrderBodyDO> bodys : bodyList) {
            String sql = "INSERT INTO order_body (id, organ_id, order_id, room_id, room_name, name, width, height, depth, multi_num, plate_num, unregular_num, filename, remark, deleted,create_time,update_time,creator,updater) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
            jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int index) throws SQLException {
                    OrderBodyDO orderBodyDO = bodys.get(index);
                    ps.setLong(1, orderBodyDO.getId());
                    ps.setLong(2, orderBodyDO.getOrganId());
                    ps.setLong(3, orderBodyDO.getOrderId());
                    ps.setLong(4, orderBodyDO.getRoomId());
                    ps.setString(5, orderBodyDO.getRoomName());
                    ps.setString(6, orderBodyDO.getName());
                    ps.setDouble(7, orderBodyDO.getWidth());
                    ps.setDouble(8, orderBodyDO.getHeight());
                    ps.setDouble(9, orderBodyDO.getDepth());
                    ps.setInt(10, orderBodyDO.getMultiNum());
                    ps.setInt(11, orderBodyDO.getPlateNum());
                    ps.setInt(12, orderBodyDO.getUnregularNum());
                    ps.setString(13, orderBodyDO.getFilename());
                    ps.setString(14, orderBodyDO.getRemark());
                    ps.setBoolean(15, orderBodyDO.getDeleted());
                    ps.setTimestamp(16, Timestamp.valueOf(orderBodyDO.getCreateTime()));
                    ps.setTimestamp(17, Timestamp.valueOf(orderBodyDO.getUpdateTime()));
                    ps.setString(18, orderBodyDO.getCreator());
                    ps.setString(19, orderBodyDO.getUpdater());
                }

                @Override
                public int getBatchSize() {
                    return bodys.size();
                }
            });
        }
    }

    /**
     * 插入加工组
     *
     * @param groupList
     */
    private void saveGroup(List<List<OrderGroupDO>> groupList) {
        for (List<OrderGroupDO> groups : groupList) {
            String sql = "INSERT INTO order_group (id, organ_id, order_id, body_id, group_type_id, group_type_name, name, width, height, depth, multi_num, plate_num, unregular_num, filename, remark, deleted,create_time,update_time,creator,updater) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?,?,?,?)";
            jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
                @Override
                public void setValues(PreparedStatement ps, int index) throws SQLException {
                    OrderGroupDO orderGroupDO = groups.get(index);
                    ps.setLong(1, orderGroupDO.getId());
                    ps.setLong(2, orderGroupDO.getOrganId());
                    ps.setLong(3, orderGroupDO.getOrderId());
                    ps.setLong(4, orderGroupDO.getBodyId());
                    ps.setLong(5, orderGroupDO.getGroupTypeId());
                    ps.setString(6, orderGroupDO.getGroupTypeName());
                    ps.setString(7, orderGroupDO.getName());
                    ps.setDouble(8, orderGroupDO.getWidth());
                    ps.setDouble(9, orderGroupDO.getHeight());
                    ps.setDouble(10, orderGroupDO.getDepth());
                    ps.setInt(11, orderGroupDO.getMultiNum());
                    ps.setInt(12, orderGroupDO.getPlateNum());
                    ps.setInt(13, orderGroupDO.getUnregularNum());
                    ps.setString(14, orderGroupDO.getFilename());
                    ps.setString(15, orderGroupDO.getRemark());
                    ps.setBoolean(16, orderGroupDO.getDeleted());
                    ps.setTimestamp(17, Timestamp.valueOf(orderGroupDO.getCreateTime()));
                    ps.setTimestamp(18, Timestamp.valueOf(orderGroupDO.getUpdateTime()));
                    ps.setString(19, orderGroupDO.getCreator());
                    ps.setString(20, orderGroupDO.getUpdater());
                }

                @Override
                public int getBatchSize() {
                    return groups.size();
                }
            });
        }
    }

    /**
     * 每batchSize条拆分dataList
     *
     * @param dataList
     */
    private <T> List<List<T>> batchProcess(List<T> dataList) {
        List<List<T>> resultList = new ArrayList<>();
        if (CollUtil.isEmpty(dataList)) {
            return resultList;
        }

        int total = dataList.size();
        for (int i = 0; i < total; i += BATCH_THRESHOLD_NUMBER) {
            int end = Math.min(i + BATCH_THRESHOLD_NUMBER, total);
            List<T> subList = dataList.subList(i, end);

            if (!subList.isEmpty()) {
                resultList.add(subList);
            }
        }
        return resultList;
    }

    /**
     * 更新生产单的板件总数
     */
    private void updateOrderPlateNum() {
        int version = orderDO.getVersion();
        Long orderId = orderDO.getId();
        int updated = orderMapper.update(new LambdaUpdateWrapper<OrderDO>()
                .eq(OrderDO::getId, orderId)
                .eq(OrderDO::getOrganId, organId)
                .eq(OrderDO::getVersion, version)
                .set(OrderDO::getPlateNum, currentPlateNum)
                .set(OrderDO::getArea, currentPlateArea)
                .set(OrderDO::getVersion, version + 1));
        if (updated == 0) {
            throw ServiceExceptionUtil.exception(ErrorCodeConstants.WEBCAD_ORDER_IMPORT_ORDER_UPDATE_CONCURRENCY_ERROR, orderId);
        }
    }

    /**
     * 新增order_goods/更新已有order_goods的板件总数
     */
    private void insertOrUpdatePlateNumGoods() {
        if (MapUtil.isNotEmpty(materialMap)) {
            // 分类新增和更新的goods
            List<GoodsDO> insertGoods = new ArrayList<>();
            List<GoodsDO> updateGoods = new ArrayList<>();
            materialMap.forEach((k, v) -> {
                if (v.isExist()) {
                    updateGoods.add(v);
                } else {
                    insertGoods.add(v);
                }
            });

            // 批量插入order_goods
            orderInfoBatchInsertWithinThreshold(goodsMapper, insertGoods, true);

            // 批量更新order_goods的plateNum
            for (GoodsDO updateDo : updateGoods) {
                int updated = goodsMapper.update(new LambdaUpdateWrapper<GoodsDO>()
                        .eq(GoodsDO::getId, updateDo.getId())
                        .eq(GoodsDO::getOrganId, organId)
                        .eq(GoodsDO::getVersion, updateDo.getVersion())
                        .set(GoodsDO::getPlateNum, updateDo.getPlateNum())
                        .set(GoodsDO::getVersion, updateDo.getVersion() + 1));
                if (updated == 0) {
                    throw ServiceExceptionUtil.exception(ErrorCodeConstants.WEBCAD_ORDER_IMPORT_GOODS_UPDATE_CONCURRENCY_ERROR, updateDo.getId());
                }
            }
        }
    }

    /**
     * 清空所有列表
     */
    private void clearAll() {
        roomBodyMap = null;
        bodyMap = null;
        orderGroupMap = null;
        materialMap = null;
        processGroupMap = null;
        existRoomIdMap = null;
        orderPartMap = null;

        plateDOS = null;
        orderItemDOS = null;
        orderPartsDOS = null;
        orderModelDOS = null;
        rawGoodsDOS = null;
        goodsDOS = null;
        sealEdgeConfigList = null;
    }
}
