package com.cf.imes.module.executor.util.fileConversion.admin.api.webcad;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.cf.imes.module.executor.dal.dataobject.goods.GoodsDO;
import com.cf.imes.module.executor.dal.dataobject.order.OrderDO;
import com.cf.imes.module.executor.dal.dataobject.orderBody.OrderBodyDO;
import com.cf.imes.module.executor.dal.dataobject.orderGroup.OrderGroupDO;
import com.cf.imes.module.executor.dal.dataobject.orderItem.OrderItemDO;
import com.cf.imes.module.executor.dal.dataobject.orderParts.OrderPartsDO;
import com.cf.imes.module.executor.dal.dataobject.plate.PlateDO;
import com.cf.imes.module.executor.dal.dataobject.rawgoods.RawGoodsDO;
import com.cf.imes.module.executor.enums.*;
import com.cf.imes.module.executor.util.fileConversion.admin.SnowflakeIdWorker3rd;
import com.cf.imes.module.executor.util.deviseData.dataTwo.*;
import com.cf.imes.module.system.api.dict.DictDataApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 实现数据格式转换
 * 使用自带id
 */
@Slf4j
@Component
public class ApiTypeRealize {

    @Resource
    private IdentifierGenerator identifierGenerator;

    @Resource
    private DictDataApi dictDataApi;

    @Resource
    SnowflakeIdWorker3rd idWorker;

    private Integer num = 0;

    private Integer groupNum = 0;

    private final static Integer X = 0;
    private final static Integer Y = 1;
    private final static Integer Z = 2;

    /**
     * @param dataPlates: 板件生产信息
     * @param dataParts:  配件信息
     * @param dataBody:   柜体信息
     * @param dataGoods:  商品信息
     * @param plates:     板件信息
     * @param dataModule: 加工组信息
     * @return Map<Long, List < ?>>
     * @author Administrator
     * @date 2024/5/6
     */
    public Map<String, List<?>> apiPlateDataChange(JSONObject dataPlates, JSONObject dataParts
            , JSONObject dataBody, JSONObject dataGoods
            , JSONObject plates, JSONObject dataModule
            , JSONObject dataBlocks, String orderNo) {

        Map<String, List<?>> map = new HashMap<>();

        // 生产单id
        Long orderId = (Long) identifierGenerator.nextId(null);

        // 生产单数据
        OrderDO orderDO = orderInfoChange(dataPlates, orderId, orderNo);
        List<OrderDO> order = new ArrayList<>();
        order.add(orderDO);
        // 商品信息数据 信息以全
        Map<String, Map<Integer, ?>> goodsInfoChange = rawGoodsInfoChange(dataGoods, orderId, dataBlocks);
//        System.out.println(" goodsInfoChange " + goodsInfoChange);
        List<GoodsDO> goodsDO = (List<GoodsDO>) goodsInfoChange.get("goodsDOS").values().stream()
                .collect(Collectors.toList());
        map.put("goodsDO", goodsDO);
        List<RawGoodsDO> rawGoodsDO = (List<RawGoodsDO>) goodsInfoChange.get("rawGoodsDOS").values().stream()
                .collect(Collectors.toList());
        map.put("rawGoodsDO", rawGoodsDO);
        // 柜体信息 少异形数量、板材数量
        Map<Integer, OrderBodyDO> bodyInfoChange = bodyInfoChange(dataBody, orderId);
//        System.out.println(" bodyInfoChange " + bodyInfoChange);
        // 加工组 少异形数量、板材数量
        Map<String, Map<Integer, ?>> group =

                groupInfoChange(dataModule, orderId, bodyInfoChange);
        Map<Integer, OrderGroupDO> orderGroupDO = (Map<Integer, OrderGroupDO>) group.get("orderGroup");
        map.put("groupDO", orderGroupDO.values().stream().collect(Collectors.toList()));
        Map<Integer, List<Integer>> groupLists = (Map<Integer, List<Integer>>) group.get("lists");
        // 配件
        Map<String, Map<Integer, ?>> partsDO = partsInfoChange(dataParts, orderId,
                (Map<Integer, GoodsDO>) goodsInfoChange.get("goodsDOS"), bodyInfoChange);
        Map<Integer, OrderPartsDO> orderPartsDO = (Map<Integer, OrderPartsDO>) partsDO.get("partsInfos");
        map.put("partsDO", orderPartsDO.values().stream().collect(Collectors.toList()));
        Map<Integer, OrderItemDO> partsItems = (Map<Integer, OrderItemDO>) partsDO.get("partsItems");

        List<OrderItemDO> itemsList = new ArrayList<>();
        partsItems = orderPartsChange(bodyInfoChange, orderGroupDO, groupLists, partsItems);// item补充
        itemsList.addAll(partsItems.values());
        // 板材 写库
        Map<String, Map<Integer, ?>> platesDO = platesInfoChange(dataPlates, plates, orderId,
                (Map<Integer, GoodsDO>) goodsInfoChange.get("goodsDOS"), bodyInfoChange, dataBlocks);
        Map<Integer, PlateDO> orderPlatesDO = (Map<Integer, PlateDO>) platesDO.get("platesInfos");
        map.put("platesDO", orderPlatesDO.values().stream().collect(Collectors.toList()));
        map.put("plateDetail", platesDO.get("plateDetail").values().stream().collect(Collectors.toList()));
        Map<Integer, OrderItemDO> platesItems = (Map<Integer, OrderItemDO>) platesDO.get("platesItems");
        Map<Integer, OrderBodyDO> bodyItemsPlates = (Map<Integer, OrderBodyDO>) platesDO.get("bodyInfos");
        platesItems = orderPartsChange(bodyInfoChange, orderGroupDO, groupLists, platesItems);// item补充
        itemsList.addAll(platesItems.values());
//        System.out.println("生产单数据 " + orderDO+ " 商品信息1 " + goodsDO + " 商品信息2 "
//                + rawGoodsDO + " 板材信息 " + new ArrayList<>(orderPlatesDO.values())
//                + " 配件信息 " + new ArrayList<>(orderPartsDO.values())
//                + " 柜体信息 " + new ArrayList<>(bodyInfoChange.values())
//                + " 加工组信息 " + orderGroupDO
//        + " 配件Item " + partsItems + " 板材Item " + platesItems);
        map.put("orderDO", order);
        map.put("itemDO", itemsList);
//        System.out.println(" bodyItemsPlates " + bodyItemsPlates);
        map.put("bodyDO", bodyItemsPlates.values().stream().collect(Collectors.toList()));
        return map;
    }


