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

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.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zt.plat.framework.common.pojo.CommonResult;
import com.zt.plat.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
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.originalmaterialprocessing.vo.OriginalMaterialProcessingDetailRespVO;
import com.zt.plat.module.contractorder.controller.admin.originalmaterialprocessing.vo.OriginalMaterialProcessingPageReqVO;
import com.zt.plat.module.contractorder.controller.admin.originalmaterialprocessing.vo.OriginalMaterialProcessingRespVO;
import com.zt.plat.module.contractorder.controller.admin.originalmaterialprocessing.vo.OriginalMaterialProcessingSaveReqVO;
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.dataobject.originalmaterialprocessing.OriginalMaterialProcessingDO;
import com.zt.plat.module.contractorder.dal.dataobject.originalmaterialprocessing.OriginalMaterialProcessingDetailDO;
import com.zt.plat.module.contractorder.dal.mysql.contract.SystemRelativityMapper;
import com.zt.plat.module.contractorder.dal.mysql.originalmaterialprocessing.OriginalMaterialProcessingMapper;
import com.zt.plat.module.contractorder.enums.OrderTypeEnum;
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.ErpSalesOrderSaveReqVO;
import com.zt.plat.module.erp.service.erp.ErpOrderService;
import com.zt.plat.module.system.api.sequence.SequenceApi;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import java.time.format.DateTimeFormatter;
import java.util.*;

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_NOT_EXISTS;
import static com.zt.plat.module.contractorder.enums.originalmaterialprocessing.ErrorCodeConstants.*;
import static com.zt.plat.module.contractorder.enums.purchaseorder.ErrorCodeConstants.MTRL_CODE_NOT_EXISTS;


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

    @Resource
    private OriginalMaterialProcessingMapper originalMaterialProcessingMapper;

    @Resource
    private OriginalMaterialProcessingDetailService originalMaterialProcessingDetailService;
    @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 OriginalMaterialProcessingRespVO createOriginalMaterialProcessing(OriginalMaterialProcessingSaveReqVO createReqVO) {
        // 插入
        OriginalMaterialProcessingDO originalMaterialProcessingDO = BeanUtils.toBean(createReqVO, OriginalMaterialProcessingDO.class);
        originalMaterialProcessingDO.setIsPush(0);
        originalMaterialProcessingDO.setStatus(OrderStatusEnum.IN_PROGRESS.getCode());
        originalMaterialProcessingDO.setSystemOrderNumber(this.generateOrderNumber(""));
        originalMaterialProcessingMapper.insert(originalMaterialProcessingDO);
        OriginalMaterialProcessingRespVO bean = BeanUtils.toBean(originalMaterialProcessingDO, OriginalMaterialProcessingRespVO.class);
        //批量插入委托加工订单明细
        if (createReqVO.getDetails() != null && !createReqVO.getDetails().isEmpty()) {
            createReqVO.getDetails().forEach(entrustOrderDetail -> entrustOrderDetail.setOrderId(originalMaterialProcessingDO.getId()));
            List<OriginalMaterialProcessingDetailRespVO> originalMaterialProcessingDetailRespVOS = originalMaterialProcessingDetailService.insertBatchSomeColumn(createReqVO.getDetails());
            bean.setDetails(originalMaterialProcessingDetailRespVOS);
        }
        // 返回
        return bean;
    }

    @Override
    public List<OriginalMaterialProcessingRespVO> createBatchOriginalMaterialProcessing(List<OriginalMaterialProcessingSaveReqVO> createReqVOS) {
        List<OriginalMaterialProcessingRespVO> respVOS = new ArrayList<>();
        createReqVOS.forEach(createReqVO -> {
            // 插入
            OriginalMaterialProcessingDO originalMaterialProcessingDO = BeanUtils.toBean(createReqVO, OriginalMaterialProcessingDO.class);
            originalMaterialProcessingDO.setIsPush(0);
            originalMaterialProcessingDO.setStatus(OrderStatusEnum.IN_PROGRESS.getCode());
            originalMaterialProcessingDO.setSystemOrderNumber(this.generateOrderNumber(""));
            originalMaterialProcessingMapper.insert(originalMaterialProcessingDO);
            OriginalMaterialProcessingRespVO bean = BeanUtils.toBean(originalMaterialProcessingDO, OriginalMaterialProcessingRespVO.class);
            //批量插入来料加工订单明细
            if (createReqVO.getDetails() != null && !createReqVO.getDetails().isEmpty()) {
                createReqVO.getDetails().forEach(entrustOrderDetail -> entrustOrderDetail.setOrderId(originalMaterialProcessingDO.getId()));
                List<OriginalMaterialProcessingDetailRespVO> originalMaterialProcessingDetailRespVOS = originalMaterialProcessingDetailService.insertBatchSomeColumn(createReqVO.getDetails());
                bean.setDetails(originalMaterialProcessingDetailRespVOS);
            }
            respVOS.add(bean);
        });
        return respVOS;
    }

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


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

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOriginalMaterialProcessing(Long id) {
        // 校验存在
        validateEntrustOrderOrderExists(id);
        // 删除
        originalMaterialProcessingMapper.deleteById(id);
        // 删除委托加工订单明细
        originalMaterialProcessingDetailService.deleteOriginalMaterialProcessingDetailByOrderIds(List.of(id));

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteOriginalMaterialProcessingListByIds(List<Long> ids) {
        // 校验存在
        validateEntrustOrderOrderExists(ids);
        // 删除
        originalMaterialProcessingMapper.deleteByIds(ids);
        // 删除委托加工订单明细
        originalMaterialProcessingDetailService.deleteOriginalMaterialProcessingDetailByOrderIds(ids);
    }

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

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

    @Override
    public OriginalMaterialProcessingDO getOriginalMaterialProcessing(Long id) {

        return originalMaterialProcessingMapper.selectById(id);
    }

    @Override
    public PageResult<OriginalMaterialProcessingDO> getOriginalMaterialProcessingPage(OriginalMaterialProcessingPageReqVO pageReqVO) {
        return originalMaterialProcessingMapper.selectPage(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    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) {
        OriginalMaterialProcessingDO originalMaterialProcessingDO = originalMaterialProcessingMapper.selectById(reqVO.getOrderId());
        if (originalMaterialProcessingDO == null) {
            throw exception(ORIGINAL_MATERIAL_PROCESSING_DO_NOT_EXISTS);
        }
        String contractNumber = originalMaterialProcessingDO.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<OriginalMaterialProcessingDO> originalMaterialProcessingDOS = originalMaterialProcessingMapper.selectList(new LambdaQueryWrapper<OriginalMaterialProcessingDO>().eq(OriginalMaterialProcessingDO::getContractNumber, systemContractNumber));
            originalMaterialProcessingDOS.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<OriginalMaterialProcessingRespVO> getBindOrderByOrder(DownOrUpOrderReqVO reqVO) {
        List<OriginalMaterialProcessingRespVO> 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<OriginalMaterialProcessingDO> originalMaterialProcessingDOS = originalMaterialProcessingMapper.selectByIds(systemRelativityDOS.stream().map(SystemRelativityDO::getUpId).toList());
                orderList = BeanUtils.toBean(originalMaterialProcessingDOS, OriginalMaterialProcessingRespVO.class);
            }
        } else {
            //下游
            log.info("获取下游订单");
            List<SystemRelativityDO> systemRelativityDOS = systemRelativityMapper.selectList(new LambdaQueryWrapper<SystemRelativityDO>().eq(SystemRelativityDO::getUpId, reqVO.getOrderId()));
            if (!systemRelativityDOS.isEmpty()) {
                List<OriginalMaterialProcessingDO> originalMaterialProcessingDOS = originalMaterialProcessingMapper.selectByIds(systemRelativityDOS.stream().map(SystemRelativityDO::getDownId).toList());
                orderList = BeanUtils.toBean(originalMaterialProcessingDOS, OriginalMaterialProcessingRespVO.class);
            }
        }
        return orderList;
    }

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

    @Override
    public List<OriginalMaterialProcessingDetailRespVO> getOriginalMaterialProcessingDetailListByOrderId(Long id) {
        return originalMaterialProcessingDetailService.getOriginalMaterialProcessingDetailListByOrderId(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitToErp061(Long id) {
        //获取订单并且判断
        OriginalMaterialProcessingDO originalMaterialProcessingDO
                = originalMaterialProcessingMapper.selectById(id);

        if (originalMaterialProcessingDO == null) {
            throw exception(ORIGINAL_MATERIAL_PROCESSING_DO_NOT_EXISTS);
        }


        if (!OrderTypeEnum.ENTED_PUR.getCode().equals(originalMaterialProcessingDO.getSplyBsnTp())) {
            throw exception(ORIGINAL_MATERIAL_PROCESSING_NOT_ALLOW_CALL_ERP, originalMaterialProcessingDO.getSplyBsnTp());
        }

        //获取明细
        List<OriginalMaterialProcessingDetailDO> originalMaterialProcessingDetailDOS = originalMaterialProcessingDetailService.queryOriginalMaterialProcessingDetailListByOrderId(id);
        if (originalMaterialProcessingDetailDOS.isEmpty()) {
            throw exception(ORIGINAL_MATERIAL_PROCESSING_DETAIL_NOT_EXISTS);
        }
        ErpOrderSaveReqVO erpOrderSaveReqVO = new ErpOrderSaveReqVO();
        build061ReqData(originalMaterialProcessingDO, originalMaterialProcessingDetailDOS, erpOrderSaveReqVO);
        String result = erpOrderService.submitOrderToErp061(erpOrderSaveReqVO);
        Long localOrderId = originalMaterialProcessingDO.getId();
        log.info("提交订单结果:{}", result);
        OriginalMaterialProcessingDO upVo = new OriginalMaterialProcessingDO();
        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);
            }
            originalMaterialProcessingMapper.updateById(upVo);
        } catch (Exception e) {
            upVo.setOrderSAPNumber(null);
            upVo.setErpStatus(OrderStatusEnum.RLBK.getCode()); // 异常时强制置为失败状态
            upVo.setCause("ERP返回结果解析/处理异常：" + e.getMessage());
            // 异常时仍需更新数据库，保证订单状态一致性
            originalMaterialProcessingMapper.updateById(upVo);
            log.error("订单推送ERP发生异常，本地订单ID【{}】，异常信息如下", localOrderId, e);
        }
    }

    private void build061ReqData(OriginalMaterialProcessingDO order, List<OriginalMaterialProcessingDetailDO> originalMaterialProcessingDetailDOS, ErpOrderSaveReqVO erpOrderSaveReqVO) {
        //订单号
        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);

        List<ErpOrderSaveReqVO.Item> items = new ArrayList<>();
        List<ErpOrderSaveReqVO.Itex> itexes = new ArrayList<>();
        originalMaterialProcessingDetailDOS.forEach(detail -> {
            ErpOrderSaveReqVO.Item item = new ErpOrderSaveReqVO.Item();
            item.setPo_item(detail.getLineNumber() != null ? detail.getLineNumber() : null); // 行项目 -> 行号
            item.setMaterial(completePrefix(getMtrlZhongtongCode(detail.getMaterialNumber()))); // 物料编码 -> 物料号
            item.setPlant(detail.getReceiveFactoryNumber()); // 收货工厂编码 -> 工厂
            item.setStge_loc(detail.getReceiveWarehouseNumber()); // 收货库位编码 -> 库存地点
            item.setQuantity(detail.getForecastQuantity()); // 暂估数量 -> 数量
            item.setPo_unit(detail.getUnit()); // 计量单位 -> 计量单位
            item.setNet_price(detail.getInTaxUnitPrice()); // 含税单价 -> 含税单价
            item.setPrice_unit(detail.getInTaxUnitPrice() != null ? detail.getInTaxUnitPrice().intValue() : 1); // 价格单位 -> 价格单位
            item.setTax_code(detail.getTaxNumber()); // 税码 -> 税码

            // 处理交货起止日期(格式: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")));
            }
            //vendMat不以'-'开头
            if (vendMat.charAt(0) != '-') {
                item.setVend_mat(vendMat.toString());
            }
            items.add(item);

            ErpOrderSaveReqVO.Itex itex = new ErpOrderSaveReqVO.Itex();
            itex.setPo_item(detail.getLineNumber() != null ? detail.getLineNumber() : null);
        });
        erpOrderSaveReqVO.setItems(items);
        erpOrderSaveReqVO.setItex(itexes);
    }
    public void submitToErp091(Long id) {
        //获取订单并且判断
        OriginalMaterialProcessingDO originalMaterialProcessingDO
                = originalMaterialProcessingMapper.selectById(id);
        if (originalMaterialProcessingDO == null) {
            throw exception(ORIGINAL_MATERIAL_PROCESSING_DO_NOT_EXISTS);
        }
        List<OriginalMaterialProcessingDetailDO> originalMaterialProcessingDetailDOS = originalMaterialProcessingDetailService.queryOriginalMaterialProcessingDetailListByOrderId(id);
        if (originalMaterialProcessingDetailDOS.isEmpty()) {
            throw exception(ORIGINAL_MATERIAL_PROCESSING_DETAIL_NOT_EXISTS);
        }
        ErpSalesOrderSaveReqVO erpSalesOrderSaveReqVO = new ErpSalesOrderSaveReqVO();
        //构建091请求数据
        build091ReqData(originalMaterialProcessingDO, originalMaterialProcessingDetailDOS, erpSalesOrderSaveReqVO);
        //提交091
        String result = erpOrderService.submitOrderToErp091(erpSalesOrderSaveReqVO);
        log.info("提交订单结果:{}", result);
    }
    private void build091ReqData(OriginalMaterialProcessingDO salesOrder, List<OriginalMaterialProcessingDetailDO> originalMaterialProcessingDetailDOS, ErpSalesOrderSaveReqVO erpSalesOrderSaveReqVO) {
        erpSalesOrderSaveReqVO.setOrderNo(salesOrder.getSystemOrderNumber());
        erpSalesOrderSaveReqVO.setPartn_es(salesOrder.getPayerNum()); // 供应商编码
        erpSalesOrderSaveReqVO.setPartn_numb(salesOrder.getSupplierNumber());// 付款方编码

        // 销售订单抬头
        ErpSalesOrderSaveReqVO.Head head = new ErpSalesOrderSaveReqVO.Head();
        head.setDoc_type(salesOrder.getType()); // 销售订单类型
        head.setSales_org(salesOrder.getSaleOrgzCd()); // 销售组织
        head.setDistr_chan(salesOrder.getSaleAcsCdg()); // 销售渠道
        head.setDivision(salesOrder.getPdtGrpCdg());// 产品组
        head.setReq_date_h(salesOrder.getVoucherDate()); // 交货日期
        head.setSales_grp(salesOrder.getPurchaseGroup()); // 销售组
        //  head.setSales_off(salesOrder.getSaleOrgzName()); // 销售办事处
        // head.setCust_grp1("10"); // 客户组
        head.setPurch_no_c(salesOrder.getPaperContractNumber());//纸质合同编号
        head.setName(salesOrder.getContractName());
        //  head.setRef_1();
        // head.setPurch_date();
        // head.setOrd_reason();
        head.setCurrency(salesOrder.getCurrencyNumber()); // 货币码
        // head.setTaxclass(1);
        erpSalesOrderSaveReqVO.setHead(head);
        List<ErpSalesOrderSaveReqVO.Item> items = new ArrayList<>();
        originalMaterialProcessingDetailDOS.forEach(detail -> {
            ErpSalesOrderSaveReqVO.Item item = new ErpSalesOrderSaveReqVO.Item();
            item.setItem_categ(String.valueOf(detail.getLineNumber()));
            item.setMaterial(completePrefix(getMtrlZhongtongCode(detail.getMaterialNumber())));
            item.setPlant(detail.getSendFactoryNumber());
            item.setStore_loc(detail.getSendWarehouseNumber());
            item.setSales_unit(detail.getUnit());
            item.setDlvschduse(detail.getInvoiceType()); // 开票类型
            item.setTarget_qty(detail.getForecastQuantity());
            item.setItm_number(Math.toIntExact(detail.getLineNumber()));
            item.setItem_categ(detail.getProjectCategory());
            item.setShip_point(detail.getShippingPlace()); // 装运地点
            item.setAcct_assgt(detail.getMetalAcctasscatGroup());//todo 物料科目分配组
            items.add(item);
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitToErp(Long id) {
        //获取订单并且判断
        OriginalMaterialProcessingDO originalMaterialProcessingDO
                = originalMaterialProcessingMapper.selectById(id);
        if (originalMaterialProcessingDO == null) {
            throw exception(ORIGINAL_MATERIAL_PROCESSING_DO_NOT_EXISTS);
        }
        if (OrderTypeEnum.ENTED_PUR.getCode().equals(originalMaterialProcessingDO.getSplyBsnTp())) {
            submitToErp061(id);
        } else if (OrderTypeEnum.ENTED_SALE.getCode().equals(originalMaterialProcessingDO.getSplyBsnTp())) {
            //销售
             submitToErp091(id);
        } else {
            throw exception(ORIGINAL_MATERIAL_PROCESSING_NOT_ALLOW_CALL_ERP, originalMaterialProcessingDO.getSplyBsnTp());
        }
    }

    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);
    }
}