package com.zt.plat.module.contractorder.service.entrustorder;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.module.base.api.materialinfomation.MaterialInfomationApi;
import com.zt.plat.module.base.api.materialinfomation.dto.MaterialInfomationPageReqDTO;
import com.zt.plat.module.base.api.materialinfomation.dto.MaterialInfomationRespDTO;
import com.zt.plat.module.contractorder.api.vo.contract.ContractRespVO;
import com.zt.plat.module.contractorder.controller.admin.entrustorder.vo.EntrustOrderDetailRespVO;
import com.zt.plat.module.contractorder.controller.admin.entrustorder.vo.EntrustOrderOrderPageReqVO;
import com.zt.plat.module.contractorder.controller.admin.entrustorder.vo.EntrustOrderOrderRespVO;
import com.zt.plat.module.contractorder.controller.admin.entrustorder.vo.EntrustOrderOrderSaveReqVO;
import com.zt.plat.module.contractorder.controller.admin.purchaseorder.vo.DownOrUpOrderReqVO;
import com.zt.plat.module.contractorder.controller.admin.purchaseorder.vo.DownOrUpOrderRespVO;
import com.zt.plat.module.contractorder.controller.admin.purchaseorder.vo.LinkOrderReqVO;
import com.zt.plat.module.contractorder.controller.admin.purchaseorder.vo.PurchaseOrderRespVO;
import com.zt.plat.module.contractorder.dal.dataobject.contract.SystemRelativityDO;
import com.zt.plat.module.contractorder.dal.dataobject.entrustorder.EntrustOrderOrderDO;
import com.zt.plat.module.contractorder.dal.mysql.contract.SystemRelativityMapper;
import com.zt.plat.module.contractorder.dal.mysql.entrustorder.EntrustOrderOrderMapper;
import com.zt.plat.module.contractorder.enums.contract.DictEnum;
import com.zt.plat.module.contractorder.enums.purchaseorder.OrderStatusEnum;
import com.zt.plat.module.contractorder.service.contract.ContractService;
import com.zt.plat.module.erp.controller.admin.erp.vo.ErpOrderSaveReqVO;
import com.zt.plat.module.erp.controller.admin.erp.vo.ErpOrderUpdateReqVO;
import com.zt.plat.module.erp.service.erp.ErpOrderService;
import com.zt.plat.module.system.api.sequence.SequenceApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;

import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;

import static com.zt.plat.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.zt.plat.module.contractorder.enums.ErpConstants.CONSTANTS_L;
import static com.zt.plat.module.contractorder.enums.ErrorCodeConstants.CONTRACT_ORDER_EXISTS;
import static com.zt.plat.module.contractorder.enums.entrustorder.ErrorCodeConstants.ENTRUST_ORDER_DETAIL_NOT_EXISTS;
import static com.zt.plat.module.contractorder.enums.entrustorder.ErrorCodeConstants.ENTRUST_ORDER_NOT_EXISTS;
import static com.zt.plat.module.contractorder.enums.purchaseorder.ErrorCodeConstants.MTRL_CODE_NOT_EXISTS;
import static com.zt.plat.module.contractorder.enums.purchaseorder.ErrorCodeConstants.PURCHASE_ORDER_NOT_EXISTS;


/**
 * 采购订单 Service 实现类
 *
 * @author 后台管理-1
 */
@Service
@Validated
@Slf4j
public class EntrustOrderOrderServiceImplImpl implements EntrustOrderOrderService {

    @Resource
    private EntrustOrderOrderMapper entrustOrderOrderMapper;

    @Resource
    private EntrustOrderDetailService entrustOrderDetailService;
    @Resource
    private SystemRelativityMapper systemRelativityMapper;

    @Resource
    private SequenceApi sequenceApi;

    @Resource
    private ContractService contractService;
    @Resource
    private MaterialInfomationApi materialInfomationApi;