    /**
     * @param bodyInfoChange: BoxId body
     * @param orderGroupDO:   ModuleID group
     * @param groupLists:     ModuleID 板材、配件id
     * @param partsItems:     ItemID item
     * @return Map<Integer, OrderItemDO>
     * @author Administrator
     * @date 2024/5/8
     */
    public Map<Integer, OrderItemDO> orderPartsChange(Map<Integer, OrderBodyDO> bodyInfoChange, Map<Integer, OrderGroupDO> orderGroupDO,
                                                      Map<Integer, List<Integer>> groupLists, Map<Integer, OrderItemDO> partsItems) {

        groupLists.forEach((k, v) -> {
            v.forEach(v1 -> {
                if (partsItems.get(v1) != null) {
                    partsItems.get(v1).setGroupId(orderGroupDO.get(k).getId());
                    if (partsItems.get(v1).getPlateId() != null)
                        groupNum++;
                }
            });
            orderGroupDO.get(k).setPlateNum(groupNum);
            groupNum = 0;
        });

        return partsItems;
    }

    /**
     * 加工组 信息转换
     */
    private Map<String, Map<Integer, ?>> groupInfoChange(JSONObject dataModule, Long orderId, Map<Integer, OrderBodyDO> bodyInfoChange) {
        Map<String, Map<Integer, ?>> map = new HashMap<>();
        Map<Integer, OrderGroupDO> orderGroupDOs = new HashMap<>();// 加工组id 和 加工组信息
        Map<Integer, List<Integer>> groupLists = new HashMap<>();// 加工组id 和 详细信息


        if (dataModule.getJSONArray("value") != null &&
                !dataModule.getJSONArray("value").isEmpty()) {
            JSONArray groupsLists = dataModule.getJSONArray("value");
            for (int i = 0; i < groupsLists.size(); i++) {
                JSONObject group = groupsLists.getJSONObject(i);

                OrderGroupDO bodyInfo = OrderGroupDO.builder()
                        .id((Long) identifierGenerator.nextId(null))
                        .orderId(orderId)
                        .bodyId(bodyInfoChange.get(group.getInteger("BoxID")).getId())//group.getLong("BoxID")
                        .groupTypeId(Long.valueOf(group.getInteger("ModuleTypeID")))
                        .groupTypeName("无")
                        .name(group.getString("ModuleTypeName"))
                        .width(group.getDouble("Width"))
                        .height(group.getDouble("Length"))
                        .depth(group.getDouble("Thickness"))
                        .multiNum(0)
                        .plateNum(0)
                        .unregularNum(0)
                        .filename("无")
                        .remark("无")
                        .build();
                groupLists.put(group.getInteger("ModuleID"), jsonArrayToList(group.getJSONArray("ItemIDList")));
                orderGroupDOs.put(group.getInteger("ModuleID"), bodyInfo);
            }
        }

        map.put("lists", groupLists);
        map.put("orderGroup", orderGroupDOs);
        return map;
    }

