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.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.purchaseorder.PurchaseOrderDO;
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.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.service.erp.ErpOrderService;
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.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

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;



    @Override
    @Transactional
    public SalesOrderRespVO createSalesOrder(SalesOrderSaveReqVO createReqVO) {
        // 插入
        SalesOrderDO salesOrderDO = BeanUtils.toBean(createReqVO, SalesOrderDO.class);
        //订单号
        //生成订单号
        if (Objects.equals(createReqVO.getIsPush(), 1)) {
            salesOrderDO.setStatus(OrderStatusEnum.DRAFT.getCode()); //设置初始状态
        } else {
            salesOrderDO.setStatus(OrderStatusEnum.TO_SUBMIT_ERP.getCode());
        }
        String orderNumber = generateOrderNumber(salesOrderDO.getMtrlTp());
        salesOrderDO.setSystemOrderNumber(orderNumber);
        salesOrderMapper.insert(salesOrderDO);
        // 返回
        return BeanUtils.toBean(salesOrderDO, SalesOrderRespVO.class);
    }

    @Override
    @Transactional
    public void updateSalesOrder(SalesOrderSaveReqVO updateReqVO) {
        // 校验存在
        validateSalesOrderExists(updateReqVO.getId());
        // 更新
        SalesOrderDO updateObj = BeanUtils.toBean(updateReqVO, SalesOrderDO.class);
        salesOrderMapper.updateById(updateObj);
    }

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

    @Override
    @Transactional
    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()); // 销售组
        erpSalesOrderSaveReqVO.setHead(head);
        // 销售订单明细
        List<ErpSalesOrderSaveReqVO.Item> items = new ArrayList<>();
        for (SalesOrderDetailRespVO salesOrderDetailRespVO : salesOrderDetailByOrderId) {
            ErpSalesOrderSaveReqVO.Item item = new ErpSalesOrderSaveReqVO.Item();
            item.setItem_categ(String.valueOf(salesOrderDetailRespVO.getLineNumber()));
            item.setMaterial(salesOrderDetailRespVO.getMaterialNumber());
            item.setPlant(salesOrderDetailRespVO.getFactoryNumber());
            item.setStore_loc(salesOrderDetailRespVO.getShippingPlace());
            item.setSales_unit(salesOrderDetailRespVO.getUnit());
            item.setDlvschduse(salesOrderDetailRespVO.getInvoiceType());
            item.setTarget_qty(salesOrderDetailRespVO.getQuantity());
            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);
                conds.addAll(strList);
            } catch (JSONException e) {
                // 处理解析失败（例如打日志、忽略错误数据等）
                log.error("解析价格条件详情失败，内容：{}", priceConditionDetail, e);
            }
        });
        erpSalesOrderSaveReqVO.setConds(conds);
      //  String result = erpOrderService.submitOrderToErp091(erpSalesOrderSaveReqVO);
        String result="3333";
        if (result != null) {
            JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(Map.of("salesdocument",R())));
            String salesdocument = jsonObject.getString("salesdocument");
            if (salesdocument != null) {
                SalesOrderDO upVo = new SalesOrderDO();
                upVo.setId(salesOrderDO.getId());
                upVo.setOrderSAPNumber(salesdocument);
                upVo.setStatus(OrderStatusEnum.IN_PROGRESS.getCode());
                salesOrderMapper.updateById(upVo);
            }

        }
    }

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