    @Resource
    private ErpOrderService erpOrderService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EntrustOrderOrderRespVO createEntrustOrderOrder(EntrustOrderOrderSaveReqVO createReqVO) {
        // 插入
        EntrustOrderOrderDO entrustOrderOrder = BeanUtils.toBean(createReqVO, EntrustOrderOrderDO.class);
        entrustOrderOrder.setIsPush(0);
        entrustOrderOrder.setStatus(OrderStatusEnum.IN_PROGRESS.getCode());
        entrustOrderOrder.setSystemOrderNumber(this.generateOrderNumber(""));
        entrustOrderOrderMapper.insert(entrustOrderOrder);
        EntrustOrderOrderRespVO bean = BeanUtils.toBean(entrustOrderOrder, EntrustOrderOrderRespVO.class);
        //批量插入委托加工订单明细
        if (createReqVO.getDetails() != null && !createReqVO.getDetails().isEmpty()) {
            createReqVO.getDetails().forEach(entrustOrderDetail -> entrustOrderDetail.setOrderId(entrustOrderOrder.getId()));
            List<EntrustOrderDetailRespVO> entrustOrderDetailRespVOS = entrustOrderDetailService.insertBatchSomeColumn(createReqVO.getDetails());
            bean.setDetails(entrustOrderDetailRespVOS);
        }
        // 返回
        return bean;
    }

    private String generateOrderNumber(String materialType) {
        return sequenceApi.getNextSequence("ENTRUST_ORDER_NUMBER", null, null).getData();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEntrustOrderOrder(EntrustOrderOrderSaveReqVO updateReqVO) {
        // 校验存在
        validateEntrustOrderOrderExists(updateReqVO.getId());
        // 更新
        EntrustOrderOrderDO updateObj = BeanUtils.toBean(updateReqVO, EntrustOrderOrderDO.class);
        if (updateReqVO.getDetails() != null && !updateReqVO.getDetails().isEmpty()) {
            //如果明细ID为空(表示新增)，则设置订单ID
            updateReqVO.getDetails().forEach(item -> {
                if (item.getId() == null) {
                    item.setOrderId(updateReqVO.getId());
                }
            });
            submitErpUpdate062(updateReqVO);
        }
        entrustOrderOrderMapper.updateById(updateObj);
        if (updateReqVO.getDetails() != null && !updateReqVO.getDetails().isEmpty()) {
            entrustOrderDetailService.updateBatchSomeColumn(updateReqVO.getDetails());
        }

    }

    @Override
    public void deleteEntrustOrderOrder(Long id) {
        // 校验存在
        validateEntrustOrderOrderExists(id);
        // 删除
        entrustOrderOrderMapper.deleteById(id);
    }

    @Override
    public void deleteEntrustOrderOrderListByIds(List<Long> ids) {
        // 校验存在
        validateEntrustOrderOrderExists(ids);
        // 删除
        entrustOrderOrderMapper.deleteByIds(ids);
        // 删除委托加工订单明细
        entrustOrderDetailService.deleteEntrustOrderDetailByOrderId(ids);
    }

    private void validateEntrustOrderOrderExists(List<Long> ids) {
        List<EntrustOrderOrderDO> list = entrustOrderOrderMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(ENTRUST_ORDER_NOT_EXISTS);
        }
    }

    private void validateEntrustOrderOrderExists(Long id) {
        if (entrustOrderOrderMapper.selectById(id) == null) {
            throw exception(ENTRUST_ORDER_NOT_EXISTS);
        }
    }

    @Override
    public EntrustOrderOrderDO getEntrustOrderOrder(Long id) {
        return entrustOrderOrderMapper.selectById(id);
    }

    @Override
    public PageResult<EntrustOrderOrderDO> getEntrustOrderOrderPage(EntrustOrderOrderPageReqVO pageReqVO) {
        return entrustOrderOrderMapper.selectPage(pageReqVO);
    }

    @Override
    public boolean linkOrder(LinkOrderReqVO req) {
        SystemRelativityDO saveDO = new SystemRelativityDO();
        saveDO.setStatus(DictEnum.BSE_SYS_REL_TP_ORDER.getCode());
        saveDO.setUpId(req.getUpOrderId());
        saveDO.setDownId(req.getDownOrderId());
        //判断订单有没有关联过
        if (systemRelativityMapper.selectCount(new LambdaQueryWrapper<SystemRelativityDO>().eq(SystemRelativityDO::getUpId, saveDO.getUpId()).eq(SystemRelativityDO::getDownId, saveDO.getDownId())) > 0) {
            throw exception(CONTRACT_ORDER_EXISTS);
        }
        return systemRelativityMapper.insert(saveDO) > 0;
    }