    /**
     * 生产单信息转换
     *
     * @param dataPlates:
     * @return OrderDO
     * @author Administrator
     * @date 2024/4/30
     */
    public OrderDO orderInfoChange(JSONObject dataPlates, Long orderId, String orderNo) {
        // 获取 Orders 字段对应的数组
        JSONObject order = dataPlates.getJSONArray("Orders").getJSONObject(0);

        // 如果 Orders 数组不为空，则获取第一个订单对象
        if (order != null && !order.isEmpty()) {
            // 获取生产单信息
            // 使用 DateTimeFormatter 解析日期字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate orderDate = LocalDate.parse(order.getString("SaleDate"), formatter);
            LocalDate deliveryDate = LocalDate.parse(order.getString("DeliveryDate"), formatter);
            String orderRemark = "[" + orderNo + "]; ";

            OrderDO orderDO = OrderDO.builder()
                    .id(orderId)
                    .parentNo(0L)
                    .orderDate(orderDate.atStartOfDay())
                    .deliveryDate(deliveryDate.atStartOfDay())
                    .orderType(OrderTypeEnum.MAIN_ORDER.getStatus())
//                    .orderSort(0)
                    .dataType(DataTypeEnum.API_IMPORT.getStatus())
                    .status(OrderStatusEnum.NEW_ORDER.getStatus())
                    .customOrderNo(order.getString("CustomOrderNo"))
                    .customer(order.getString("Consigee"))
                    .address(order.getString("ConsigeeAddress"))
                    .phoneNumber(order.getString("ConsigeePhone"))
                    .dealer(order.getString("CustomName"))
                    .dealerPhoneNumber("无")
                    .salesman(order.getString("SalePerson"))
                    .splitter("无")
                    .remark(orderRemark + order.getString("Remark"))
                    .build();
            return orderDO;
        }
        return null;
    }


    /**
     * 板材数据转换成 Map<String, Object>
     */
    public Map<Integer, JSONObject> getBlocksDataByGoodsID(JSONObject dataBlocks) {
        Map<Integer, JSONObject> map = new HashMap<>();
        JSONArray ordersArray = dataBlocks.getJSONArray("List");
        if (ordersArray != null && !ordersArray.isEmpty()) {
            for (int i = 0; i < ordersArray.size(); i++) {
                JSONObject block = ordersArray.getJSONObject(i);
                map.put(block.getInteger("GoodsID"), block);
            }
        }
        return map;
    }


    /**
     * raw商品信息转换 和  商品信息转换
     *
     * @param dataRawGoods:
     * @param orderId:
     * @return Map<String, Map < Integer, ?>> String 标识 ， Integer:商品ID标识，RawGoodsDO:商品信息
     * @author Administrator
     * @date 2024/4/30
     */
    public Map<String, Map<Integer, ?>> rawGoodsInfoChange(JSONObject dataRawGoods, Long orderId , JSONObject dataBlocks) {
        Map<String, Map<Integer, ?>> map = new HashMap<>();
        Map<Integer, RawGoodsDO> rawGoodsDOS = new HashMap<>();
        Map<Integer, GoodsDO> goodsDOS = new HashMap<>();

        if (dataRawGoods.getJSONArray("List") != null &&
                !dataRawGoods.getJSONArray("List").isEmpty()) {
            JSONArray goodsLists = dataRawGoods.getJSONArray("List");
            for (int i = 0; i < goodsLists.size(); i++) {
                JSONObject goods = goodsLists.getJSONObject(i);

                RawGoodsDO rawGoodsDO = RawGoodsDO.builder()
                        .id((Long) identifierGenerator.nextId(null))
                        .orderId(orderId)
                        .rawGoodsId(goods.getString("GoodsID"))
                        .goodsName(goods.getString("GoodsName"))
                        .material(goods.getString("Material"))
                        .color(goods.getString("Color"))
                        .texture(goods.getInteger("Wave"))
                        .thickness(goods.getDouble("Thickness"))
                        .price(goods.getDouble("Price"))
                        .brand(goods.getString("Brand"))
                        .spec(goods.getString("Spec"))
                        .build();
                rawGoodsDOS.put(goods.getInteger("GoodsID"), rawGoodsDO);

                GoodsDO goodsDO = GoodsDO.builder()
                        .id((Long) identifierGenerator.nextId(null))
                        .orderId(orderId)
                        .rawGoodsId(String.valueOf(rawGoodsDO.getId()))
                        .goodsId(goods.getString("GoodsID")) // 先填这个，后面改
                        .goodsName(goods.getString("GoodsName"))
                        .material(goods.getString("Material"))
                        .color(goods.getString("Color"))
                        .texture(goods.getInteger("Wave"))
                        .width(BigDecimal.valueOf(goods.getDouble("Width")))
                        .height(BigDecimal.valueOf(goods.getDouble("Height")))
                        .thickness(BigDecimal.valueOf(goods.getDouble("Thickness")))
                        .price(BigDecimal.valueOf(goods.getDouble("Price")))
                        .brand(goods.getString("Brand"))
                        .spec(goods.getString("Spec"))
                        .build();
                goodsDOS.put(goods.getInteger("GoodsID"), goodsDO);

            }
        }

        map.put("rawGoodsDOS", rawGoodsDOS);
        map.put("goodsDOS", goodsDOS);
        return map;
    }

