//package com.cf.imes.module.executor.service.order;
//
//import cn.hutool.core.collection.CollUtil;
//import co.elastic.clients.elasticsearch.ElasticsearchClient;
//import co.elastic.clients.elasticsearch._types.ElasticsearchException;
//import co.elastic.clients.elasticsearch._types.FieldValue;
//import co.elastic.clients.elasticsearch.core.*;
//import co.elastic.clients.elasticsearch.core.search.Hit;
//import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
//import com.cf.imes.framework.common.exception.ServiceException;
//import com.cf.imes.framework.es.core.service.ESDocumentService;
//import com.cf.imes.module.executor.controller.admin.orderParts.vo.OrderPartsRemark;
//import com.cf.imes.module.executor.dal.dataobject.goods.GoodsDO;
//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.orderParts.PartsDO;
//import com.cf.imes.module.executor.dal.dataobject.ordermodel.OrderModelDO;
//import com.cf.imes.module.executor.dal.dataobject.plate.PlateDO;
//import com.cf.imes.module.executor.dal.dataobject.plate.PlateGoodDO;
//import com.cf.imes.module.executor.dal.dataobject.rawgoods.RawGoodsDO;
//import com.cf.imes.module.executor.dal.mysql.goods.GoodsMapper;
//import com.cf.imes.module.executor.dal.mysql.order.OrderMapper;
//import com.cf.imes.module.executor.dal.mysql.orderBody.OrderBodyMapper;
//import com.cf.imes.module.executor.dal.mysql.orderGroup.OrderGroupMapper;
//import com.cf.imes.module.executor.dal.mysql.orderItem.OrderItemMapper;
//import com.cf.imes.module.executor.dal.mysql.orderParts.OrderPartsMapper;
//import com.cf.imes.module.executor.dal.mysql.orderParts.PartsMapper;
//import com.cf.imes.module.executor.dal.mysql.plate.PlateGoodMapper;
//import com.cf.imes.module.executor.dal.mysql.plate.PlateMapper;
//import com.cf.imes.module.executor.dal.mysql.rawgoods.RawGoodsMapper;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//import org.springframework.transaction.annotation.Transactional;
//
//import jakarta.annotation.Resource;
//import java.io.IOException;
//import java.util.ArrayList;
//import java.util.Collection;
//import java.util.List;
//import java.util.function.BiConsumer;
//import java.util.stream.Collectors;
//
//import static com.cf.imes.framework.common.exception.enums.GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR;
//import static com.cf.imes.module.executor.enums.EsIndexEnum.*;
//
///**
// * @author Beal
// * 订单入库处理器
// */
//@Slf4j
////@Component
//public class OrderInputProcessor {
//
//    @Resource
//    private IdentifierGenerator identifierGenerator;
//    /*private IdentifierGenerator identifierGenerator = new SnowFlakeGenerator(0, 0);*/
//
//    @Resource
//    private OrderMapper orderMapper;
//
//    @Resource
//    private RawGoodsMapper rawGoodsMapper;
//
//    @Resource
//    private OrderBodyMapper orderBodyMapper;
//
//    @Resource
//    private OrderGroupMapper orderGroupMapper;
//
//    @Resource
//    private OrderPartsMapper orderPartsMapper;
//
//    @Resource
//    private PlateMapper plateMapper;
//
//    @Resource
//    private OrderItemMapper orderItemMapper;
//
//    @Resource
//    private GoodsMapper goodsMapper;
//
//    @Resource
//    private PlateGoodMapper plateGoodMapper;
//
//    @Resource
//    private ESDocumentService esDocumentService;
//
//    @Resource
//    private PartsMapper partsMapper;
//
//    @Resource
//    private ElasticsearchClient elasticsearchClient;
//
//    private static final String FIELD_ORDER_ID = "orderId";
//
//
//    /**
//     * 批量保存订单小板五金数据
//     *
//     * @param rawGoodsDOS
//     * @param orderBodyDOS
//     * @param orderGroupDOS
//     * @param orderPartsDOS
//     * @param plateDOS
//     * @param itemDOS
//     */
//    @Transactional(rollbackFor = Exception.class)
//    public void batchInsert(Collection<RawGoodsDO> rawGoodsDOS,
//                            Collection<OrderBodyDO> orderBodyDOS,
//                            Collection<OrderGroupDO> orderGroupDOS,
//                            Collection<OrderPartsDO> orderPartsDOS,
//                            Collection<PlateDO> plateDOS,
//                            Collection<OrderItemDO> itemDOS,
//                            Collection<GoodsDO> goodsDOS,
//                            Collection<PlateGoodDO> plateGoodDOS,
//                            Collection<PartsDO> partsDOS) {
//
//
////        if (rawGoodsDOS != null)
////            for (int i = 0; i < rawGoodsDOS.size(); i += 1000) {
////                rawGoodsMapper.insertBatch(rawGoodsDOS.stream().skip(i).limit(1000).collect(Collectors.toList()));
////            }
////        if (orderBodyDOS != null)
////            for (int i = 0; i < orderBodyDOS.size(); i += 1000) {
////                orderBodyMapper.insertBatch(orderBodyDOS.stream().skip(i).limit(1000).collect(Collectors.toList()));
////            }
////        if (orderGroupDOS != null)
////            for (int i = 0; i < orderGroupDOS.size(); i += 1000) {
////                orderGroupMapper.insertBatch(orderGroupDOS.stream().skip(i).limit(1000).collect(Collectors.toList()));
////            }
////        if (orderPartsDOS != null)
////            for (int i = 0; i < orderPartsDOS.size(); i += 1000) {
////                orderPartsMapper.insertBatch(orderPartsDOS.stream().skip(i).limit(1000).collect(Collectors.toList()));
////            }
////        if (plateDOS != null)
////            for (int i = 0; i < plateDOS.size(); i += 1000) {
////                plateMapper.insertBatch(plateDOS.stream().skip(i).limit(1000).collect(Collectors.toList()));
////            }
////        if (itemDOS != null) {
////            for (int i = 0; i < itemDOS.size(); i += 1000) {
////                orderItemMapper.insertBatch(itemDOS.stream().skip(i).limit(1000).collect(Collectors.toList()));
////            }
////        }
////        if (goodsDOS != null) {
////            for (int i = 0; i < itemDOS.size(); i += 1000) {
////                goodsMapper.insertBatch(goodsDOS.stream().skip(i).limit(1000).collect(Collectors.toList()));
////            }
////        }
////        if (plateGoodDOS != null) {
////            for (int i = 0; i < itemDOS.size(); i += 1000) {
////                plateGoodMapper.insertBatch(plateGoodDOS.stream().skip(i).limit(1000).collect(Collectors.toList()));
////            }
////        }
//
//        insertInBatches(rawGoodsDOS, 1000, (batch, index) -> rawGoodsMapper.insertBatch((Collection<RawGoodsDO>) batch));
//        insertInBatches(orderBodyDOS, 1000, (batch, index) -> orderBodyMapper.insertBatch((Collection<OrderBodyDO>) batch));
//        insertInBatches(orderGroupDOS, 1000, (batch, index) -> orderGroupMapper.insertBatch((Collection<OrderGroupDO>) batch));
//        insertInBatches(orderPartsDOS, 1000, (batch, index) -> orderPartsMapper.insertBatch((Collection<OrderPartsDO>) batch));
//        insertInBatches(plateDOS, 1000, (batch, index) -> plateMapper.insertBatch((Collection<PlateDO>) batch));
//        insertInBatches(itemDOS, 1000, (batch, index) -> orderItemMapper.insertBatch((Collection<OrderItemDO>) batch));
//        insertInBatches(goodsDOS, 1000, (batch, index) -> goodsMapper.insertBatch((Collection<GoodsDO>) batch));
////        insertInBatches(plateGoodDOS, 1000, (batch, index) -> plateGoodMapper.insertBatch((Collection<PlateGoodDO>) batch));
//        insertInBatches(partsDOS, 1000, (batch, index) -> partsMapper.insertBatch((Collection<PartsDO>) batch));
//    }
//
//    private void insertInBatches(Collection<?> entities, int batchSize, BiConsumer<Collection<?>, Integer> insertFunction) {
//        if (entities != null) {
//            int total = entities.size();
//            for (int i = 0; i < total; i += batchSize) {
//                Collection<?> batch = entities.stream()
//                        .skip(i)
//                        .limit(batchSize)
//                        .collect(Collectors.toList());
//                insertFunction.accept(batch, i);
//            }
//        }
//    }
//
//    /**
//     * 保存订单造型数据
//     *
//     * @param orderModelDOs
//     */
//    public void batchSaveModel(List<OrderModelDO> orderModelDOs) {
//        try {
//            BulkResponse bulkResponse = esDocumentService.bulkCreate(ORDER_PLATE_MODEL.getIndex(), orderModelDOs);
//            boolean errors = bulkResponse.errors();
//            if (errors) {
//                log.error(bulkResponse.items().toString());
//                throw new ServiceException(500, "未知异常");
//            }
//        } catch (IOException | ElasticsearchException e) {
//            log.error(e.getMessage(), e);
//            throw new RuntimeException(e);
//        }
//
//    }
//
//
//
//
//
//    /**
//     * 保存订单配件备注数据
//     *
//     * @param orderPartsRemarks
//     */
//    public void batchSaveOrderPartsModel(List<OrderPartsRemark> orderPartsRemarks) {
//        try {
//            BulkResponse bulkResponse = esDocumentService.bulkCreate(ORDER_PARTS_REMARK_MODEL.getIndex(), orderPartsRemarks);
//            boolean errors = bulkResponse.errors();
//            if (errors) {
//                log.error(bulkResponse.items().toString());
//                throw new ServiceException(500, "未知异常");
//            }
//        } catch (IOException | ElasticsearchException e) {
//            log.error(e.getMessage(), e);
//            throw new RuntimeException(e);
//        }
//
//    }
//
//    /**
//     * 订单Id删除
//     */
//    public void deleteByOrderId(Long orderId, String index) {
//        try {
//            // 查文档_id
//            SearchResponse<Void> search = elasticsearchClient.search(s -> s
//                            .index(index)
//                            .size(1) // 只取一条
//                            .query(q -> q.term(t -> t.field("orderId").value(orderId)))
//                            .source(src -> src.fetch(false)), // 不拉取 _source
//                    Void.class
//            );
//            List<Hit<Void>> hits = search.hits().hits();
//            if (hits.isEmpty()) {
//                log.warn("No document found for orderId: {}", orderId);
//                return;
//            }
//
//            String docId = hits.get(0).id();
//
//            // 按 _id 删除
//            elasticsearchClient.delete(d -> d.index(index).id(docId));
//            log.info("Successfully deleted document with orderId={} (docId={})", orderId, docId);
//        } catch (IOException | ElasticsearchException e) {
//            log.error("Error deleting documents with orderId {}: {}", orderId, e);
//            throw new ServiceException(INTERNAL_SERVER_ERROR);
//        }
//    }
//
//    /**
//     * 批量删除
//     */
//    public void deleteByOrderId(List<Long> orderIds, String index) {
//        List<FieldValue> fieldValues = orderIds.stream().map(FieldValue::of).toList();
//
//        DeleteByQueryRequest.Builder builder = new DeleteByQueryRequest.Builder();
//        builder.index(index);
//
//        builder.query(q -> q.terms(b -> b.field(FIELD_ORDER_ID).terms(e -> e.value(fieldValues))));
//
//        try {
//            DeleteByQueryResponse response = elasticsearchClient.deleteByQuery(builder.build());
//            log.info("Deleted {} documents with planId {}", response.deleted(), orderIds);
//        } catch (IOException | ElasticsearchException e) {
//            log.error("Error deleting documents with planId {}: {}", orderIds, e);
//            throw new ServiceException(INTERNAL_SERVER_ERROR);
//        }
//    }
//}