    @Override
    public List<DownOrUpOrderRespVO> getOrderByOrderIdAndType(DownOrUpOrderReqVO reqVO) {
        EntrustOrderOrderDO entrustOrderOrderDO = entrustOrderOrderMapper.selectById(reqVO.getOrderId());
        if (entrustOrderOrderDO == null) {
            throw exception(PURCHASE_ORDER_NOT_EXISTS);
        }
        String contractNumber = entrustOrderOrderDO.getContractNumber();// 合同号
        ContractRespVO contractRespVO = contractService.getBySystemContractNumber(contractNumber);

        ContractRespVO upRelation = null;
        if ("up".equals(reqVO.getOrderType())) {
            log.info("获取上游订单");
            //上游
            upRelation = contractService.getUpRelation(contractRespVO.getId());
        } else {
            //下游
            log.info("获取下游订单");
            upRelation = contractService.getDownRelation(contractRespVO.getId());
        }
        List<DownOrUpOrderRespVO> orderList = new ArrayList<>();
        if (upRelation != null) {
            String systemContractNumber = upRelation.getSystemContractNumber();

            List<EntrustOrderOrderDO> entrustOrderOrderDOS = entrustOrderOrderMapper.selectList(new LambdaQueryWrapper<EntrustOrderOrderDO>().eq(EntrustOrderOrderDO::getContractNumber, systemContractNumber));
            entrustOrderOrderDOS.forEach(p -> {
                        DownOrUpOrderRespVO downOrUpOrderRespVO = new DownOrUpOrderRespVO();
                        downOrUpOrderRespVO.setOrderId(String.valueOf(p.getId()));
                        downOrUpOrderRespVO.setOrderNo(p.getSystemOrderNumber());
                        downOrUpOrderRespVO.setOrderType(reqVO.getOrderType());
                        downOrUpOrderRespVO.setContractId(String.valueOf(p.getId()));
                        downOrUpOrderRespVO.setContractName(p.getContractName());
                        downOrUpOrderRespVO.setContractNumber(p.getContractNumber());
                        downOrUpOrderRespVO.setOrder(BeanUtils.toBean(p, PurchaseOrderRespVO.class));
                        orderList.add(downOrUpOrderRespVO);
                    }
            );

        }
        return orderList;
    }