    /**
     * 柜体信息转换
     *
     * @param dataBody:
     * @return Map<Integer, OrderBodyDO> Integer:柜体ID标识，OrderBodyDO:柜体信息(差数据)
     * @author Administrator
     * @date 2024/4/30
     */
    private Map<Integer, OrderBodyDO> bodyInfoChange(JSONObject dataBody, Long orderId) {
        Map<Integer, OrderBodyDO> bodyInfos = new HashMap<>();

        if (dataBody.getJSONArray("List") != null &&
                !dataBody.getJSONArray("List").isEmpty()) {
            JSONArray bodyLists = dataBody.getJSONArray("List");
            for (int i = 0; i < bodyLists.size(); i++) {
                JSONObject body = bodyLists.getJSONObject(i);
                OrderBodyDO bodyInfo = OrderBodyDO.builder()
                        .id((Long) identifierGenerator.nextId(null))
                        .orderId(orderId)
                        .roomId(Long.valueOf(body.getString("RoomID")))
                        .roomName(body.getString("Room"))
                        .name(body.getString("Name"))
                        .width(body.getDouble("Width"))
                        .height(body.getDouble("Height"))
                        .depth(body.getDouble("Depth"))
                        .multiNum(0)
                        .plateNum(0)
                        .unregularNum(0)
                        .filename("无")
                        .remark("无")
                        .build();
                bodyInfos.put(body.getInteger("BoxID"), bodyInfo);

            }
        }
//        System.out.println(" bodyInfos " + bodyInfos);
        return bodyInfos;
    }


