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

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONException;
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.framework.common.pojo.PageResult;
import com.zt.plat.framework.common.util.object.BeanUtils;
import com.zt.plat.framework.security.core.util.SecurityFrameworkUtils;
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.bpm.api.task.BpmProcessInstanceApi;
import com.zt.plat.module.bpm.api.task.BpmTaskApi;
import com.zt.plat.module.bpm.api.task.dto.*;
import com.zt.plat.module.bpm.enums.task.BpmProcessInstanceStatusEnum;
import com.zt.plat.module.contractorder.api.vo.contract.ContractRespVO;
import com.zt.plat.module.contractorder.controller.admin.purchaseorder.vo.*;
import com.zt.plat.module.contractorder.controller.admin.salesorder.vo.*;
import com.zt.plat.module.contractorder.dal.dataobject.contract.SystemRelativityDO;
import com.zt.plat.module.contractorder.dal.dataobject.salesorder.SalesOrderDO;
import com.zt.plat.module.contractorder.dal.mysql.contract.SystemRelativityMapper;
import com.zt.plat.module.contractorder.dal.mysql.salesorder.SalesOrderMapper;
import com.zt.plat.module.contractorder.enums.ErpConstants;
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.contractorder.util.constants.ProcessDefinitionKeyConstants;
import com.zt.plat.module.erp.controller.admin.erp.vo.ErpSalesOrderSaveReqVO;
import com.zt.plat.module.erp.controller.admin.erp.vo.SalesDocumentRequestVO;
import com.zt.plat.module.erp.controller.admin.erp.vo.WarehouseFactoryRespVO;
import com.zt.plat.module.erp.dal.dataobject.erp.internalwarehouse.InternalWarehouseDO;
import com.zt.plat.module.erp.service.erp.ErpOrderService;
import com.zt.plat.module.erp.service.erp.WarehouseFactoryService;
import com.zt.plat.module.erp.service.erp.internalwarehouse.InternalWarehouseService;
import com.zt.plat.module.system.api.sequence.SequenceApi;
import com.zt.plat.module.system.api.user.AdminUserApi;
import com.zt.plat.module.system.api.user.dto.AdminUserRespDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
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.ErrorCodeConstants.CONTRACT_ORDER_EXISTS;
import static com.zt.plat.module.contractorder.enums.purchaseorder.ErrorCodeConstants.*;


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

    @Resource
    private SalesOrderMapper salesOrderMapper;
    @Resource
    private SalesOrderDetailService salesOrderDetailService;

    @Resource
    private BpmProcessInstanceApi bpmProcessInstanceApi;
    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private BpmTaskApi bpmTaskApi;

    @Resource
    private SequenceApi sequenceApi;

    @Resource
    private ErpOrderService erpOrderService;

    @Resource
    private SystemRelativityMapper systemRelativityMapper;

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

    @Resource
    private WarehouseFactoryService warehouseFactoryService;
    @Resource
    private InternalWarehouseService internalWarehouseService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SalesOrderRespVO createSalesOrder(SalesOrderSaveReqVO createReqVO) {
        // 插入
        SalesOrderDO salesOrderDO = BeanUtils.toBean(createReqVO, SalesOrderDO.class);
        //订单号
        salesOrderDO.setIsPush(0);
        salesOrderDO.setStatus(OrderStatusEnum.IN_PROGRESS.getCode());
        String orderNumber = generateOrderNumber(salesOrderDO.getMtrlTp());
        salesOrderDO.setSystemOrderNumber(orderNumber);
        salesOrderMapper.insert(salesOrderDO);
        //插入订单明细
        if (createReqVO.getDetails() == null || createReqVO.getDetails().isEmpty()) {
            throw exception(Sales_ORD_DTL_NOT_EXISTS);
        }
        createReqVO.getDetails().forEach(details -> details.setOrderId(String.valueOf(salesOrderDO.getId())));
        List<SalesOrderDetailRespVO> salesOrderDetail = salesOrderDetailService.createSalesOrderDetail(createReqVO.getDetails());
        // 返回
        SalesOrderRespVO bean = BeanUtils.toBean(salesOrderDO, SalesOrderRespVO.class);
        bean.setSalesOrderDetailRespVOS(salesOrderDetail);
        return bean;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSalesOrder(SalesOrderSaveReqVO updateReqVO) {
        // 校验存在
        validateSalesOrderExists(updateReqVO.getId());

        SalesOrderDO updateObj = BeanUtils.toBean(updateReqVO, SalesOrderDO.class);
        updateReqVO.getDetails().forEach(details -> details.setOrderId(String.valueOf(updateObj.getId())));
        if (updateObj.getOrderSAPNumber() != null) {
            submitErpUpdate092(updateObj, updateReqVO.getDetails());//更新 ERP
        }
        // 更新
        salesOrderMapper.updateById(updateObj);
        if (updateReqVO.getDetails() == null || updateReqVO.getDetails().isEmpty()) {
            return;
        }
        salesOrderDetailService.updateSalesOrderDetailList(updateReqVO.getDetails());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSalesOrder(Long id) {
        // 校验存在
        validateSalesOrderExists(id);
        // 删除
        salesOrderMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteSalesOrderListByIds(List<Long> ids) {
        // 校验存在
        validateSalesOrderExists(ids);
        // 删除
        salesOrderMapper.deleteByIds(ids);
        //删除消费订单明细
        salesOrderDetailService.deleteSalesOrderDetailByOrderIds(ids);
    }

    private void validateSalesOrderExists(List<Long> ids) {
        List<SalesOrderDO> list = salesOrderMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(Sales_ORDER_NOT_EXISTS);
        }
    }

    private void validateSalesOrderExists(Long id) {
        if (salesOrderMapper.selectById(id) == null) {
            throw exception(Sales_ORDER_NOT_EXISTS);
        }
    }

    @Override
    public SalesOrderDO getSalesOrder(Long id, String splyBsnTp) {
        return salesOrderMapper.selectOne(new LambdaQueryWrapper<SalesOrderDO>().eq(SalesOrderDO::getId, id).eq(splyBsnTp != null && !splyBsnTp.isEmpty(), SalesOrderDO::getSplyBsnTp, splyBsnTp));
    }

    @Override
    public PageResult<SalesOrderDO> getSalesOrderPage(SalesOrderPageReqVO pageReqVO) {
        return salesOrderMapper.selectPage(pageReqVO);
    }

    @Override
    public void setSalesOrderDetail(SalesOrderRespVO salesOrderRespVO) {
        List<SalesOrderDetailRespVO> salesOrderDetailByOrderId = salesOrderDetailService.getSalesOrderDetailByOrderId(salesOrderRespVO.getId());
        salesOrderRespVO.setSalesOrderDetailRespVOS(salesOrderDetailByOrderId);
    }

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


    @Override
    public boolean pushErp091(String orderId) {
        SalesOrderDO salesOrderDO = salesOrderMapper.selectById(orderId);
        if (salesOrderDO == null) {
            throw exception(Sales_ORDER_NOT_EXISTS);
        }
        List<SalesOrderDetailRespVO> salesOrderDetailByOrderId = salesOrderDetailService.getSalesOrderDetailByOrderId(Long.valueOf(orderId));
        if (CollUtil.isEmpty(salesOrderDetailByOrderId)) {
            throw exception(Sales_ORD_DTL_NOT_EXISTS);
        }
        submitErp091(salesOrderDO, salesOrderDetailByOrderId);
        return true;
    }

    private void submitErp091(SalesOrderDO salesOrderDO, List<SalesOrderDetailRespVO> salesOrderDetailByOrderId) {
        ErpSalesOrderSaveReqVO erpSalesOrderSaveReqVO = new ErpSalesOrderSaveReqVO();
        erpSalesOrderSaveReqVO.setOrderNo(salesOrderDO.getSystemOrderNumber());
        erpSalesOrderSaveReqVO.setPartn_es(salesOrderDO.getPayerNum()); // 供应商编码
        erpSalesOrderSaveReqVO.setPartn_numb(salesOrderDO.getSupplierNumber());// 付款方编码

        // 销售订单抬头
        ErpSalesOrderSaveReqVO.Head head = new ErpSalesOrderSaveReqVO.Head();
        head.setDoc_type(salesOrderDO.getType()); // 销售订单类型
        head.setSales_org(salesOrderDO.getSaleOrgzCd()); // 销售组织
        head.setDistr_chan(salesOrderDO.getSaleAcsCdg()); // 销售渠道
        head.setDivision(salesOrderDO.getPdtGrpCdg());// 产品组
        head.setReq_date_h(salesOrderDO.getVoucherDate()); // 交货日期
        head.setSales_grp(salesOrderDO.getPurchaseGroup()); // 销售组
        //  head.setSales_off(salesOrderDO.getSaleOrgzName()); // 销售办事处
        // head.setCust_grp1("10"); // 客户组
        head.setPurch_no_c(salesOrderDO.getPaperContractNumber());//纸质合同编号
        head.setName(salesOrderDO.getContractName());
        //  head.setRef_1();
        // head.setPurch_date();
        // head.setOrd_reason();
        head.setCurrency(salesOrderDO.getCurrencyNumber()); // 货币码
        // head.setTaxclass(1);
        erpSalesOrderSaveReqVO.setHead(head);
        // 销售订单明细
        List<ErpSalesOrderSaveReqVO.Item> items = new ArrayList<>();
        for (SalesOrderDetailRespVO salesOrderDetailRespVO : salesOrderDetailByOrderId) {
            MaterialInfomationPageReqDTO infomationPageReqDTO = new MaterialInfomationPageReqDTO();
            infomationPageReqDTO.setPageSize(10000);
            infomationPageReqDTO.setCode(salesOrderDetailRespVO.getMaterialNumber());
            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);
            }
            //查询对应的库位和工厂
            // WarehouseFactoryRespVO boundFactoryAndWarehouse = getBoundFactoryAndWarehouse(salesOrderDetailRespVO.getFactoryNumber(), salesOrderDetailRespVO.getWarehouseNumber());
            ErpSalesOrderSaveReqVO.Item item = new ErpSalesOrderSaveReqVO.Item();
            item.setItem_categ(String.valueOf(salesOrderDetailRespVO.getLineNumber()));
            item.setMaterial(mtrlZhongtongCode);
            item.setPlant(salesOrderDetailRespVO.getFactoryNumber());
            item.setStore_loc(salesOrderDetailRespVO.getWarehouseNumber());
            item.setSales_unit(salesOrderDetailRespVO.getUnit());
            item.setDlvschduse(salesOrderDetailRespVO.getInvoiceType());
            item.setTarget_qty(salesOrderDetailRespVO.getQuantity());
            item.setItm_number(Math.toIntExact(salesOrderDetailRespVO.getLineNumber()));
            item.setItem_categ(salesOrderDetailRespVO.getProjectCategory());
            item.setShip_point(salesOrderDetailRespVO.getShippingPlace()); // 装运地点
            item.setAcct_assgt(salesOrderDetailRespVO.getMetalAcctasscatGroup());//todo 物料科目分配组
            items.add(item);
        }
        erpSalesOrderSaveReqVO.setItems(items);
        // 请求列表-cond
//        List<ErpSalesOrderSaveReqVO.Cond> conds = new ArrayList<>();
//        for (SalesOrderDetailRespVO salesOrderDetailRespVO : salesOrderDetailByOrderId) {
//            ErpSalesOrderSaveReqVO.Cond cond = new ErpSalesOrderSaveReqVO.Cond();
//            cond.setCond_type(salesOrderDetailRespVO.getTaxAcctasscat());//条件类型
//            cond.setCond_value(salesOrderDetailRespVO.getGross());//条件金额
//            cond.setCurrency(salesOrderDO.getCurrencyNumber()); //货币码
//            cond.setCond_unit(salesOrderDetailRespVO.getUnit());
//            cond.setCond_p_unt(1); //固定值1
//            conds.add(cond);
//        }
//        erpSalesOrderSaveReqVO.setConds(conds);
        List<String> conds = new ArrayList<>();
        salesOrderDetailByOrderId.forEach(salesOrderDetailRespVO -> {
            String priceConditionDetail = salesOrderDetailRespVO.getPriceConditionDetail();
            if (priceConditionDetail == null || priceConditionDetail.trim().isEmpty()) {
                return; // 空字符串直接跳过
            }
            try {
                // 解析 JSON 数组，捕获格式错误
                List<String> strList = JSONArray.parseArray(priceConditionDetail, String.class);
                // List<JSONArray> jsonArrays = JSONArray.parseArray(priceConditionDetail, JSONArray.class);
                conds.addAll(strList);
            } catch (JSONException e) {
                // 处理解析失败（例如打日志、忽略错误数据等）
                log.error("解析价格条件详情失败，内容：{}", priceConditionDetail, e);
            }
        });
        erpSalesOrderSaveReqVO.setConds(conds);
        String result = erpOrderService.submitOrderToErp091(erpSalesOrderSaveReqVO);
        log.info("ERP返回结果：{}", result);
        SalesOrderDO upVo = new SalesOrderDO();
        upVo.setId(salesOrderDO.getId());
        JSONObject rootObj = JSONObject.parseObject(result);
        String flag = rootObj.getString("flag");
        if (result != null && !result.trim().isEmpty()&&"S".equals(flag)) {
            try {
                // ========== FastJSON2 核心解析 ==========
                // 3. 解析E_RESP
                String eRespStr = rootObj.getString("E_RESP");
                String salesdocument = null;
                if (eRespStr != null && !eRespStr.trim().isEmpty()) {
                    JSONObject eRespObj = JSONObject.parseObject(eRespStr);
                    // 提取销售单号并去除空格
                    salesdocument = eRespObj.getString("SALESDOCUMENT");
                    if (salesdocument != null) {
                        salesdocument = salesdocument.trim();
                    }
                }
                upVo.setOrderSAPNumber(salesdocument);

                String resStr = rootObj.getString("resStr");
                List<JSONObject> msgList = null;
                if (resStr != null && !resStr.trim().isEmpty()) {
                    JSONArray msgArray = JSONArray.parseArray(resStr);
                    msgList = msgArray.stream().map(item -> (JSONObject) item).toList();
                }

                // 5. 业务成功/失败判断
                if (salesdocument != null && !salesdocument.isEmpty()) {
                    // 成功：更新为FIND状态
                    upVo.setErpStatus(OrderStatusEnum.FIND.getCode());
                    upVo.setCause("ERP订单提交成功，SAP单号：" + salesdocument);
                    //价格条件flag变更为U
                    updateConditionFlag(salesOrderDetailByOrderId);
                } else {
                    // 失败：拼接详细原因
                    StringBuilder failMsg = new StringBuilder("ERP订单提交失败：");
                    failMsg.append("flag=").append(flag).append("，SAP单号=").append(salesdocument).append("；");

                    if (msgList != null && !msgList.isEmpty()) {
                        for (JSONObject msg : msgList) {
                            String type = msg.getString("TYPE");
                            String message = msg.getString("MESSAGE");
                            String number = msg.getString("NUMBER");
                            failMsg.append("[").append(type).append("]").append(number).append(":").append(message).append("; ");
                        }
                    } else {
                        failMsg.append("无具体返回消息");
                    }
                    upVo.setErpStatus(OrderStatusEnum.RLBK.getCode());
                    upVo.setCause(failMsg.toString());
                }
            } catch (Exception e) {
                // 捕获所有解析异常，保证流程不中断
                log.error("FastJSON2解析ERP返回结果失败", e);
                upVo.setErpStatus(OrderStatusEnum.RLBK.getCode());
                upVo.setCause("解析ERP返回结果失败：" + e.getMessage());
            }
        } else {
            upVo.setErpStatus(OrderStatusEnum.RLBK.getCode());
            upVo.setCause(rootObj.toString().isBlank()?"ERP返回结果为空":rootObj.toString());
        }
        // 执行数据库更新
        salesOrderMapper.updateById(upVo);

    }

    private void updateConditionFlag(List<SalesOrderDetailRespVO> salesOrderDetailList){
        log.info("更新明细的价格条件操作类型为U，ID：【{}】", salesOrderDetailList.stream().map(SalesOrderDetailRespVO::getId).toList());
        salesOrderDetailService.updateSalesOrderDetailList(BeanUtils.toBean(salesOrderDetailList,SalesOrderDetailSaveReqVO.class));
    }


    @Override
    @Transactional
    public String submitOrder(String id) {
        if (ObjectUtils.isEmpty(id)) {
            throw exception(ORDER_ID_NOT_EXISTS);
        }
        SalesOrderDO salesOrderDO = salesOrderMapper.selectById(id);
        if (ObjectUtils.isEmpty(salesOrderDO)) {
            throw exception(ORDER_ID_NOT_EXISTS);
        }
        if (salesOrderDO.getIsPush() == 0) {
            throw exception(ORDER_DONT_SUBMIT);
        }
        AdminUserRespDTO adminUserRespDTO = adminUserApi.getUser(SecurityFrameworkUtils.getLoginUserId()).getData();
        if (ObjectUtils.isEmpty(salesOrderDO.getProcessInstanceId())) {
            BpmProcessInstanceCreateReqDTO pidto = new BpmProcessInstanceCreateReqDTO();
            pidto.setProcessDefinitionKey(ProcessDefinitionKeyConstants.SALES_ORDER_REVIEW_PROCESS);
            pidto.setBusinessKey(id);
            String data = bpmProcessInstanceApi.createProcessInstance(adminUserRespDTO.getId(), pidto).getData();
            if (StringUtils.isNotBlank(data)) {
                // 获取流程当前审批的任务节点
                List<BpmTaskRespDTO> taskList = bpmTaskApi.getTaskListByProcessInstanceId(data).getData();
                salesOrderDO.setProcessInstanceId(data);
                if (CollectionUtils.isNotEmpty(taskList)) {
                    BpmTaskRespDTO undoTask = taskList.get(taskList.size() - 1);// 获取流程当前审批的任务节点
                    salesOrderDO.setTaskId(undoTask.getId());
                }
                salesOrderDO.setStatus(OrderStatusEnum.APPROVING.getCode()); //
                salesOrderMapper.updateById(salesOrderDO);
                return "提交审批成功";
            }

        } else {
            // 获取流程当前审批的任务节点
            List<BpmTaskRespDTO> taskList = bpmTaskApi.getTaskListByProcessInstanceId(salesOrderDO.getProcessInstanceId()).getData();
            if (CollectionUtils.isNotEmpty(taskList)) {
                BpmTaskRespDTO bpmTaskDto = taskList.get(taskList.size() - 1);
                BpmApprovalDetailReqDTO badrDto = new BpmApprovalDetailReqDTO();
                badrDto.setProcessInstanceId(salesOrderDO.getProcessInstanceId()); // 流程实例id
                badrDto.setTaskId(bpmTaskDto.getId()); // 当前审核任务节点id
                BpmApprovalDetailRespDTO approvalDetail = bpmProcessInstanceApi.getApprovalDetail(SecurityFrameworkUtils.getLoginUserId(), badrDto).getData();
                if (BpmProcessInstanceStatusEnum.REJECT.getStatus().equals(approvalDetail.getStatus())) {
                    // 如果状态是驳回状态,需要重新创建一个流程实例
                    BpmProcessInstanceCreateReqDTO pidtoNew = new BpmProcessInstanceCreateReqDTO();
                    pidtoNew.setProcessDefinitionKey(ProcessDefinitionKeyConstants.SALES_ORDER_REVIEW_PROCESS);
                    pidtoNew.setBusinessKey(String.valueOf(id));
                    String data = bpmProcessInstanceApi.createProcessInstance(adminUserRespDTO.getId(), pidtoNew).getData();
                    if (StringUtils.isNotBlank(data)) {
                        // 获取流程当前审批的任务节点
                        List<BpmTaskRespDTO> taskListNew = bpmTaskApi.getTaskListByProcessInstanceId(data).getData();
                        salesOrderDO.setProcessInstanceId(data);
                        if (CollectionUtils.isNotEmpty(taskListNew)) {
                            BpmTaskRespDTO undoTask = taskListNew.get(taskListNew.size() - 1);
                            salesOrderDO.setTaskId(undoTask.getId());
                        }
                        salesOrderDO.setStatus(OrderStatusEnum.APPROVING.getCode());
                        salesOrderMapper.updateById(salesOrderDO);
                        return "提交审批成功";
                    }
                } else if (BpmProcessInstanceStatusEnum.APPROVE.getStatus().equals(approvalDetail.getStatus())) {
                    return "该授信单审批流程已经审批通过";
                }
            }
        }
        log.info("流程实例id:{}", salesOrderDO.getProcessInstanceId());
        return "提交审批成功";
    }