    @Override
    public List<EntrustOrderOrderRespVO> getBindOrderByOrder(DownOrUpOrderReqVO reqVO) {
        List<EntrustOrderOrderRespVO> orderList = new ArrayList<>();
        if ("up".equals(reqVO.getOrderType())) {
            log.info("获取上游订单");
            //上游
            List<SystemRelativityDO> systemRelativityDOS = systemRelativityMapper.selectList(new LambdaQueryWrapper<SystemRelativityDO>().eq(SystemRelativityDO::getDownId, reqVO.getOrderId()));
            if (!systemRelativityDOS.isEmpty()) {
                List<EntrustOrderOrderDO> entrustOrderOrderDOS = entrustOrderOrderMapper.selectByIds(systemRelativityDOS.stream().map(SystemRelativityDO::getUpId).toList());
                orderList = BeanUtils.toBean(entrustOrderOrderDOS, EntrustOrderOrderRespVO.class);
            }
        } else {
            //下游
            log.info("获取下游订单");
            List<SystemRelativityDO> systemRelativityDOS = systemRelativityMapper.selectList(new LambdaQueryWrapper<SystemRelativityDO>().eq(SystemRelativityDO::getUpId, reqVO.getOrderId()));
            if (!systemRelativityDOS.isEmpty()) {
                List<EntrustOrderOrderDO> purchaseOrderDOS = entrustOrderOrderMapper.selectByIds(systemRelativityDOS.stream().map(SystemRelativityDO::getDownId).toList());
                orderList = BeanUtils.toBean(purchaseOrderDOS, EntrustOrderOrderRespVO.class);
            }
        }
        return orderList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void closeOrder(List<Long> ids) {
        EntrustOrderOrderDO updateObj = new EntrustOrderOrderDO();
        updateObj.setStatus(OrderStatusEnum.CLOSED.getCode());
        entrustOrderOrderMapper.update(new LambdaUpdateWrapper<EntrustOrderOrderDO>()
                .set(EntrustOrderOrderDO::getStatus, OrderStatusEnum.CLOSED.getCode())
                .in(EntrustOrderOrderDO::getId, ids));
    }

    @Override
    public List<EntrustOrderDetailRespVO> getEntrustOrderDetailListByOrderId(Long id) {
        return entrustOrderDetailService.getEntrustOrderDetailListByOrderId(id);
    }

    @Override
    public void submitErp061(Long id) {
        //查询订单
        EntrustOrderOrderDO entrustOrderOrderDO = entrustOrderOrderMapper.selectById(id);
        if (entrustOrderOrderDO == null) {
            throw exception(ENTRUST_ORDER_NOT_EXISTS);
        }
        log.info("提交订单到ERP：【{}】，订单信息：【{}】", id, entrustOrderOrderDO);
        List<EntrustOrderDetailRespVO> entrustOrderDetailListByOrderId = entrustOrderDetailService.getEntrustOrderDetailListByOrderId(id);
        if (entrustOrderDetailListByOrderId == null || entrustOrderDetailListByOrderId.isEmpty()) {
            throw exception(ENTRUST_ORDER_DETAIL_NOT_EXISTS);
        }
        log.info("提交订单到ERP：【{}】，订单明细信息：【{}】", id, entrustOrderDetailListByOrderId);
        ErpOrderSaveReqVO erpOrderSaveReqVO = new ErpOrderSaveReqVO();

        //构建请求数据
        buildErp061Data(erpOrderSaveReqVO, entrustOrderOrderDO, entrustOrderDetailListByOrderId);


        Long localOrderId = entrustOrderOrderDO.getId();
        String result = erpOrderService.submitOrderToErp061(erpOrderSaveReqVO);
        log.info("提交订单到ERP：【{}】，结果：【{}】", id, result);
        EntrustOrderOrderDO upVo = new EntrustOrderOrderDO();
        upVo.setId(localOrderId);
        String erpId = null; // ERP订单号(PO_NUMBER)
        try {
            if (StringUtils.isNotBlank(result)) {
                // 解析顶层JSON对象
                JSONObject rootJson = JSONObject.parseObject(result);
                String eResp = rootJson.getString("E_RESP");
                if (StringUtils.isNotBlank(eResp)) {
                    // 解析E_RESP为JSON对象，获取PO_NUMBER
                    JSONObject eRespJson = JSONObject.parseObject(eResp);
                    erpId = eRespJson.getString("PO_NUMBER");
                }
            }

            // 3. 根据ERP订单号是否有效，设置本地订单更新属性
            if (StringUtils.isNotBlank(erpId)) {
                // ERP返回有效订单号，更新为成功状态
                upVo.setOrderSAPNumber(erpId);
                upVo.setCause("ERP提交成功，erpID为：" + erpId);
                upVo.setErpStatus(OrderStatusEnum.FIND.getCode()); // 推送成功状态
                log.info("订单推送ERP成功，本地订单ID【{}】，ERP订单号【{}】，已更新本地状态", localOrderId, erpId);
            } else {
                upVo.setOrderSAPNumber(null);
                upVo.setErpStatus(OrderStatusEnum.RLBK.getCode());
                upVo.setCause(result);
                log.warn("订单推送ERP失败，本地订单ID【{}】，失败原因【{}】", localOrderId, result);
            }
            entrustOrderOrderMapper.updateById(upVo);
        } catch (Exception e) {
            upVo.setOrderSAPNumber(null);
            upVo.setErpStatus(OrderStatusEnum.RLBK.getCode()); // 异常时强制置为失败状态
            upVo.setCause("ERP返回结果解析/处理异常：" + e.getMessage());
            // 异常时仍需更新数据库，保证订单状态一致性
            entrustOrderOrderMapper.updateById(upVo);
            log.error("订单推送ERP发生异常，本地订单ID【{}】，异常信息如下", localOrderId, e);
        }
    }

    @Override
    public void submitErpUpdate062(EntrustOrderOrderSaveReqVO updateReqVO) {
        EntrustOrderOrderDO entrustOrderOrderDO = BeanUtils.toBean(updateReqVO, EntrustOrderOrderDO.class);
        if (entrustOrderOrderDO == null) {
            throw exception(ENTRUST_ORDER_NOT_EXISTS);
        }
        //获取订单明细
        List<EntrustOrderDetailRespVO> entrustOrderDetailList = BeanUtils.toBean(updateReqVO.getDetails(), EntrustOrderDetailRespVO.class);
        if (entrustOrderDetailList == null || entrustOrderDetailList.isEmpty()) {
            throw exception(ENTRUST_ORDER_DETAIL_NOT_EXISTS);
        }
        log.info("提交订单到ERP：【{}】，订单信息：【{}】", updateReqVO.getId(), entrustOrderOrderDO);
        log.info("提交订单到ERP：【{}】，订单明细信息：【{}】", updateReqVO.getId(), entrustOrderDetailList);
        ErpOrderUpdateReqVO erpOrderUpdateReqVO = new ErpOrderUpdateReqVO();
        buildErp062Data(erpOrderUpdateReqVO, entrustOrderOrderDO, entrustOrderDetailList);
        String result = erpOrderService.submitOrderToErp062(erpOrderUpdateReqVO);
        log.info("提交订单到ERP：【{}】，结果：【{}】", updateReqVO.getId(), result);
    }

    private void buildErp062Data(ErpOrderUpdateReqVO erpOrderUpdateReqVO, EntrustOrderOrderDO order, List<EntrustOrderDetailRespVO> entrustOrderDetailList) {
        erpOrderUpdateReqVO
                .setPoNumber(order.getOrderSAPNumber())
              //  .setDeleteInd(order.getDeleted() ? "1" : null)
                .setCurrency(order.getCurrencyNumber())
                .setExchRate(order.getExchangeRate());
        //exte
        erpOrderUpdateReqVO
                .setZzhth(order.getPaperContractNumber())
                .setZxxyh(order.getAgreementNumber())
                .setZnote(order.getRemark())
                .setZlifnr(order.getAgreementNumber());
        //item
        List<ErpOrderUpdateReqVO.item> items = new ArrayList<>();
        List<ErpOrderUpdateReqVO.comp> comps = new ArrayList<>();
        AtomicReference<Integer> index = new AtomicReference<>(0);
        entrustOrderDetailList.forEach(detail -> {
            index.getAndSet(index.get() + 1);
            ErpOrderUpdateReqVO.item item = new ErpOrderUpdateReqVO.item(); // item
            item.setPo_item(Long.valueOf(detail.getLineNumber()));//行号
            item.setMaterial(completePrefix(getMtrlZhongtongCode(detail.getSendMaterialNumber())));//物料号
            item.setPlant(detail.getReceiveFactoryNumber());//工厂
            item.setStge_loc(detail.getReceiveWarehouseNumber());//库位
            item.setQuantity(String.valueOf(detail.getForecastQuantity()));// 数量
            item.setPo_unit(detail.getSendUnit());// 计量单位
            item.setNet_price(detail.getInTaxUnitPrice());// 含税单价
            item.setTax_code(detail.getTaxNumber());//税码
            item.setItem_cat(CONSTANTS_L);//科目分配类别
            item.setMatl_group(detail.getMaterialGroup());//物料组
            item.setShort_text(detail.getShortText());//短文本
            item.setDelete_ind(null);//行项目删除标识
            items.add(item);

            ErpOrderUpdateReqVO.comp comp = new ErpOrderUpdateReqVO.comp();
            comp.setPo_item(Long.valueOf(detail.getLineNumber()));
            comp.setSched_line(index.get()); // 计划行号 -> 计划行号（保持一致）
            comp.setItem_no(index.get()); // 项目编号 -> 项目编号
            comp.setMaterial(completePrefix(getMtrlZhongtongCode(detail.getSendMaterialNumber()))); // 物料号 -> 物料号
            comp.setPlant(detail.getReceiveFactoryNumber()); // 收货工厂 -> 收货工厂
            comp.setEntry_quantity(detail.getForecastQuantity()); // 委托加工需求数量 -> 委托加工需求数量
            comp.setEntry_uom(detail.getSendUnit()); // 组件计量单位 -> 组件计量单位
            comps.add(comp);
        });
        erpOrderUpdateReqVO.setItems(items);
        //comp
        erpOrderUpdateReqVO.setComps(comps);

    }

    private void buildErp061Data(ErpOrderSaveReqVO erpOrderSaveReqVO, EntrustOrderOrderDO order, List<EntrustOrderDetailRespVO> entrustOrderDetailList) {
        //订单号
        erpOrderSaveReqVO.setOrderNo(order.getSystemOrderNumber());

        // 1. 处理抬头信息(Head)
        ErpOrderSaveReqVO.Head head = new ErpOrderSaveReqVO.Head();
        head.setComp_code(order.getCpNum()); // 公司编码 -> 公司代码
        head.setVendor(order.getSupplierNumber()); // 客商编码 -> 供应商帐号
        head.setDoc_type(order.getType()); // 订单类型 -> 采购凭证类型
        head.setDoc_date(order.getVoucherDate() != null ? order.getVoucherDate().format(DateTimeFormatter.ofPattern("yyyyMMdd")) : null); // 凭证日期 -> 采购凭证日期
        head.setPurch_org(order.getPurchaseOrganizationCustomsDeclaration()); // 采购组织编码 -> 采购组织
        head.setPur_group(order.getPurchaseGroup()); // 采购组编码 -> 采购组
        head.setCurrency(order.getCurrencyNumber()); // 货币码 -> 货币码
        head.setExch_rate(order.getExchangeRate()); // 汇率 -> 汇率
        erpOrderSaveReqVO.setHead(head);

        // 2. 处理抬头扩展信息(Exte)
        ErpOrderSaveReqVO.Exte exte = new ErpOrderSaveReqVO.Exte();
        exte.setZzhth(order.getPaperContractNumber()); // 合同纸质合同号 -> 纸质合同号
        exte.setZxxyh(order.getAgreementNumber()); // 小协议号 -> 小协议号
        exte.setZnote(order.getRemark()); // 备注 -> 备注
        exte.setZlifnr(order.getAgentNumber()); // 代理方编码 -> 代理方
        erpOrderSaveReqVO.setExte(exte);
        //item
        List<ErpOrderSaveReqVO.Item> items = new ArrayList<>();
        List<ErpOrderSaveReqVO.Itex> itexes = new ArrayList<>();
        List<ErpOrderSaveReqVO.Comp> comps = new ArrayList<>();
        AtomicInteger index = new AtomicInteger();
        entrustOrderDetailList.forEach(detail -> {
            index.getAndIncrement();
            ErpOrderSaveReqVO.Item item = new ErpOrderSaveReqVO.Item();
            item.setPo_item(detail.getLineNumber() != null ? detail.getLineNumber() : null); // 行项目 -> 行号
            item.setMaterial(completePrefix(getMtrlZhongtongCode(detail.getSendMaterialNumber()))); // 物料编码 -> 物料号
            item.setPlant(detail.getReceiveFactoryNumber()); // 收货工厂编码 -> 工厂
            item.setStge_loc(detail.getReceiveWarehouseNumber()); // 收货库位编码 -> 库存地点
            item.setQuantity(detail.getForecastQuantity()); // 暂估数量 -> 数量
            item.setPo_unit(detail.getSendUnit()); // 计量单位 -> 计量单位
            item.setNet_price(detail.getInTaxUnitPrice()); // 含税单价 -> 含税单价
            item.setPrice_unit(detail.getInTaxUnitPrice() != null ? detail.getInTaxUnitPrice().intValue() : 1); // 价格单位 -> 价格单位
            item.setTax_code(detail.getTaxNumber()); // 税码 -> 税码
            // item.setGr_basediv(); // 是否基于GR的发票校验 -> 基于GR的发票校验
            //item.setUnlimited_dlv(detail.getIsUnlRcv()); // 是否允许无限制收货 -> 允许无限制过量交货
            //item.setBatch(detail.getBat()); // 批次 -> 批次
            item.setItem_cat(CONSTANTS_L);
            item.setAcctasscat(detail.getAccountingItemAllocation()); // 科目分配类别 -> 科目分配类别
            item.setMatl_group(detail.getMaterialGroup()); // 物料组编码 -> 物料组
            item.setShort_text(detail.getShortText()); // 短文本 -> 短文本
            item.setRet_item(detail.getReturnItem()); // 退货标识 -> 退货项目标识
            item.setFree_item(detail.getFreeItem()); // 是否免费收货标识 -> 免费项目标识
            //item.setVendrbatch(String.valueOf(detail.getExternalLineNumber())); // 外部行项目号 -> 外部行项目号
//            item.setNote_xq(detail.getRemark()); // 备注信息-需求单位 -> 备注信息-需求单位
//            item.setNote_wl(detail.getRmkMtrl()); // 备注信息-物料详细 -> 备注信息-物料详细
            // 处理交货起止日期(格式:YYYYMMDD-YYYYMMDD)
            StringBuilder vendMat = new StringBuilder();
            if (detail.getDeliveryCargoBeginDate() != null) {
                vendMat.append(detail.getDeliveryCargoBeginDate().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
            }
            vendMat.append("-");
            if (detail.getDeliveryCargoEndDate() != null) {
                vendMat.append(detail.getDeliveryCargoEndDate().format(DateTimeFormatter.ofPattern("yyyyMMdd")));
            }
            item.setVend_mat(vendMat.toString());
            items.add(item);

            ErpOrderSaveReqVO.Itex itex = new ErpOrderSaveReqVO.Itex();
            itex.setPo_item(detail.getLineNumber() != null ? detail.getLineNumber() : null);
            //itex.setZmatnr(getMtrlZhongtongCode(detail.getSendMaterialNumber())); // 物料号 -> 销售物料号
            //itex.setZaufnr(detail.get()); // 统计型内部订单 -> 统计型内部订单
            //itex.setZpurty(detail.getPrchCtgr()); // 采购类别 -> 采购类别
            //itex.setZmenge(detail.getOrigWet()); // 原料湿重 -> 原料湿重
            itexes.add(itex);

            //  列表-comp

            ErpOrderSaveReqVO.Comp comp = new ErpOrderSaveReqVO.Comp();
            comp.setPo_item(detail.getLineNumber());
//            comp.setSched_line(index.get()); // 计划行号 -> 计划行号
//            comp.setItem_no(index.get()); // 项目编号 -> 项目编号
            comp.setMaterial(completePrefix(getMtrlZhongtongCode(detail.getSendMaterialNumber()))); // 物料号 -> 物料号
            comp.setPlant(detail.getReceiveFactoryNumber()); // 收货工厂 -> 收货工厂
            comp.setEntry_quantity(detail.getForecastQuantity()); // 委托加工需求数量 -> 委托加工需求数量
            comp.setEntry_uom(detail.getSendUnit()); // 组件计量单位 -> 组件计量单位
            comps.add(comp);
        });
        erpOrderSaveReqVO.setItems(items);
        erpOrderSaveReqVO.setItex(itexes);
        erpOrderSaveReqVO.setComps(comps);
        //列表-acct不需要委托订单不需要填写
    }

    public String getMtrlZhongtongCode(String materialNumber) {
        MaterialInfomationPageReqDTO infomationPageReqDTO = new MaterialInfomationPageReqDTO();
        infomationPageReqDTO.setPageSize(10000);
        infomationPageReqDTO.setCode(materialNumber);
        CommonResult<PageResult<MaterialInfomationRespDTO>> materialInfomationPage = materialInfomationApi.getMaterialInfomationPage(infomationPageReqDTO);
        if (materialInfomationPage.getData() == null || materialInfomationPage.getData().getList().isEmpty()) {
            throw exception(MTRL_CODE_NOT_EXISTS);

        }
        MaterialInfomationRespDTO materialInfomationRespDTO = materialInfomationPage.getData().getList().get(0);
        Map<String, Object> flatAttributes = materialInfomationRespDTO.getFlatAttributes();
        //获取中铜物料编码
        String mtrlZhongtongCode = flatAttributes.getOrDefault("mtrlZhongtongCode", "").toString();
        if (mtrlZhongtongCode.isEmpty()) {
            throw exception(MTRL_CODE_NOT_EXISTS);
        }
        return mtrlZhongtongCode;
    }
    private String completePrefix(String str) {
        String target = str == null ? "" : str;
        if (target.length() >= 18) return target;
        String temp = "000000000000000000" + target;
        return temp.substring(temp.length() - 18);
    }

}