    /**
     * JSONArray转List<Integer>
     */
    public List<Integer> jsonArrayToList(JSONArray jsonArray) {
        List<Integer> list = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            list.add(jsonArray.getInteger(i));
        }
        return list;
    }

    /**
     * 配件信息转存
     *
     * @param value:      JSON数据
     * @param orderId:
     * @param goodsDOMap:
     * @return Map<Integer, OrderPartsDO> Integer指配件的dataId标识id
     * @author Administrator
     * @date 2024/4/30
     */
    public Map<String, Map<Integer, ?>> partsInfoChange(JSONObject value, Long orderId, Map<Integer, GoodsDO> goodsDOMap, Map<Integer, OrderBodyDO> bodyInfos) {
        Map<String, Map<Integer, ?>> map = new HashMap<>();
        Map<Integer, OrderPartsDO> partsInfos = new HashMap<>();
        Map<Integer, OrderItemDO> partsItem = new HashMap<>();

        if (value != null && !value.isEmpty()) {
            JSONArray partsLists = value.getJSONArray("List");
            for (int i = 0; i < partsLists.size(); i++) {
                JSONObject parts = partsLists.getJSONObject(i);
                Long partsId = (Long) identifierGenerator.nextId(null);
                OrderPartsDO partsInfo = OrderPartsDO.builder()
                        .id(partsId)
                        .orderId(orderId)
                        .goodsId(String.valueOf(goodsDOMap.get(parts.getInteger("GoodsID")) != null
                                ? goodsDOMap.get(parts.getInteger("GoodsID")).getId() : parts.getInteger("GoodsID")))
                        .name(parts.getString("Name"))
                        .material(String.valueOf(goodsDOMap.get(parts.getInteger("GoodsID")) != null
                                ? goodsDOMap.get(parts.getInteger("GoodsID")).getMaterial() : ""))
                        .type(parts.getString("ObjectType"))
                        .model(parts.getString("Model"))
                        .spec(parts.getString("Spec"))
                        .brand(parts.getString("Brand"))
                        .factory(parts.getString("Factory"))
                        .unit(parts.getString("Units"))
                        .price(parts.getDouble("Price"))
                        .isComposite(parts.getBoolean("IsComposite"))
                        .remark(parts.getString("Remark"))
                        .build();
                partsInfos.put(parts.getInteger("DataID"), partsInfo);

                // item 明细
                OrderItemDO item = OrderItemDO.builder()
                        .id((Long) identifierGenerator.nextId(null))
                        .orderId(orderId)
                        .type(OrderItemTypeEnum.PARTS_ITEM.getStatus())
                        .roomId(bodyInfos.get(parts.getInteger("BoxID")).getRoomId())
                        .bodyId(bodyInfos.get(parts.getInteger("BoxID")).getId())
                        .planId(0L)
                        .packageId(0L)
                        .groupId(0L)
                        .partsId(partsId)
                        .num(parts.getDouble("Num"))
                        .build();
                partsItem.put(parts.getInteger("DataID"), item);
            }
        }

        map.put("partsInfos", partsInfos);
        map.put("partsItems", partsItem);
        return map;
    }

    // 配件备注集合
    private String partsRemarkChange(JSONObject value) {
        List<Map<String, String>> mapList = new ArrayList<>();
        if (value != null && !value.isEmpty()) {
            Map<String, String> map = new HashMap<>();
            map.put("Remark", value.getString("Remark"));
            map.put("SpecExtras", value.getString("SpecExtras"));
            map.put("SpecialRemark", value.getString("SpecialRemark"));
            map.put("DoorRemark", value.getString("DoorRemark"));
            map.put("HingeRemark", value.getString("HingeRemark"));
            mapList.add(map);
        }
        // 转String
        String remark = JSON.toJSONString(mapList);
        return remark;
    }

    /**
     * 板材信息转换 写表 Integer指板材的ItemID板id 加一个板材自定义编号
     */
    private Map<String, Map<Integer, ?>> platesInfoChange(JSONObject value, JSONObject dataPlates, Long orderId,
                                                          Map<Integer, GoodsDO> goodsDOMap, Map<Integer, OrderBodyDO> bodyInfos,
                                                          JSONObject dataBlocks) {
        // 板材 写ES
        Map<Integer, PlateDetail> plateDetail = platesDetailChange(value);

        // 板材数据
        Map<Integer, JSONObject> plateMap = getBlocksData(dataBlocks);

        Map<String, Map<Integer, ?>> map = new HashMap<>();
        Map<Integer, PlateDO> platesInfos = new HashMap<>();
        Map<Integer, OrderItemDO> platesItem = new HashMap<>();

        if (dataPlates != null && !dataPlates.isEmpty()) {
            JSONArray plateLists = dataPlates.getJSONArray("List");
            for (int i = 0; i < plateLists.size(); i++) {
                long plateNo = idWorker.nextId();
                long obtainingTime = idWorker.obtainingTime();

                JSONObject plate = plateLists.getJSONObject(i);

                Integer type = Integer.valueOf(dictDataApi.parseDictData("order_plate_type",
                                plate.getString("BoardType"))
                        .getData().getValue());
                Long plateId = (Long) identifierGenerator.nextId(null);
                PlateDO plateInfo = PlateDO.builder()
                        .id(plateId)
                        .orderId(orderId)
                        .name(plate.getString("BoardName"))
//                        .plateNo(plate.getString("CustBlockNo"))
                        .plateNo((obtainingTime)+ Long.toString(plateNo).substring(2))
                        .type(type)

                        .goodsId(goodsDOMap.get(plate.getInteger("GoodsID")) != null
                                ? goodsDOMap.get(plate.getInteger("GoodsID")).getId() : plate.getInteger("GoodsID"))
//                        .width(BigDecimal.valueOf(plate.getDouble("CutWidth")))
//                        .height(BigDecimal.valueOf(plate.getDouble("CutWidth")))
//                        .thickness(goodsDOMap.get(plate.getInteger("GoodsID")) != null
//                                ? goodsDOMap.get(plate.getInteger("GoodsID")).getThickness() : BigDecimal.valueOf(0L))
                        .splitHeight(BigDecimal.valueOf(plate.getDouble("SpliteHeight")))
                        .splitThickness(BigDecimal.valueOf(plate.getDouble("SpliteThickness")))
                        .splitWidth(BigDecimal.valueOf(plate.getDouble("SpliteWidth")))
                        .sealLeft(BigDecimal.valueOf(plate.getDouble("SealedLeft")))
                        .sealRight(BigDecimal.valueOf(plate.getDouble("SealedRight")))
                        .sealUp(BigDecimal.valueOf(plate.getDouble("SealedUp")))
                        .sealDown(BigDecimal.valueOf(plate.getDouble("SealedDown")))
                        .area(plateDetail.get(plate.getInteger("BlockNo")).getSealAcreage())
                        .texture(plateDetail.get(plate.getInteger("BlockNo")).getTexture())

                        .holeFace(plateDetail.get(plate.getInteger("BlockNo")).getTypographicFace()) // 孔面类型
                        .holeArrange(0)  // 排孔类型  值无实际含义，默认初始化值
                        .unregularPointCount(0)// 异形孔个数  值无实际含义，默认初始化值

                        .frontHoleCount(plate.getInteger("FrontHoleCount"))
                        .sideHoleCount(plate.getInteger("BackHoleCount"))
                        .sideHoleCount(plate.getInteger("SideHoleCount"))
                        .frontModelCount(plate.getInteger("FrontModelCount"))
                        .backModelCount(plate.getInteger("BackModelCount"))
                        .isDoor(plateDetail.get(plate.getInteger("BlockNo")).getOpenDoorType() == 0)
                        .openDoorType(plate.getInteger("OpenDoorType"))
                        .offsetX(plateDetail.get(plate.getInteger("BlockNo")).getOffsetX())
                        .offsetY(plateDetail.get(plate.getInteger("BlockNo")).getOffsetY())
                        .isArcAcross(false)
                        .moduleTypeId(0L)
                        .isSculpt(plate.getBoolean("IsModel"))
                        .isSpecialShaped(plate.getBoolean("UnRegular"))
                        .isCancel(false)
                        .remark("无")
                        .build();

                // item 明细
                OrderItemDO itemPlate = OrderItemDO.builder()
                        .id((Long) identifierGenerator.nextId(null))
                        .orderId(orderId)
                        .type(OrderItemTypeEnum.PLATE_ITEM.getStatus())
                        .roomId(bodyInfos.get(plate.getInteger("BoxID")).getRoomId())
                        .bodyId(bodyInfos.get(plate.getInteger("BoxID")).getId())
                        .planId(0L)
                        .packageId(0L)
                        .groupId(0L)
                        .partsId(0L)
                        .plateId(plateId)
                        .num(1.0)
                        .build();

                if (plateDetail.get(plate.getInteger("BlockNo")) != null) {
                    plateDetail.get(plate.getInteger("BlockNo")).setPlateId(plateId)
                            .setExtraRemark(plate.getString("ExtraRemark"))
                            .setSpecialRemarkDei(plate.getString("SpecialRemark"))
                            .setExtraHandleRemark(plate.getString("ExtraHandleRemark"))
                            .setDrillsRemark(plate.getString("DrillsRemark"))
                            .setInfoRemark(plate.getString("InfoRemark"))
                            .setRemarkJsonDei(plate.getString("RemarkJson"));
                    plateInfo.setRemark(plateDetail.get(plate.getInteger("BlockNo")).getRemark() != null ?
                            plateDetail.get(plate.getInteger("BlockNo")).getRemark().toString() : "");
                }
                if (plateMap.get(plate.getInteger("BlockNo")) != null) {
                    JSONObject jsonObject = plateMap.get(plate.getInteger("BlockNo"));
                    plateInfo.setHeight(BigDecimal.valueOf(jsonObject.getDouble("Height")))
                            .setWidth(BigDecimal.valueOf(jsonObject.getDouble("Width")))
                            .setThickness(BigDecimal.valueOf(jsonObject.getDouble("Thickness")))
                            .setArea(BigDecimal.valueOf(jsonObject.getDouble("Area")));
                    plateDetail.get(plate.getInteger("BlockNo"))
                            .setRemarkJson(jsonObject.getString("RemarkJson"))
                            .setSpecialRemark(jsonObject.getString("SpecialRemark"));
                }
                platesInfos.put(plate.getInteger("ItemID"), plateInfo);
                platesItem.put(plate.getInteger("ItemID"), itemPlate);

            }
        }

        List<OrderItemDO> platesList = platesItem.values().stream().collect(Collectors.toList());
        Map<Long, List<OrderItemDO>> platesDetail = platesList.stream()
                .collect(Collectors.groupingBy(OrderItemDO::getBodyId));
        // 遍历platesDetail

        platesDetail.forEach((k, v) -> {
            Integer specialShapedNum = 0;
            v.forEach(item -> {
                num++;
            });
            bodyInfos.forEach((n, m) -> {
                if (k == m.getId()) {
                    m.setPlateNum(num);
                }
            });
            num = 0;
        });
//        System.err.println(bodyInfos);
        map.put("platesInfos", platesInfos);
        map.put("platesItems", platesItem);
        map.put("plateDetail", plateDetail);
        map.put("bodyInfos", bodyInfos);
        return map;
    }

    /**
     * 板材数据转换成 Map<String, Object>
     */
    public Map<Integer, JSONObject> getBlocksData(JSONObject dataBlocks) {
        Map<Integer, JSONObject> map = new HashMap<>();
        JSONArray ordersArray = dataBlocks.getJSONArray("List");
        if (ordersArray != null && !ordersArray.isEmpty()) {
            for (int i = 0; i < ordersArray.size(); i++) {
                JSONObject block = ordersArray.getJSONObject(i);
                map.put(block.getInteger("BlockNo"), block);
            }
        }
        return map;
    }

    /**
     * 板材设计数据转换成PlateDetail Integer指BlockID板id
     */
    public Map<Integer, PlateDetail> platesDetailChange(JSONObject dataPlates) {
        Map<Integer, PlateDetail> plateDetails = new HashMap<>();
        // 获取 Orders 字段对应的数组
        JSONArray ordersArray = dataPlates.getJSONArray("Orders");
//        System.err.println(dataPlates);
        if (ordersArray != null && !ordersArray.isEmpty()) {
            for (int i = 0; i < ordersArray.size(); i++) {
                JSONObject order = ordersArray.getJSONObject(i);
                // 获取材料信息
                if (order.getJSONArray("Materials") != null && !order.getJSONArray("Materials").isEmpty()) {
                    for (int j = 0; j < order.getJSONArray("Materials").size(); j++) {
                        JSONObject material = order.getJSONArray("Materials").getJSONObject(j);
//                        goodsMap.put()
                        // 板件信息
                        if (material.getJSONArray("Blocks") != null && !material.getJSONArray("Blocks").isEmpty()) {
                            for (int k = 0; k < material.getJSONArray("Blocks").size(); k++) {
                                JSONObject block = material.getJSONArray("Blocks").getJSONObject(k);// 每块板

                                PlateDetail plateDetail = PlateDetail.builder()
                                        .bodyNo(block.getString("BoxNo"))
                                        .plateNo(block.getString("BlockNo"))
                                        .name(block.getString("BlockName"))
                                        .customPlateNo(block.getString("CustomNo"))
                                        .roomsName(block.getString("RoomName"))
                                        .bodyName(block.getString("BoxName"))
                                        .group(block.getString("ProcessGroupName"))
                                        .multiNum(1)
                                        .plateWidth(block.getBigDecimal("Width"))
                                        .plateLength(block.getBigDecimal("Length"))
                                        .acreage(block.getBigDecimal("Size"))
                                        .splitWidth(block.getBigDecimal("CuttingWidth"))
                                        .splitLength(block.getBigDecimal("CuttingLength"))
                                        .sealAcreage(block.getBigDecimal("CuttingSize"))
                                        .isUnRegular(block.getBoolean("IsUnRegular"))
                                        .sealLeft(block.getBigDecimal("BorderLeft"))
                                        .sealRight(block.getBigDecimal("BorderRight"))
                                        .sealUp(block.getBigDecimal("BorderUpper"))
                                        .sealDown(block.getBigDecimal("BorderUnder"))
                                        .texture(block.getInteger("Wave"))
                                        .typographicFace(Integer.valueOf(block.getString("PlaceFace")))
                                        .openDoorType(Integer.valueOf(block.getString("OpenDoorType")))
                                        .offsetX(block.getBigDecimal("OffsetX"))
                                        .offsetY(block.getBigDecimal("OffsetY"))
                                        .pointDetail(getPointDetail(block, true))
                                        .rawPointDetail(getPointDetail(block, false))
                                        .holeDetail(getHoleDetail(block, true))
                                        .sideHoleDetail(getHoleDetail(block, false))
                                        .contourDetail(getModelDetail(block))
//                                        排钻类型
                                        .drillsInfos(getDrillsInfo(block))
                                        .build();

                                if (block.getJSONObject("ExtraRemark") != null) {
                                    if (block.getJSONObject("ExtraRemark").getJSONObject("extra") != null)
                                        plateDetail.setBoardType(block.getJSONObject("ExtraRemark").getJSONObject("extra").getString("boardType"))
                                                .setThroughHoleCount(Double.valueOf(block.getJSONObject("ExtraRemark").getJSONObject("extra").getString("throughHoleCount")))
                                                .setThroughModelCount(Double.valueOf(block.getJSONObject("ExtraRemark").getJSONObject("extra").getString("throughModelCount")))
                                                .setHas2DModel(Boolean.valueOf(block.getJSONObject("ExtraRemark").getJSONObject("extra").getString("has2DModel")))
                                                .setHas3DModel(Boolean.valueOf(block.getJSONObject("ExtraRemark").getJSONObject("extra").getString("has3DModel")))
                                                .setRemark(remarkToMap(block))
                                                .setSideRemark(edgeRemarkToMap(block.getJSONObject("ExtraRemark").getJSONObject("extra")));
                                }
                                plateDetails.put(block.getInteger("BlockNo"), plateDetail);
                            }
                        }
                    }

                }
//                System.out.println("板块 " + plateDetails);
            }

        } else {
            System.out.println("JSON 数据中没有订单信息（Orders 数组为空）。");
        }

        return plateDetails;
    }


    //    异形板的开料轮廓 (type 为true，不含封边;其他为,含封边)
    private List<PointDetail> getPointDetail(JSONObject block, Boolean type) {
        List<PointDetail> pointDetailList = new ArrayList<>();

        if (type) { // 不含封边
            if (block.getJSONArray("Points") != null && !block.getJSONArray("Points").isEmpty()) {
                for (int i = 0; i < block.getJSONArray("Points").size(); i++) {
                    JSONObject point = block.getJSONArray("Points").getJSONObject(i);
                    pointDetailList.add(PointDetail.builder()
                            .pointX(Double.valueOf(point.getString("X")))
                            .pointY(Double.valueOf(point.getString("Y")))
                            .curve(Double.valueOf(point.getString("Curve")))
                            .build());
                }
            }
        } else { // 含封边
            if (block.getJSONArray("OrgPoints") != null && !block.getJSONArray("OrgPoints").isEmpty()) {
                for (int i = 0; i < block.getJSONArray("OrgPoints").size(); i++) {
                    JSONObject rawPoint = block.getJSONArray("OrgPoints").getJSONObject(i);
                    pointDetailList.add(PointDetail.builder()
                            .pointX(Double.valueOf(rawPoint.getString("X")))
                            .pointY(Double.valueOf(rawPoint.getString("Y")))
                            .curve(Double.valueOf(rawPoint.getString("Curve")))
                            .sealSize(Double.valueOf(rawPoint.getString("Edge")))
                            .build());

                }
            }
        }
        return pointDetailList;
    }

    //    孔明细板数据解析 (type 为true，正面;false,侧面)
    private List<HoleDetail> getHoleDetail(JSONObject block, Boolean type) {
        List<HoleDetail> holeDetails = new ArrayList<>();
        if (type) { // 1，正面
            if (block.getJSONArray("Holes") != null && !block.getJSONArray("Holes").isEmpty()) {
                for (int i = 0; i < block.getJSONArray("Holes").size(); i++) {
                    JSONObject hole = block.getJSONArray("Holes").getJSONObject(i);
                    holeDetails.add(HoleDetail.builder()
                            .startX(Double.valueOf(hole.getString("X")))
                            .startY(Double.valueOf(hole.getString("Y")))
                            .faceType(hole.getInteger("Face"))
                            .radius(Double.valueOf(hole.getString("Diameter")) / 2)
                            .depth(Double.valueOf(hole.getString("Depth")))
                            .build());
                }
            }
        } else {
            if (block.getJSONArray("SideHoles") != null && !block.getJSONArray("SideHoles").isEmpty()) {
                for (int i = 0; i < block.getJSONArray("SideHoles").size(); i++) {
                    JSONObject hole = block.getJSONArray("SideHoles").getJSONObject(i);
                    String[] startPoints = splitAndTrim(hole.getString("StartPoint"));
                    String[] endPoints = splitAndTrim(hole.getString("EndPoint"));
                    try {
                        holeDetails.add(HoleDetail.builder()
                                .startX(Double.valueOf(startPoints[X]))
                                .startY(Double.valueOf(startPoints[Y]))
                                .startZ(Double.valueOf(startPoints[Z]))
                                .endX(Double.valueOf(endPoints[X]))
                                .endY(Double.valueOf(endPoints[Y]))
                                .endZ(Double.valueOf(endPoints[Z]))
                                .faceType(2)
                                .direction(hole.getInteger("Direction"))
                                .radius(Double.valueOf(hole.getString("Diameter")) / 2)
                                .depth(Double.valueOf(hole.getString("Depth")))
                                .build());
                    } catch (Exception e) {
                        System.out.println("HoleDetail " + hole);
                    }

                }
            }
        }

        return holeDetails;
    }

    //    造型明细板数据解析 (type 为1，正面;3,侧面)
    private List<ModelDetail> getModelDetail(JSONObject block) {
        List<ModelDetail> modelDetails = new ArrayList<>();

        if (block.getJSONArray("Models") != null && !block.getJSONArray("Models").isEmpty()) {
            for (int i = 0; i < block.getJSONArray("Models").size(); i++) {
                JSONObject model = block.getJSONArray("Models").getJSONObject(i);

                List<PointList> pointLists = new ArrayList<>();
                if (model.getJSONArray("Points") != null && !model.getJSONArray("Points").isEmpty()) {
                    for (int j = 0; j < model.getJSONArray("Points").size(); j++) {
                        JSONObject point = model.getJSONArray("Points").getJSONObject(j);
                        String[] points = splitAndTrim(point.getString("Pos"));
                        pointLists.add(PointList.builder()
                                .pointX(Double.valueOf(points[X]))
                                .pointY(Double.valueOf(points[Y]))
                                .pointZ(Double.valueOf(points[Z]))
                                .curve(Double.valueOf(point.getString("Curve")))
                                .build());
                    }
                }

                List<OffSetList> offSetLists = new ArrayList<>();
                if (model.getJSONArray("OffsetList") != null && !model.getJSONArray("OffsetList").isEmpty()) {
                    for (int j = 0; j < model.getJSONArray("OffsetList").size(); j++) {
                        JSONObject offSet = model.getJSONArray("OffsetList").getJSONObject(j);
                        offSetLists.add(OffSetList.builder()
                                .value(Double.valueOf(offSet.getString("Value")))
                                .name(offSet.getString("Name"))
                                .radius(Double.valueOf(offSet.getString("Diameter")) / 2)
                                .angle(Double.valueOf(offSet.getString("Angle")))
                                .depth(Double.valueOf(offSet.getString("Depth")))
                                .build());
                    }
                }
                modelDetails.add(ModelDetail.builder()
                        .depth(Double.valueOf(model.getString("Depth")))
                        .faceType(Integer.valueOf(model.getString("Face")))
                        .knifeName(model.getString("TooINo"))
                        .knifeRadius(Double.valueOf(model.getString("Diameter")) / 2)
                        .pointList(pointLists)
                        .offSetList(offSetLists)
                        .build());
            }
        }

        return modelDetails;
    }

    //    排钻数据
    private List<DrillsInfo> getDrillsInfo(JSONObject block) {
        List<DrillsInfo> drillsInfos = new ArrayList<>();

        if (block.getJSONArray("drills") != null && !block.getJSONArray("drills").isEmpty()) {
            for (int i = 0; i < block.getJSONArray("drills").size(); i++) {
                JSONObject drill = block.getJSONArray("drills").getJSONObject(i);
                drillsInfos.add(DrillsInfo.builder()
                        .name(drill.getString("name"))
                        .type(drill.getString("type"))
                        .face(drill.getString("face"))
                        .count(Double.valueOf(drill.getString("count")))
                        .build());
            }
        }
        return drillsInfos;
    }

    //    String[] 以逗号分割,去空格 得到包含X Y Z三位坐标的数组（顺序包含）
    public String[] splitAndTrim(String str) {
        String[] strs = str.split(",");
        for (int i = 0; i < strs.length; i++) {
            strs[i] = strs[i].trim();
        }
        return strs;
    }


    //  将remark转为map
    public Map<String, String> remarkToMap(JSONObject block) {
        Map<String, String> map = new HashMap<>();
        for (int i = 0; i < 4; i++) {
            if (block.getString("remark" + i) != null && !block.getString("remark" + i).isEmpty()) {
                map.put("remark" + i, block.getString("remark" + i));
            }
        }
        return map;
    }

    //  将remark转为map
    public Map<String, String> edgeRemarkToMap(JSONObject edgeRemark) {
        Map<String, String> map = new HashMap<>();
        if (edgeRemark.getJSONArray("edgeRemarks") != null && !edgeRemark.getJSONArray("edgeRemarks").isEmpty()) {
            for (int i = 0; i < edgeRemark.getJSONArray("edgeRemarks").size(); i++) {
                if (edgeRemark.getJSONArray("edgeRemarks").getString(i) != null && !edgeRemark.getJSONArray("edgeRemarks").getString(i).isEmpty()) {
                    map.put(String.valueOf(i), edgeRemark.getJSONArray("edgeRemarks").getString(i));
                }
            }
        }
        return map;
    }
}