//    @Override
//    @Transactional
//    public boolean orderPassReject(SalesOrderReviewReqVO salesOrderReviewReqVO) {
//        SalesOrderDO salesOrderDO = salesOrderMapper.selectById(salesOrderReviewReqVO.getId());
//        if (ObjectUtils.isEmpty(salesOrderDO)) {
//            throw exception(PURCHASE_ORDER_NOT_EXISTS);
//        }
//        // 获取当前流程正在审批的任务节点
//        List<BpmTaskRespDTO> taskList = bpmTaskApi.getTaskListByProcessInstanceId(salesOrderDO.getProcessInstanceId()).getData();
//        BpmTaskRespDTO undoTask = taskList.get(taskList.size() - 1);
//
//        // 判断是否流程已经通过、驳回
//        BpmApprovalDetailReqDTO badrDto = new BpmApprovalDetailReqDTO();
//        badrDto.setProcessInstanceId(salesOrderDO.getProcessInstanceId()); // 流程实例id
//        badrDto.setTaskId(undoTask.getId()); // 当前审核任务节点id
//        BpmApprovalDetailRespDTO approvalDetail = bpmProcessInstanceApi.getApprovalDetail(SecurityFrameworkUtils.getLoginUserId(), badrDto).getData();
//        //如果审核通过
//        if ("WAIT_PUSH".equals(salesOrderReviewReqVO.getStatus())) {
//            salesOrderDO.setStatus(getStatusByBpmProcessInstanceCode(approvalDetail.getStatus()));
//        } else  {
//            //如果审核不通过
//            salesOrderDO.setStatus(OrderStatusEnum.DRAFT.getCode());
//        }
//        //设置审核意见
//        salesOrderDO.setReviewOpinion(salesOrderDO.getReviewOpinion());
//        if (ObjectUtils.isNotEmpty(undoTask)) {
//            salesOrderDO.setTaskId(undoTask.getId());
//        }
//        salesOrderMapper.updateById(salesOrderDO); //更新状态
//
//        // 需要调用bpm 审核接口更新审批中的状态
//        if (DictEnum.BSE_CTRT_STS_WAIT_PUSH.getCode().equals(salesOrderDO.getStatus()) && ObjectUtils.isNotEmpty(undoTask)) {
//            if (approvalDetail.getStatus().equals(BpmProcessInstanceStatusEnum.RUNNING.getStatus())) {
//                BpmTaskApproveReqDTO btarDto = new BpmTaskApproveReqDTO();
//                btarDto.setId(undoTask.getId());
//                btarDto.setReason(salesOrderDO.getReviewOpinion());
//                bpmProcessInstanceApi.approveTask(btarDto);
//            }
//        } else if (DictEnum.BSE_CTRT_STS_REJECTED.getCode().equals(salesOrderDO.getStatus()) && ObjectUtils.isNotEmpty(undoTask)) {
//            if (approvalDetail.getStatus().equals(BpmProcessInstanceStatusEnum.RUNNING.getStatus())) {
//                BpmTaskRejectReqDTO btrrDto = new BpmTaskRejectReqDTO();
//                btrrDto.setId(undoTask.getId());
//                btrrDto.setReason(salesOrderDO.getReviewOpinion());
//                bpmProcessInstanceApi.rejectTask(btrrDto);
//            }
//        }
//        return true;
//    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean orderPassReject(SalesOrderReviewReqVO salesOrderReviewReqVO) {
        // 查询采购单
        SalesOrderDO salesOrderDO = salesOrderMapper.selectById(salesOrderReviewReqVO.getId());
        if (ObjectUtils.isEmpty(salesOrderDO)) {
            throw exception(PURCHASE_ORDER_NOT_EXISTS);
        }

        // 获取当前流程的所有任务节点
        List<BpmTaskRespDTO> taskList = bpmTaskApi.getTaskListByProcessInstanceId(salesOrderDO.getProcessInstanceId()).getData();

        // 筛选出当前待处理的任务（未结束的任务）
        BpmTaskRespDTO undoTask = taskList.stream().filter(task -> task.getEndTime() == null).findFirst().orElse(null);

        if (ObjectUtils.isEmpty(undoTask)) {
            throw new RuntimeException("未找到待审批的任务节点");
        }

        // 先调用BPM审批接口，再更新本地状态
        if (DictEnum.BSE_CTRT_STS_WAIT_PUSH.getCode().equals(salesOrderReviewReqVO.getStatus())) {
            // 审批通过
            BpmTaskApproveReqDTO btarDto = new BpmTaskApproveReqDTO();
            btarDto.setId(undoTask.getId());
            btarDto.setReason(salesOrderReviewReqVO.getReviewOpinion());
            CommonResult<Boolean> result = bpmProcessInstanceApi.approveTask(btarDto);
            if (result.isError()) {
                throw new RuntimeException(result.getMsg());
            }
        } else if (DictEnum.BSE_CTRT_STS_REJECTED.getCode().equals(salesOrderReviewReqVO.getStatus())) {
            // 审批驳回
            BpmTaskRejectReqDTO btrrDto = new BpmTaskRejectReqDTO();
            btrrDto.setId(undoTask.getId());
            btrrDto.setReason(salesOrderReviewReqVO.getReviewOpinion());
            CommonResult<Boolean> result = bpmProcessInstanceApi.rejectTask(btrrDto);
            if (result.isError()) {
                throw new RuntimeException(result.getMsg());
            }
        }

        // 调用BPM接口后，查询最新的审批详情
        BpmApprovalDetailReqDTO badrDto = new BpmApprovalDetailReqDTO();
        badrDto.setProcessInstanceId(salesOrderDO.getProcessInstanceId());
        badrDto.setTaskId(undoTask.getId());
        BpmApprovalDetailRespDTO approvalDetail = bpmProcessInstanceApi.getApprovalDetail(SecurityFrameworkUtils.getLoginUserId(), badrDto).getData();

        // 使用统一方法转换状态
        salesOrderDO.setStatus(getStatusByBpmProcessInstanceCode(approvalDetail.getStatus()));
        salesOrderDO.setReviewOpinion(salesOrderReviewReqVO.getReviewOpinion());
        salesOrderDO.setTaskId(undoTask.getId());

        salesOrderMapper.updateById(salesOrderDO);

        return true;
    }

    @Override
    public boolean linkOrder(LinkOrderReqVO LinkOrderReqVO) {

        SystemRelativityDO saveDO = new SystemRelativityDO();
        saveDO.setStatus(DictEnum.BSE_SYS_REL_TP_ORDER.getCode());
        saveDO.setUpId(LinkOrderReqVO.getUpOrderId());
        saveDO.setDownId(LinkOrderReqVO.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) {
        SalesOrderDO salesOrderDO = salesOrderMapper.selectById(reqVO.getOrderId());
        if (salesOrderDO == null) {
            throw exception(PURCHASE_ORDER_NOT_EXISTS);
        }
        String contractNumber = salesOrderDO.getContractNumber();// 合同号
        ContractRespVO bySystemContractNumber = contractService.getBySystemContractNumber(contractNumber);
        ContractRespVO upRelation = null;
        if ("up".equals(reqVO.getOrderType())) {
            log.info("获取上游订单");
            //上游
            upRelation = contractService.getUpRelation(bySystemContractNumber.getId());
        } else {
            //下游
            log.info("获取下游订单");
            upRelation = contractService.getDownRelation(bySystemContractNumber.getId());
        }
        List<DownOrUpOrderRespVO> orderList = new ArrayList<>();
        if (upRelation != null) {
            String systemContractNumber = upRelation.getSystemContractNumber();

            List<SalesOrderDO> salesOrderDOS = salesOrderMapper.selectList(new LambdaQueryWrapper<SalesOrderDO>().eq(SalesOrderDO::getContractNumber, systemContractNumber));
            salesOrderDOS.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, SalesOrderRespVO.class));
                orderList.add(downOrUpOrderRespVO);
            });

        }
        return orderList;
    }

    @Override
    public List<PurchaseOrderRespVO> getBindOrderByOrder(DownOrUpOrderReqVO reqVO) {
        List<PurchaseOrderRespVO> 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<SalesOrderDO> salesOrderDOS = salesOrderMapper.selectByIds(systemRelativityDOS.stream().map(SystemRelativityDO::getUpId).toList());
                orderList = BeanUtils.toBean(salesOrderDOS, PurchaseOrderRespVO.class);
            }
        } else {
            //下游
            log.info("获取下游订单");
            List<SystemRelativityDO> systemRelativityDOS = systemRelativityMapper.selectList(new LambdaQueryWrapper<SystemRelativityDO>().eq(SystemRelativityDO::getUpId, reqVO.getOrderId()));
            if (!systemRelativityDOS.isEmpty()) {
                List<SalesOrderDO> purchaseOrderDOS = salesOrderMapper.selectByIds(systemRelativityDOS.stream().map(SystemRelativityDO::getDownId).toList());
                orderList = BeanUtils.toBean(purchaseOrderDOS, PurchaseOrderRespVO.class);
            }
        }
        return orderList;
    }

    @Override
    public void updateOrderStatusByIdOrOrderNo(OrderStsReqVO reqVO) {
        // 校验存在
        if (reqVO.getIds() != null) {
            validateSalesOrderExists(reqVO.getIds());
        }
        if (reqVO.getOrderNos() != null) {
            validateSalesOrderNosExists(reqVO.getOrderNos());
        }
        OrderStatusEnum byCode = OrderStatusEnum.getByCode(reqVO.getSts());
        if (byCode == null) {
            throw exception(PURCHASE_ORDER_STATUS_ERROR);
        }
        salesOrderMapper.update(new LambdaUpdateWrapper<SalesOrderDO>().in(reqVO.getOrderNos() != null, SalesOrderDO::getSystemOrderNumber, reqVO.getOrderNos()).in(reqVO.getIds() != null, SalesOrderDO::getId, reqVO.getIds()).set(SalesOrderDO::getStatus, reqVO.getSts()));
    }


    private void validateSalesOrderNosExists(List<String> orderNos) {
        List<SalesOrderDO> list = salesOrderMapper.selectList(new LambdaQueryWrapper<SalesOrderDO>().in(SalesOrderDO::getSystemOrderNumber, orderNos));
        if (CollUtil.isEmpty(list) || list.size() != orderNos.size()) {
            throw exception(PURCHASE_ORDER_NOT_EXISTS);
        }
    }

    private String getStatusByBpmProcessInstanceCode(Integer code) {
        return Optional.ofNullable(code).map(c -> switch (c) {
            case -1, 3, 4 -> OrderStatusEnum.REJECTED.getCode();
            case 1 -> OrderStatusEnum.APPROVING.getCode();
            case 2 -> OrderStatusEnum.TO_SUBMIT_ERP.getCode();
            default -> throw new IllegalArgumentException("未定义的BPM状态码：" + c);
        }).orElseThrow(() -> new IllegalArgumentException("BPM状态码不能为null"));
    }

    private String R() {
        int number = (int) (Math.random() * 900000 + 100000);
        return String.valueOf(number);
    }

    @Override
    public SalesOrderDO getSalesOrderByOrderNo(String orderNo) {
        return salesOrderMapper.selectOne(SalesOrderDO::getSystemOrderNumber, orderNo);
    }

    public void submitErpUpdate092(SalesOrderDO salesOrderDO, List<SalesOrderDetailSaveReqVO> salesOrderDetailList) {
        //提交092的参数
        SalesDocumentRequestVO salesDocumentRequestVO = new SalesDocumentRequestVO();
        buildSalesDocumentRequestData(salesDocumentRequestVO, salesOrderDO, salesOrderDetailList);
        String result = erpOrderService.submitOrderToErp092(salesDocumentRequestVO);
        log.info("销售订单ID：【{}】,提交092结果：【{}】", salesOrderDO.getId(), result);

    }

    public void buildSalesDocumentRequestData(SalesDocumentRequestVO salesDocumentRequestVO, SalesOrderDO salesOrderDO, List<SalesOrderDetailSaveReqVO> salesOrderDetailList) {
        //head-抬头
        salesDocumentRequestVO.setOrderNo(salesOrderDO.getSystemOrderNumber());
        salesDocumentRequestVO.setSalesdocument(salesOrderDO.getOrderSAPNumber());
        salesDocumentRequestVO.setUpdateflag(ErpConstants.SALES_DOCUMENT_REQUEST_FLAG_U);
        salesDocumentRequestVO.setPartn_es(salesOrderDO.getPayerNum());
        //Head
        SalesDocumentRequestVO.Head head = new SalesDocumentRequestVO.Head();
        head.setSales_org(salesOrderDO.getSaleOrgzCd());//销售组织
        head.setDistr_chan(salesOrderDO.getSaleAcsCdg());//销售渠道
        head.setDivision(salesOrderDO.getPdtGrpCdg());//产品组编码
        head.setReq_date_h(salesOrderDO.getVoucherDate().format(DateTimeFormatter.ofPattern("yyyyMMdd")));//凭证日期
        //item
        List<SalesDocumentRequestVO.Item> items = new ArrayList<>();
        salesOrderDetailList.forEach(salesOrderDetail -> {
            MaterialInfomationPageReqDTO infomationPageReqDTO = new MaterialInfomationPageReqDTO();
            infomationPageReqDTO.setPageSize(10000);
            infomationPageReqDTO.setCode(salesOrderDetail.getMaterialNumber());
            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);
            }
            SalesDocumentRequestVO.Item item = getItem(salesOrderDetail, mtrlZhongtongCode);
            items.add(item);
        });
        List<String> conds = new ArrayList<>();
        salesOrderDetailList.forEach(salesOrderDetailRespVO -> {
            String priceConditionDetail = salesOrderDetailRespVO.getPriceConditionDetail();
            if (priceConditionDetail == null || priceConditionDetail.trim().isEmpty()) {
                return; // 空字符串直接跳过
            }
            try {
                List<String> strList = new ArrayList<>();
                // 解析 JSON 数组
                List<JSONArray> jsonArrays = JSONArray.parseArray(priceConditionDetail, JSONArray.class);
                if (salesOrderDetailRespVO.getId() != null) {
                    for (JSONArray jsonArray : jsonArrays) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            // 解析单个JSON字符串为JSONObject
                            JSONObject jsonObject = JSONObject.parseObject(jsonArray.getString(i));
                            // 添加updateflag字段
                            jsonObject.put("updateflag", ErpConstants.SALES_DOCUMENT_REQUEST_FLAG_I);
                            // 将处理后的JSON对象转为字符串并加入strList
                            String processedJson = jsonObject.toString();
                            strList.add(processedJson);
                        }
                    }
                } else {
                    for (JSONArray jsonArray : jsonArrays) {
                        for (int i = 0; i < jsonArray.size(); i++) {
                            // 解析单个JSON字符串为JSONObject
                            JSONObject jsonObject = JSONObject.parseObject(jsonArray.getString(i));
                            // 添加updateflag字段
                            if (ErpConstants.SALES_DOCUMENT_REQUEST_FLAG_D.equals(jsonObject.get("flag"))) {
                                jsonObject.put("updateflag", ErpConstants.SALES_DOCUMENT_REQUEST_FLAG_D);
                            }
                            // 移除flag字段
                            jsonObject.remove("flag");
                            // 将处理后的JSON对象转为字符串并加入strList
                            String processedJson = jsonObject.toString();
                            strList.add(processedJson);
                        }
                    }
                }
                // 将处理后的JSON字符串列表合并到conds
                conds.addAll(strList);
            } catch (JSONException e) {
                // 处理解析失败（例如打日志、忽略错误数据等）
                log.error("解析价格条件详情失败，内容：{}", priceConditionDetail, e);
            }
        });
        salesDocumentRequestVO.setItemList(items);// 设置订单明细列表
        salesDocumentRequestVO.setCondList(conds); // 设置价格条件列表
    }

    private SalesDocumentRequestVO.@NotNull Item getItem(SalesOrderDetailSaveReqVO salesOrderDetail, String mtrlZhongtongCode) {
        String flag = ErpConstants.SALES_DOCUMENT_REQUEST_FLAG_U;
        if (salesOrderDetail.getId() == null) {
            flag = ErpConstants.SALES_DOCUMENT_REQUEST_FLAG_I;
        }
        SalesDocumentRequestVO.Item item = new SalesDocumentRequestVO.Item();
        item.setItm_number(Math.toIntExact(salesOrderDetail.getLineNumber()));
        item.setUpdateflag(flag);//更新标志
        item.setMaterial(mtrlZhongtongCode);//物料号
        item.setPlant(salesOrderDetail.getFactoryNumber());//工厂编码
        item.setStore_loc(salesOrderDetail.getWarehouseNumber());//库存地点
        item.setSales_unit(salesOrderDetail.getUnt());//单位
        //item.setDlvschduse();//开票类型
        item.setTarget_qty(salesOrderDetail.getQuantity()); //目标数量（暂估数量）
        item.setShip_point(salesOrderDetail.getShippingPlace());//装运地点
        return item;
    }

    public WarehouseFactoryRespVO getBoundFactoryAndWarehouse(String factoryCode, String warehouseCode) {
        // 1. 查询主库信息，空值直接抛异常（精准异常信息）
        InternalWarehouseDO internalWarehouseDO = internalWarehouseService.getInternalWarehouseByFactoryCodeAndWarehouseCode(factoryCode, warehouseCode);
        if (internalWarehouseDO == null) {
            throw exception(WAREHOUSE_CODE_OR_FACTORY_CODE_NOT_EXISTS, "工厂编码：" + factoryCode + "，仓库编码：" + warehouseCode + " 不存在关联记录");
        }

        // 2. Stream流式查询+过滤，直接获取符合条件的唯一VO，空值抛异常
        return warehouseFactoryService.getWarehouseFactoryByMainId(String.valueOf(internalWarehouseDO.getId())).stream()
                // 过滤条件：MMSI类型+操作类型匹配ERP常量
                .filter(vo -> ErpConstants.WAREHOUSE_MMSITYPE_SALE.equals(vo.getMmsiType()) && ErpConstants.WAREHOUSE_TYPE_SHIPPING.equals(vo.getOperationType()))
                // 取第一个匹配结果（无结果则抛指定异常）
                .findFirst().orElseThrow(() -> exception(WAREHOUSE_CODE_OR_FACTORY_CODE_NOT_EXISTS, "工厂编码：" + factoryCode + "，仓库编码：" + warehouseCode + " 无符合操作条件的库位"));
    }
}
