package com.fs.erp.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.utils.StringUtils;
import com.fs.erp.constant.AfterSalesOrderStatusEnum;
import com.fs.erp.constant.ErpQueryOrderStatusEnum;
import com.fs.erp.constant.OrderStatusEnum;
import com.fs.erp.constant.TaskStatusEnum;
import com.fs.erp.domain.*;
import com.fs.erp.dto.*;
import com.fs.erp.exception.JstRateLimitException;
import com.fs.erp.http.JstErpHttpService;
import com.fs.erp.mapper.FsJstAftersalePushMapper;
import com.fs.erp.mapper.FsJstAftersalePushScrmMapper;
import com.fs.erp.mapper.FsJstCodPushMapper;
import com.fs.erp.mapper.FsJstCodPushScrmMapper;
import com.fs.erp.service.IErpOrderService;
import com.fs.his.domain.FsStoreOrder;
import com.fs.his.domain.FsStoreOrderItem;
import com.fs.his.domain.FsStoreProduct;
import com.fs.his.mapper.FsStoreAfterSalesMapper;
import com.fs.his.service.IFsStoreOrderItemService;
import com.fs.his.service.IFsStoreOrderService;
import com.fs.his.service.IFsStoreProductService;
import com.fs.hisStore.domain.FsStoreOrderItemScrm;
import com.fs.hisStore.domain.FsStoreOrderScrm;
import com.fs.hisStore.domain.FsStoreProductScrm;
import com.fs.hisStore.service.IFsStoreOrderItemScrmService;
import com.fs.hisStore.service.IFsStoreOrderScrmService;
import com.fs.hisStore.service.IFsStoreProductScrmService;
import com.fs.hisStore.service.impl.FsStoreProductScrmServiceImpl;
import com.fs.hisStore.vo.FsStoreOrderItemVO;
import com.fs.live.domain.LiveOrder;
import com.fs.live.domain.LiveOrderItem;
import com.fs.live.mapper.LiveOrderItemMapper;
import com.fs.live.mapper.LiveOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class JSTErpOrderServiceImpl implements IErpOrderService {
    @Autowired
    private JstErpHttpService jstErpHttpService;

    @Autowired
    private IFsStoreOrderService fsStoreOrderService;

    @Autowired
    private IFsStoreOrderScrmService fsStoreOrderScrmService;

    @Autowired
    private IFsStoreOrderItemService fsStoreOrderItemService;
    @Autowired
    private IFsStoreOrderItemScrmService fsStoreOrderItemScrmService;
    @Autowired
    private IFsStoreProductService fsStoreProductService;

    @Autowired
    private FsJstCodPushMapper fsJstCodPushMapper;

    @Autowired
    private FsJstAftersalePushScrmMapper fsJstAftersalePushScrmMapper;
    @Autowired
    private FsJstCodPushScrmMapper fsJstCodPushScrmMapper;

    @Autowired
    private IFsStoreProductScrmService fsStoreProductScrmService;

    @Autowired
    private LiveOrderMapper liveOrderMapper;

    @Autowired
    private LiveOrderItemMapper liveOrderItemMapper;

    @Autowired
    private RedisCache redisCache;

    // 限流配置：每分钟最多100次请求，超过95次返回429
    private static final int MAX_REQUESTS_PER_MINUTE = 100;
    private static final int RATE_LIMIT_THRESHOLD = 95;
    private static final String RATE_LIMIT_KEY_PREFIX = "jst:query:rate_limit:";

    @Override
    public ErpOrderResponse addOrder(ErpOrder order) {
        FsStoreOrder fsStoreOrder = fsStoreOrderService.selectFsStoreOrderByOrderCode(order.getPlatform_code());
        log.info("ERP订单号: {}, 订单信息: {}",order.getPlatform_code(), JSON.toJSONString(fsStoreOrder));
        ErpOrderPayment erpOrderPayment = order.getPayments().get(0);

        ShopOrderDTO shopOrderDTO = new ShopOrderDTO();

        shopOrderDTO.setShopId(Long.valueOf(order.getShop_code()));
        shopOrderDTO.setSoId(order.getPlatform_code());
        shopOrderDTO.setOrderDate(order.getDeal_datetime());
        // 待发货
        shopOrderDTO.setShopStatus(OrderStatusEnum.WAIT_SELLER_SEND_GOODS.name());
        // 买家账号
        shopOrderDTO.setShopBuyerId(order.getBuyer_account());
        // 收货人省份
        shopOrderDTO.setReceiverState(order.getReceiver_province());
        // 收货人城市
        shopOrderDTO.setReceiverCity(order.getReceiver_city());
        // 收货人区域
        shopOrderDTO.setReceiverDistrict(order.getReceiver_district());
        // 收货人详细地址
        shopOrderDTO.setReceiverAddress(order.getReceiver_address());
        // 收货人详细地址
        shopOrderDTO.setReceiverName(order.getReceiver_name());
        // 收货人电话
        shopOrderDTO.setReceiverPhone(order.getReceiver_mobile());
        // 支付金额
        shopOrderDTO.setPayAmount(erpOrderPayment.getPayment());

        if (ObjectUtil.isNull(fsStoreOrder.getPayDelivery())) {
            shopOrderDTO.setFreight(Double.valueOf("0.00"));
        } else {
            shopOrderDTO.setFreight(fsStoreOrder.getPayDelivery().doubleValue());
        }
        // 备注
        //shopOrderDTO.setRemark(order.getBuyer_memo());
        shopOrderDTO.setRemark(DateUtil.format(new Date(), "dd"));

        // 买家留言
        shopOrderDTO.setBuyerMessage(order.getBuyer_memo());

        // 订单商品项列表
        List<OrderItemDTO> itemDTOList = new ArrayList<>();

        List<FsStoreOrderItem> fsStoreOrderItemVOS = fsStoreOrderItemService.selectFsStoreOrderItemListByOrderId(fsStoreOrder.getOrderId());
        for (FsStoreOrderItem item : fsStoreOrderItemVOS) {
            OrderItemDTO orderItemDTO = new OrderItemDTO();
            JSONObject jsonObject = JSON.parseObject(item.getJsonInfo());

            String barCode = jsonObject.getString("barCode");
            String productName = jsonObject.getString("productName");
            String sku=jsonObject.getString("sku");

            orderItemDTO.setSkuId(barCode);
            orderItemDTO.setShopSkuId(barCode);
            orderItemDTO.setName(productName);
            orderItemDTO.setShopIId(orderItemDTO.getSkuId());//款式编码ID，当前没有这个目前就与SKU ID一致
            orderItemDTO.setPropertiesValue(sku);//商品属性

            FsStoreProduct fsStoreProduct = fsStoreProductService.selectFsStoreProductById(item.getProductId());

            orderItemDTO.setAmount(fsStoreProduct.getPrice().multiply(new BigDecimal(item.getNum())));
            orderItemDTO.setPic(fsStoreProduct.getImgUrl());
            orderItemDTO.setPrice(fsStoreProduct.getPrice());
            orderItemDTO.setQty(item.getNum().intValue());
            orderItemDTO.setOuterOiId(String.format("%s%s",fsStoreOrder.getOrderCode(),item.getItemId()));
            itemDTOList.add(orderItemDTO);
        }
        shopOrderDTO.setItems(itemDTOList);

        // 实际支付金额
        PaymentDTO paymentDTO = new PaymentDTO();
        paymentDTO.setAmount(fsStoreOrder.getPayMoney().doubleValue());
        paymentDTO.setOuterPayId(order.getPlatform_code());
        paymentDTO.setPayDate(order.getDeal_datetime());
        paymentDTO.setPayment("微信支付");
        paymentDTO.setBuyerAccount(order.getBuyer_account());
        paymentDTO.setSellerAccount("平台销售");
        shopOrderDTO.setPay(paymentDTO);


        // 如果是货到付款
        if(fsStoreOrder.getPayType() == 2 || fsStoreOrder.getPayType() == 3){
            shopOrderDTO.setIsCod(true);
            // 货到付款金额 = 物流代收金额-优惠金额
            shopOrderDTO.setBuyerPaidAmount(fsStoreOrder.getPayDelivery());
            shopOrderDTO.setPayAmount(fsStoreOrder.getPayRemain().doubleValue());

            // 货到付款要推两次
            PaymentDTO paymentDTO2 = new PaymentDTO();
            // 物流代收金额
            paymentDTO2.setAmount(fsStoreOrder.getPayRemain().doubleValue());
            paymentDTO2.setOuterPayId(String.format("%s%d",order.getPlatform_code(),1));
            paymentDTO2.setPayDate(order.getDeal_datetime());
            paymentDTO2.setPayment("货到付款");
            paymentDTO2.setBuyerAccount(order.getBuyer_account());
            paymentDTO2.setSellerAccount("平台销售");
            shopOrderDTO.setPay(paymentDTO2);

            FsJstCodPush fsJstCodPush = new FsJstCodPush();
            fsJstCodPush.setOrderId(fsStoreOrder.getOrderCode());
            fsJstCodPush.setType("0");
            fsJstCodPush.setParams(JSON.toJSONString(shopOrderDTO));
            fsJstCodPush.setRetryCount(0);
            fsJstCodPush.setTaskStatus(TaskStatusEnum.PENDING.getCode());
            fsJstCodPushMapper.insert(fsJstCodPush);

        }

        ErpOrderResponseDTO upload = jstErpHttpService.upload(shopOrderDTO);

        if(CollectionUtils.isEmpty(upload.getDatas())) {
            log.info("推送ERP返回结果: {}",upload);
            throw new IllegalArgumentException("推送ERP返回数不应该为0");
        }
        ErpOrderResponseDTO.OrderData orderData = upload.getDatas().get(0);

        ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
        erpOrderResponse.setSuccess(true);
        erpOrderResponse.setCode(String.valueOf(orderData.getOId()));
        return erpOrderResponse;
    }

    @Override
    public ErpOrderResponse addOrderScrm(ErpOrder order) {
        FsStoreOrderScrm fsStoreOrder = fsStoreOrderScrmService.selectFsStoreOrderByOrderCode(order.getPlatform_code());
        log.info("ERP订单号: {}, 订单信息: {}",order.getPlatform_code(), JSON.toJSONString(fsStoreOrder));

        ErpOrderPayment erpOrderPayment = order.getPayments().get(0);

        ShopOrderDTO shopOrderDTO = new ShopOrderDTO();

        shopOrderDTO.setShopId(Long.valueOf(order.getShop_code()));
        shopOrderDTO.setSoId(order.getPlatform_code());
        shopOrderDTO.setOrderDate(order.getDeal_datetime());
        // 待发货
        shopOrderDTO.setShopStatus(OrderStatusEnum.WAIT_SELLER_SEND_GOODS.name());
        // 买家账号
        shopOrderDTO.setShopBuyerId(order.getBuyer_account());
        // 收货人省份
        shopOrderDTO.setReceiverState(order.getReceiver_province());
        // 收货人城市
        shopOrderDTO.setReceiverCity(order.getReceiver_city());
        // 收货人区域
        shopOrderDTO.setReceiverDistrict(order.getReceiver_district());
        // 收货人详细地址
        shopOrderDTO.setReceiverAddress(order.getReceiver_address());
        // 收货人详细地址
        shopOrderDTO.setReceiverName(order.getReceiver_name());
        // 收货人电话
        shopOrderDTO.setReceiverPhone(order.getReceiver_mobile());
        // 支付金额
        shopOrderDTO.setPayAmount(erpOrderPayment.getPayment());
        // 运费 改
        if (ObjectUtil.isNull(fsStoreOrder.getPayDelivery())) {
            shopOrderDTO.setFreight(Double.valueOf("0.00"));
        } else {
            shopOrderDTO.setFreight(fsStoreOrder.getPayDelivery().doubleValue());
        }
        // 备注
        //shopOrderDTO.setRemark(order.getBuyer_memo());
        shopOrderDTO.setRemark(DateUtil.format(new Date(), "dd"));
        // 买家留言
        shopOrderDTO.setBuyerMessage(order.getBuyer_memo());

        // 订单商品项列表
        List<OrderItemDTO> itemDTOList = new ArrayList<>();

        List<FsStoreOrderItemVO> fsStoreOrderItemVOS = fsStoreOrderItemScrmService.selectFsStoreOrderItemListByOrderId(fsStoreOrder.getId());
        log.info("fsStoreOrderItemVOS==========>{}",fsStoreOrderItemVOS);
        for (FsStoreOrderItemVO item : fsStoreOrderItemVOS) {
            OrderItemDTO orderItemDTO = new OrderItemDTO();
            JSONObject jsonObject = JSON.parseObject(item.getJsonInfo());

            String barCode = jsonObject.getString("barCode");
            String productName = jsonObject.getString("productName");
            String sku=jsonObject.getString("sku");

            orderItemDTO.setSkuId(barCode);
            orderItemDTO.setShopSkuId(barCode);
            orderItemDTO.setName(productName);
            orderItemDTO.setShopIId(orderItemDTO.getSkuId());//款式编码ID，当前没有这个目前就与SKU ID一致
            orderItemDTO.setPropertiesValue(sku);//商品属性

            FsStoreProductScrm fsStoreProduct = fsStoreProductScrmService.selectFsStoreProductById(item.getProductId());

            orderItemDTO.setAmount(fsStoreProduct.getPrice().multiply(new BigDecimal(item.getNum())));
            orderItemDTO.setPic(fsStoreProduct.getImage());
            orderItemDTO.setPrice(fsStoreProduct.getPrice());
            orderItemDTO.setQty(item.getNum().intValue());
            orderItemDTO.setOuterOiId(String.format("%s%s",fsStoreOrder.getOrderCode(),item.getItemId()));
            itemDTOList.add(orderItemDTO);
        }
        shopOrderDTO.setItems(itemDTOList);

        // 实际支付金额
        PaymentDTO paymentDTO = new PaymentDTO();
        paymentDTO.setAmount(fsStoreOrder.getPayMoney().doubleValue());
        paymentDTO.setOuterPayId(order.getPlatform_code());
        paymentDTO.setPayDate(order.getDeal_datetime());
        paymentDTO.setPayment("微信支付");
        paymentDTO.setBuyerAccount(order.getBuyer_account());
        paymentDTO.setSellerAccount("平台销售");
        shopOrderDTO.setPay(paymentDTO);

        // 如果是货到付款
        if("2".equals(fsStoreOrder.getPayType()) || "3".equals(fsStoreOrder.getPayType())){
            shopOrderDTO.setIsCod(true);
            // 货到付款金额 = 物流代收金额-优惠金额
            //注释掉总买家实付
            //shopOrderDTO.setBuyerPaidAmount(fsStoreOrder.getPayDelivery());
            //应付金额(货到付款= 订单总金额 - 已付金额)
            shopOrderDTO.setPayAmount(fsStoreOrder.getTotalPrice().subtract(fsStoreOrder.getPayPrice()).doubleValue());

            // 货到付款要推两次
            PaymentDTO paymentDTO2 = new PaymentDTO();
            // 物流代收金额
            paymentDTO2.setAmount(fsStoreOrder.getTotalPrice().subtract(fsStoreOrder.getPayPrice()).doubleValue());
            paymentDTO2.setOuterPayId(String.format("%s%d",order.getPlatform_code(),1));
            paymentDTO2.setPayDate(order.getDeal_datetime());
            paymentDTO2.setPayment("货到付款");
            paymentDTO2.setBuyerAccount(order.getBuyer_account());
            paymentDTO2.setSellerAccount("平台销售");
            shopOrderDTO.setPay(paymentDTO2);

            FsJstCodPush fsJstCodPush = new FsJstCodPush();
            fsJstCodPush.setOrderId(fsStoreOrder.getOrderCode());
            fsJstCodPush.setType("0");
            fsJstCodPush.setParams(JSON.toJSONString(shopOrderDTO));
            fsJstCodPush.setRetryCount(0);
            fsJstCodPush.setTaskStatus(TaskStatusEnum.PENDING.getCode());
            fsJstCodPushScrmMapper.insert(fsJstCodPush);

            //shopOrderDTO.setPay(paymentDTO);
        }

        ErpOrderResponseDTO upload = jstErpHttpService.upload(shopOrderDTO);

        if(CollectionUtils.isEmpty(upload.getDatas())) {
            log.info("推送ERP返回结果: {}",upload);
            throw new IllegalArgumentException("推送ERP返回数不应该为0");
        }
        ErpOrderResponseDTO.OrderData orderData = upload.getDatas().get(0);

        ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
        erpOrderResponse.setSuccess(true);
        erpOrderResponse.setCode(String.valueOf(orderData.getOId()));
        return erpOrderResponse;
    }

    @Override
    public ErpOrderResponse addLiveOrder(ErpOrder order) {
        LiveOrder liveOrder = liveOrderMapper.selectLiveOrderByOrderCode(order.getPlatform_code());
        log.info("ERP订单号: {}, 订单信息: {}",order.getPlatform_code(), JSON.toJSONString(liveOrder));

        ErpOrderPayment erpOrderPayment = order.getPayments().get(0);

        ShopOrderDTO shopOrderDTO = new ShopOrderDTO();

        shopOrderDTO.setShopId(Long.valueOf(order.getShop_code()));
        shopOrderDTO.setSoId(order.getPlatform_code());
        shopOrderDTO.setOrderDate(order.getDeal_datetime());
        // 待发货
        shopOrderDTO.setShopStatus(OrderStatusEnum.WAIT_SELLER_SEND_GOODS.name());
        // 买家账号
        shopOrderDTO.setShopBuyerId(order.getBuyer_account());
        // 收货人省份
        shopOrderDTO.setReceiverState(order.getReceiver_province());
        // 收货人城市
        shopOrderDTO.setReceiverCity(order.getReceiver_city());
        // 收货人区域
        shopOrderDTO.setReceiverDistrict(order.getReceiver_district());
        // 收货人详细地址
        shopOrderDTO.setReceiverAddress(order.getReceiver_address());
        // 收货人详细地址
        shopOrderDTO.setReceiverName(order.getReceiver_name());
        // 收货人电话
        shopOrderDTO.setReceiverPhone(order.getReceiver_mobile());
        // 支付金额
        shopOrderDTO.setPayAmount(erpOrderPayment.getPayment());
        // 运费 改
        if (ObjectUtil.isNull(liveOrder.getPayDelivery())) {
            shopOrderDTO.setFreight(Double.valueOf("0.00"));
        } else {
            shopOrderDTO.setFreight(liveOrder.getPayDelivery().doubleValue());
        }
        // 备注
        shopOrderDTO.setRemark(DateUtil.format(new Date(), "dd"));
        // 买家留言
        shopOrderDTO.setBuyerMessage(order.getBuyer_memo());

        // 订单商品项列表
        List<OrderItemDTO> itemDTOList = new ArrayList<>();

        List<LiveOrderItem> liveOrderItems = liveOrderItemMapper.selectLiveOrderItemByOrderId(liveOrder.getOrderId());
        log.info("liveOrderItems==========>{}",liveOrderItems);
        for (LiveOrderItem item : liveOrderItems) {
            OrderItemDTO orderItemDTO = new OrderItemDTO();
            JSONObject jsonObject = JSON.parseObject(item.getJsonInfo());

            String barCode = jsonObject.getString("barCode");
            String productName = jsonObject.getString("productName");
            String sku=jsonObject.getString("sku");

            orderItemDTO.setSkuId(barCode);
            orderItemDTO.setShopSkuId(barCode);
            orderItemDTO.setName(productName);
            orderItemDTO.setShopIId(orderItemDTO.getSkuId());//款式编码ID，当前没有这个目前就与SKU ID一致
            orderItemDTO.setPropertiesValue(sku);//商品属性

            FsStoreProductScrm fsStoreProduct = fsStoreProductScrmService.selectFsStoreProductById(item.getProductId());

            orderItemDTO.setAmount(fsStoreProduct.getPrice().multiply(new BigDecimal(item.getNum())));
            orderItemDTO.setPic(fsStoreProduct.getImage());
            orderItemDTO.setPrice(fsStoreProduct.getPrice());
            orderItemDTO.setQty(item.getNum().intValue());
            orderItemDTO.setOuterOiId(String.format("%s%s",liveOrder.getOrderCode(),item.getItemId()));
            itemDTOList.add(orderItemDTO);
        }
        shopOrderDTO.setItems(itemDTOList);

        // 实际支付金额
        PaymentDTO paymentDTO = new PaymentDTO();
        paymentDTO.setAmount(liveOrder.getPayMoney().doubleValue());
        paymentDTO.setOuterPayId(order.getPlatform_code());
        paymentDTO.setPayDate(order.getDeal_datetime());
        paymentDTO.setPayment("微信支付");
        paymentDTO.setBuyerAccount(order.getBuyer_account());
        paymentDTO.setSellerAccount("平台销售");
        shopOrderDTO.setPay(paymentDTO);

        // 如果是货到付款
        if("2".equals(liveOrder.getPayType()) || "3".equals(liveOrder.getPayType())){
            shopOrderDTO.setIsCod(true);
            // 货到付款金额 = 物流代收金额-优惠金额
            //应付金额(货到付款= 订单总金额 - 已付金额)
            shopOrderDTO.setPayAmount(liveOrder.getTotalPrice().subtract(liveOrder.getPayPrice()).doubleValue());

            // 货到付款要推两次
            PaymentDTO paymentDTO2 = new PaymentDTO();
            // 物流代收金额
            paymentDTO2.setAmount(liveOrder.getTotalPrice().subtract(liveOrder.getPayPrice()).doubleValue());
            paymentDTO2.setOuterPayId(String.format("%s%d",order.getPlatform_code(),1));
            paymentDTO2.setPayDate(order.getDeal_datetime());
            paymentDTO2.setPayment("货到付款");
            paymentDTO2.setBuyerAccount(order.getBuyer_account());
            paymentDTO2.setSellerAccount("平台销售");
            shopOrderDTO.setPay(paymentDTO2);

            FsJstCodPush fsJstCodPush = new FsJstCodPush();
            fsJstCodPush.setOrderId(liveOrder.getOrderCode());
            fsJstCodPush.setType("0");
            fsJstCodPush.setParams(JSON.toJSONString(shopOrderDTO));
            fsJstCodPush.setRetryCount(0);
            fsJstCodPush.setTaskStatus(TaskStatusEnum.PENDING.getCode());
            fsJstCodPushScrmMapper.insert(fsJstCodPush);
        }

        ErpOrderResponseDTO upload = jstErpHttpService.upload(shopOrderDTO);

        if(CollectionUtils.isEmpty(upload.getDatas())) {
            log.info("推送ERP返回结果: {}",upload);
            throw new IllegalArgumentException("推送ERP返回数不应该为0");
        }
        ErpOrderResponseDTO.OrderData orderData = upload.getDatas().get(0);

        ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
        erpOrderResponse.setSuccess(true);
        erpOrderResponse.setCode(String.valueOf(orderData.getOId()));
        return erpOrderResponse;
    }

    @Override
    public ErpOrderResponse refundOrder(ErpRefundOrder order) {
        return null;
    }

    @Override
    public ErpOrderResponse refundOrderScrm(ErpRefundOrder order) {
        return null;
    }

    @Override
    public ErpOrderResponse refundLiveOrder(ErpRefundOrder order) {
        return null;
    }

    @Override
    public ErpDeliverysResponse getDeliver(ErpDeliverysRequest param) {
        return null;
    }

    @Override
    public ErpOrderQueryResponse getOrder(ErpOrderQueryRequert param) {
        // 1. 构建查询请求DTO
        OrderQueryRequestDTO requestDTO = new OrderQueryRequestDTO();
        requestDTO.setOIds(Collections.singletonList(Long.valueOf(param.getCode())));


        // 2. 调用ERP服务查询订单
        OrderQueryResponseDTO query = jstErpHttpService.query(requestDTO);

        // 3. 构建响应对象
        ErpOrderQueryResponse response = new ErpOrderQueryResponse();

        // 4. 设置基本响应信息

        // 5. 转换订单数据
        if (query.getOrders() != null && !query.getOrders().isEmpty()) {
            List<ErpOrderQuery> erpOrders = query.getOrders().stream()
                    .map(this::convertToErpOrderQuery)
                    .collect(Collectors.toList());

            response.setOrders(erpOrders);
        } else {
            response.setOrders(Collections.emptyList());
        }

        return response;
    }


    @Override
    public ErpOrderQueryResponse getScrmOrder(ErpOrderQueryRequert param) {
        // 1. 构建查询请求DTO
        OrderQueryRequestDTO requestDTO = new OrderQueryRequestDTO();
        requestDTO.setOIds(Collections.singletonList(Long.valueOf(param.getCode())));

        // 3. 构建响应对象
        ErpOrderQueryResponse response = new ErpOrderQueryResponse();

        // 2. 调用ERP服务查询订单
        OrderQueryResponseDTO query = jstErpHttpService.query(requestDTO);


        // 4. 设置基本响应信息

        // 5. 转换订单数据
        if (query.getOrders() != null && !query.getOrders().isEmpty()) {
            List<ErpOrderQuery> erpOrders = query.getOrders().stream()
                    .map(this::convertToErpOrderQueryScrm)
                    .collect(Collectors.toList());
            response.setOrders(erpOrders);
        } else {
            response.setOrders(Collections.emptyList());
        }
        response.setSuccess(true);
        return response;
    }

    @Override
    public ErpOrderQueryResponse getLiveOrder(ErpOrderQueryRequert param) {


        // 3. 构建响应对象
        ErpOrderQueryResponse response = new ErpOrderQueryResponse();

        // 1. 构建查询请求DTO
        OrderQueryRequestDTO requestDTO = new OrderQueryRequestDTO();
        requestDTO.setOIds(Collections.singletonList(Long.valueOf(param.getCode())));
        requestDTO.setOrderItemFlds(Arrays.asList("status"));

        // 2. 调用ERP服务查询订单
        OrderQueryResponseDTO query = jstErpHttpService.query(requestDTO);

        // 4. 设置基本响应信息

        // 5. 转换订单数据
        if (query.getOrders() != null && !query.getOrders().isEmpty()) {
            OrderQueryResponseDTO.Order firstOrder = query.getOrders().get(0);

            // 如果订单状态是拆分，重新查询聚水潭获取所有拆分订单
            if ("Split".equals(firstOrder.getStatus())) {
                // 处理拆分订单逻辑
//                this.splitLiveOrder(firstOrder);

                // 使用订单号（soId）重新查询聚水潭，获取所有相关订单
                OrderQueryRequestDTO splitRequestDTO = new OrderQueryRequestDTO();
                splitRequestDTO.setSoIds(Collections.singletonList(firstOrder.getSoId()));
                splitRequestDTO.setOrderItemFlds(Arrays.asList("status"));

                // 重新查询聚水潭
                OrderQueryResponseDTO splitQuery = jstErpHttpService.query(splitRequestDTO);

                if (splitQuery != null && splitQuery.getOrders() != null && !splitQuery.getOrders().isEmpty()) {
                    // 查找状态不为拆分并且已发货的订单
                    OrderQueryResponseDTO.Order sentOrder = splitQuery.getOrders().stream()
                            .filter(order -> !"Split".equals(order.getStatus())
                                    && ErpQueryOrderStatusEnum.SENT.getCode().equals(order.getStatus()))
                            .findFirst()
                            .orElse(null);

                    if (sentOrder != null) {
                        // 找到符合条件的订单，转换状态并设置到响应中
                        ErpOrderQuery erpOrder = convertToErpOrderQueryLive(sentOrder);
                        response.setOrders(Collections.singletonList(erpOrder));
                        log.info("拆分订单查询：找到已发货订单，orderCode: {}, status: {}",
                                sentOrder.getSoId(), sentOrder.getStatus());
                    } else {
                        // 如果没有找到已发货的订单，返回空列表
                        log.warn("拆分订单查询：未找到已发货的非拆分订单，orderCode: {}", firstOrder.getSoId());
                        response.setOrders(Collections.emptyList());
                    }
                } else {
                    // 重新查询失败，返回空列表
                    log.error("拆分订单查询：重新查询聚水潭失败，orderCode: {}", firstOrder.getSoId());
                    response.setOrders(Collections.emptyList());
                }
            } else {
                // 非拆分订单，正常转换
                List<ErpOrderQuery> erpOrders = query.getOrders().stream()
                        .map(this::convertToErpOrderQueryLive)
                        .collect(Collectors.toList());
                response.setOrders(erpOrders);
            }
        } else {
            response.setOrders(Collections.emptyList());
        }

        return response;
    }

    private void splitLiveOrder(OrderQueryResponseDTO.Order order) {
        // ① 首先查询原来的订单
        LiveOrder liveOrder = liveOrderMapper.selectLiveOrderByOrderCode(order.getSoId());
        if (liveOrder == null) {
            log.error("直播拆分订单：未查询到数据,{}", order.getSoId());
            return;
        }

        try {
            // ② 重新组装请求，使用 OrderQueryRequestDTO 查询拆分订单
            OrderQueryRequestDTO requestDTO = new OrderQueryRequestDTO();
            requestDTO.setOrderItemFlds(Arrays.asList("status"));
            requestDTO.setSoIds(Collections.singletonList(order.getSoId()));

            // 调用ERP服务查询拆分订单
            OrderQueryResponseDTO query = jstErpHttpService.query(requestDTO);

            if (query == null || query.getOrders() == null || query.getOrders().isEmpty()) {
                log.error("直播拆分订单：查询拆分订单失败, orderCode={}", order.getSoId());
                return;
            }

            // ③ 把原来的订单状态修改为 6（被拆分）
//            liveOrder.setStatus(6);
//            liveOrderMapper.updateLiveOrder(liveOrder);
            log.info("直播拆分订单：原订单状态已更新为被拆分, orderCode={}, orderId={}", order.getSoId(), liveOrder.getOrderId());

            // ④ 查询出来的订单里面，除了原来的订单，将查询出来的订单新增到数据库里面
            for (OrderQueryResponseDTO.Order splitOrder : query.getOrders()) {
                // 跳过原来的订单（状态为 Split 的订单）
                if ("Split".equals(splitOrder.getStatus())) {
                    continue;
                }

                // 检查是否已经存在该拆分订单
                LiveOrder existingOrder = liveOrderMapper.selectLiveOrderByOrderCode(splitOrder.getSoId());
                if (existingOrder != null) {
                    log.info("直播拆分订单：拆分订单已存在，跳过, orderCode={}", splitOrder.getSoId());
                    continue;
                }

                // 创建新的拆分订单
                LiveOrder newOrder = new LiveOrder();
                // 复制原订单的基本信息
                newOrder.setLiveId(liveOrder.getLiveId());
                newOrder.setStoreId(liveOrder.getStoreId());
                newOrder.setOrderCode(splitOrder.getSoId()); // 保存订单ID（soId）
                newOrder.setUserId(liveOrder.getUserId()); // buyerId -> userId
                newOrder.setUserName(liveOrder.getUserName());
                newOrder.setRealName(liveOrder.getRealName());
                newOrder.setUserPhone(liveOrder.getUserPhone());
                newOrder.setUserAddress(liveOrder.getUserAddress());
                newOrder.setCompanyId(liveOrder.getCompanyId());
                newOrder.setCompanyUserId(liveOrder.getCompanyUserId());

                // 设置支付金额
                if (splitOrder.getPayAmount() != null) {
                    newOrder.setPayMoney(splitOrder.getPayAmount());
                    newOrder.setPayPrice(splitOrder.getPayAmount());
                }

                // 根据订单状态枚举设置状态
                ErpQueryOrderStatusEnum statusEnum = ErpQueryOrderStatusEnum.getByCode(splitOrder.getStatus());
                if (statusEnum != null) {
                    // 根据状态类型设置订单状态
                    // WaitPay -> 1 (待支付)
                    // Sent -> 3 (待收货)
                    // Cancelled -> 0 (已取消)
                    // 其他状态根据业务需求设置
                    if ("WaitPay".equals(splitOrder.getStatus())) {
                        newOrder.setStatus(1); // 待支付
                    } else if ("Sent".equals(splitOrder.getStatus())) {
                        newOrder.setStatus(3); // 待收货
                    } else if ("Cancelled".equals(splitOrder.getStatus())) {
//                        newOrder.setStatus(0); // 已取消
                    } else {
                        newOrder.setStatus(2); // 默认待发货
                    }
                } else {
                    newOrder.setStatus(2); // 默认待发货
                }

                // 设置物流信息
                if (StringUtils.isNotEmpty(splitOrder.getLogisticsCompany())) {
                    newOrder.setDeliveryName(splitOrder.getLogisticsCompany());
                }
                if (StringUtils.isNotEmpty(splitOrder.getLId())) {
                    newOrder.setDeliverySn(splitOrder.getLId());
                }
                if (StringUtils.isNotEmpty(splitOrder.getLcId())) {
                    newOrder.setDeliveryCode(splitOrder.getLcId());
                }

                // 设置发货时间
                if (StringUtils.isNotEmpty(splitOrder.getSendDate())) {
                    try {
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date sendDate = formatter.parse(splitOrder.getSendDate());
                        newOrder.setDeliverySendTime(sendDate);
                        newOrder.setDeliveryTime(splitOrder.getSendDate());
                    } catch (Exception e) {
                        log.error("解析发货时间失败: {}", splitOrder.getSendDate(), e);
                    }
                }

                // 设置支付时间
                if (StringUtils.isNotEmpty(splitOrder.getPayDate())) {
                    try {
                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        Date payDate = formatter.parse(splitOrder.getPayDate());
                        newOrder.setPayTime(payDate.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDateTime());
                    } catch (Exception e) {
                        log.error("解析支付时间失败: {}", splitOrder.getPayDate(), e);
                    }
                }

                // 设置扩展订单ID
                newOrder.setExtendOrderId(String.valueOf(splitOrder.getOId()));

                // 计算订单总数量
                if (splitOrder.getItems() != null && !splitOrder.getItems().isEmpty()) {
                    int totalQty = splitOrder.getItems().stream()
                            .mapToInt(OrderQueryResponseDTO.OrderItem::getQty)
                            .sum();
                    newOrder.setTotalNum(String.valueOf(totalQty));
                }

                // 设置订单总价
                if (splitOrder.getAmount() != null) {
                    newOrder.setTotalPrice(splitOrder.getAmount());
                }

                // 设置创建时间和更新时间
                newOrder.setCreateTime(new Date());
                newOrder.setUpdateTime(new Date());

                // 插入订单
                liveOrderMapper.insertLiveOrder(newOrder);

                // 保存订单项（SKU）
                if (splitOrder.getItems() != null && !splitOrder.getItems().isEmpty()) {
                    for (OrderQueryResponseDTO.OrderItem item : splitOrder.getItems()) {
                        LiveOrderItem orderItem = new LiveOrderItem();
                        orderItem.setOrderId(newOrder.getOrderId());
                        orderItem.setOrderCode(splitOrder.getSoId());
                        orderItem.setNum(item.getQty() != null ? item.getQty().longValue() : 0L);
                        // 可以根据需要设置其他字段，如 productId, goodsId 等
                        // 这里需要根据业务逻辑从 item 中获取或从原订单项中复制
                        liveOrderItemMapper.insertLiveOrderItem(orderItem);
                    }
                }
            }

        } catch (Exception e) {
            log.error("直播拆分订单处理异常, orderCode={}", order.getSoId(), e);
        }
    }

    /**
     * 将OrderQueryResponseDTO.Order转换为ErpOrderQuery
     *
     * @param order 订单数据
     * @return ErpOrderQuery 转换后的订单数据
     */
    private ErpOrderQuery convertToErpOrderQuery(OrderQueryResponseDTO.Order order) {
        ErpOrderQuery erpOrder = new ErpOrderQuery();

        FsStoreOrder fsStoreOrder = fsStoreOrderService.selectFsStoreOrderByOrderCode(order.getSoId());
        Asserts.notNull(fsStoreOrder,"该订单号没有找到！");

        // 设置基本订单信息
        erpOrder.setCode(order.getSoId());

        // 计算订单总数量
        if (order.getItems() != null && !order.getItems().isEmpty()) {
            int totalQty = order.getItems().stream()
                    .mapToInt(OrderQueryResponseDTO.OrderItem::getQty)
                    .sum();
            erpOrder.setQty(totalQty);
        }

        // 设置金额相关信息
        erpOrder.setAmount(order.getAmount() != null ? order.getAmount().doubleValue() : null);
        erpOrder.setPayment(order.getPaidAmount() != null ? order.getPaidAmount().doubleValue() : null);

        // 设置其他订单属性
        erpOrder.setCod(order.getIsCod());
        erpOrder.setPlatform_code(order.getOrderFrom());

        // 尝试解析创建时间
        try {
            if (order.getCreated() != null) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                erpOrder.setCreatetime(formatter.parse(order.getCreated()));
            }
        } catch (Exception e) {
            // 日期解析异常处理
            // 可以记录日志或保持为null
        }

        // 设置店铺信息
        erpOrder.setShop_name(order.getShopName());
        erpOrder.setShop_code(String.valueOf(order.getShopId()));

        // 设置物流信息
        erpOrder.setExpress_name(order.getLogisticsCompany());
        erpOrder.setExpress_code(order.getLId());

        // 设置收件人信息
//        erpOrder.setReceiver_name(fsStoreOrder.getRealName());
        erpOrder.setReceiver_name(fsStoreOrder.getUserName());
        erpOrder.setReceiver_phone(fsStoreOrder.getUserPhone());
        erpOrder.setReceiver_mobile(fsStoreOrder.getUserPhone());

        // 构建完整地址
        erpOrder.setReceiver_address(fsStoreOrder.getUserAddress());

        // 如果是已发货
        if(ObjectUtil.equal(order.getStatus(), ErpQueryOrderStatusEnum.SENT.getCode())){
            List<ErpDeliverys> deliverysList = new ArrayList<>();

            ErpDeliverys delivery = new ErpDeliverys();
            delivery.setMail_no(order.getLId());
            delivery.setExpress_code(order.getLcId());
            delivery.setExpress_name(order.getLogisticsCompany());
            delivery.setDelivery(true);
            delivery.setCode(order.getSoId());

            deliverysList.add(delivery);
            erpOrder.setDeliverys(deliverysList);

            // 设置发货状态，假设有物流单号就是已发货状态
            erpOrder.setDelivery_state(1);
        } else {
            erpOrder.setDelivery_state(0);
        }

        return erpOrder;
    }



    private ErpOrderQuery convertToErpOrderQueryScrm(OrderQueryResponseDTO.Order order) {
        ErpOrderQuery erpOrder = new ErpOrderQuery();

        FsStoreOrderScrm fsStoreOrder = fsStoreOrderService.selectFsStoreOrderScrmByOrderCode(order.getSoId());
        Asserts.notNull(fsStoreOrder,"该订单号没有找到！");

        // 设置基本订单信息
        erpOrder.setCode(order.getSoId());

        // 计算订单总数量
        if (order.getItems() != null && !order.getItems().isEmpty()) {
            int totalQty = order.getItems().stream()
                    .mapToInt(OrderQueryResponseDTO.OrderItem::getQty)
                    .sum();
            erpOrder.setQty(totalQty);
        }

        // 设置金额相关信息
        erpOrder.setAmount(order.getAmount() != null ? order.getAmount().doubleValue() : null);
        erpOrder.setPayment(order.getPaidAmount() != null ? order.getPaidAmount().doubleValue() : null);

        // 设置其他订单属性
        erpOrder.setCod(order.getIsCod());
        erpOrder.setPlatform_code(order.getOrderFrom());

        // 尝试解析创建时间
        try {
            if (order.getCreated() != null) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                erpOrder.setCreatetime(formatter.parse(order.getCreated()));
            }
        } catch (Exception e) {
            // 日期解析异常处理
            // 可以记录日志或保持为null
        }

        // 设置店铺信息
        erpOrder.setShop_name(order.getShopName());
        erpOrder.setShop_code(String.valueOf(order.getShopId()));

        // 设置物流信息
        erpOrder.setExpress_name(order.getLogisticsCompany());
        erpOrder.setExpress_code(order.getLId());

        // 设置收件人信息
//        erpOrder.setReceiver_name(fsStoreOrder.getRealName());
        erpOrder.setReceiver_name(fsStoreOrder.getRealName());
        erpOrder.setReceiver_phone(fsStoreOrder.getUserPhone());
        erpOrder.setReceiver_mobile(fsStoreOrder.getUserPhone());

        // 构建完整地址
        erpOrder.setReceiver_address(fsStoreOrder.getUserAddress());

        // 如果是已发货
        if(ObjectUtil.equal(order.getStatus(), ErpQueryOrderStatusEnum.SENT.getCode())){
            List<ErpDeliverys> deliverysList = new ArrayList<>();

            ErpDeliverys delivery = new ErpDeliverys();
            delivery.setMail_no(order.getLId());
            delivery.setExpress_code(order.getLcId());
            delivery.setExpress_name(order.getLogisticsCompany());
            delivery.setDelivery(true);
            delivery.setCode(order.getSoId());

            deliverysList.add(delivery);
            erpOrder.setDeliverys(deliverysList);

            // 设置发货状态，假设有物流单号就是已发货状态
            erpOrder.setDelivery_state(1);
        } else {
            erpOrder.setDelivery_state(0);
        }

        return erpOrder;
    }

    private ErpOrderQuery convertToErpOrderQueryLive(OrderQueryResponseDTO.Order order) {
        ErpOrderQuery erpOrder = new ErpOrderQuery();

        LiveOrder liveOrder = liveOrderMapper.selectLiveOrderByOrderCode(order.getSoId());
        Asserts.notNull(liveOrder,"该订单号没有找到！");

        // 设置基本订单信息
        erpOrder.setCode(order.getSoId());

        // 计算订单总数量
        if (order.getItems() != null && !order.getItems().isEmpty()) {
            int totalQty = order.getItems().stream()
                    .mapToInt(OrderQueryResponseDTO.OrderItem::getQty)
                    .sum();
            erpOrder.setQty(totalQty);
        }
        if (StringUtils.isNotEmpty(order.getStatus()) && "Cancelled".equals(order.getStatus())) {
            erpOrder.setCancle(true);
        }

        // 设置金额相关信息
        erpOrder.setAmount(order.getAmount() != null ? order.getAmount().doubleValue() : null);
        erpOrder.setPayment(order.getPaidAmount() != null ? order.getPaidAmount().doubleValue() : null);

        // 设置其他订单属性
        erpOrder.setCod(order.getIsCod());
        erpOrder.setPlatform_code(order.getOrderFrom());

        // 尝试解析创建时间
        try {
            if (order.getCreated() != null) {
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                erpOrder.setCreatetime(formatter.parse(order.getCreated()));
            }
        } catch (Exception e) {
            // 日期解析异常处理
            // 可以记录日志或保持为null
        }

        // 设置店铺信息
        erpOrder.setShop_name(order.getShopName());
        erpOrder.setShop_code(String.valueOf(order.getShopId()));

        // 设置物流信息
        erpOrder.setExpress_name(order.getLogisticsCompany());
        erpOrder.setExpress_code(order.getLId());

        // 设置收件人信息
        erpOrder.setReceiver_name(liveOrder.getUserName());
        erpOrder.setReceiver_phone(liveOrder.getUserPhone());
        erpOrder.setReceiver_mobile(liveOrder.getUserPhone());

        // 构建完整地址
        erpOrder.setReceiver_address(liveOrder.getUserAddress());

        // 如果是已发货
        if(ObjectUtil.equal(order.getStatus(), ErpQueryOrderStatusEnum.SENT.getCode())){
            List<ErpDeliverys> deliverysList = new ArrayList<>();

            ErpDeliverys delivery = new ErpDeliverys();
            delivery.setMail_no(order.getLId());
            delivery.setExpress_code(order.getLcId());
            delivery.setExpress_name(order.getLogisticsCompany());
            delivery.setDelivery(true);
            delivery.setCode(order.getSoId());

            deliverysList.add(delivery);
            erpOrder.setDeliverys(deliverysList);

            // 设置发货状态，假设有物流单号就是已发货状态
            erpOrder.setDelivery_state(1);
        } else {
            erpOrder.setDelivery_state(0);
        }

        return erpOrder;
    }

    @Override
    public BaseResponse refundUpdate(ErpRefundUpdateRequest param) {

        FsStoreOrder fsStoreOrder = fsStoreOrderService.selectFsStoreOrderByOrderCode(param.getTid());
        // 发货后退款
        if(ObjectUtils.equals(param.getOrderStatus(),2)){
            FsJstAftersalePush fsJstAftersalePush = new FsJstAftersalePush();
            fsJstAftersalePush.setOrderId(fsStoreOrder.getOrderCode());
            fsJstAftersalePush.setTaskStatus(com.fs.hisStore.enums.TaskStatusEnum.PENDING.getCode());
            fsJstAftersalePush.setType(String.valueOf(AfterSalesOrderStatusEnum.WAIT_SELLER_AGREE.getIndex()));
            fsJstAftersalePush.setRetryCount(0);
            fsJstAftersalePush.setAfterSaleId(String.valueOf(param.getStoreAfterSalesId()));
            fsJstAftersalePushMapper.insert(fsJstAftersalePush);

        } else {
            // 如果是发货前退款，直接走取消订单流程
            // 如果是发货后退款，走售后流程
            OrderCancelRequestDTO requestDTO = new OrderCancelRequestDTO();
            requestDTO.setOIds(Collections.singletonList(Integer.valueOf(fsStoreOrder.getExtendOrderId())));
            requestDTO.setCancelType("用户退款");
            requestDTO.setRemark("用户退款");

            jstErpHttpService.cancel(requestDTO);
        }


        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setSuccess(true);

        return baseResponse;
    }

    @Autowired
    private FsJstAftersalePushScrmMapper fsJstAftersalePushMapper;

    @Override
    public BaseResponse refundUpdateScrm(ErpRefundUpdateRequest param) {
        FsStoreOrderScrm fsStoreOrder = fsStoreOrderScrmService.selectFsStoreOrderByOrderCode(param.getTid());
        log.info("订单号: {},发货状态: {},是否发货后: {}",fsStoreOrder.getOrderCode(),fsStoreOrder.getStatus(),ObjectUtils.equals(fsStoreOrder.getStatus(),2));

        // 发货后退款
        if(ObjectUtils.equals(param.getOrderStatus(),2) || ObjectUtils.equals(param.getOrderStatus(),3)){

            FsJstAftersalePush fsJstAftersalePush = new FsJstAftersalePush();
            fsJstAftersalePush.setOrderId(fsStoreOrder.getOrderCode());
            fsJstAftersalePush.setTaskStatus(com.fs.hisStore.enums.TaskStatusEnum.PENDING.getCode());
            fsJstAftersalePush.setType(String.valueOf(AfterSalesOrderStatusEnum.WAIT_SELLER_AGREE.getIndex()));
            fsJstAftersalePush.setRetryCount(0);
            fsJstAftersalePush.setAfterSaleId(String.valueOf(param.getStoreAfterSalesId()));
            fsJstAftersalePushScrmMapper.insert(fsJstAftersalePush);

        } else {
            // 如果是发货前退款，直接走取消订单流程
            // 如果是发货后退款，走售后流程
            OrderCancelRequestDTO requestDTO = new OrderCancelRequestDTO();
            requestDTO.setOIds(Collections.singletonList(Integer.valueOf(fsStoreOrder.getExtendOrderId())));
            requestDTO.setCancelType("用户退款");
            requestDTO.setRemark("用户退款");

            jstErpHttpService.cancel(requestDTO);
        }


        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setSuccess(true);

        return baseResponse;
    }

    @Override
    public BaseResponse refundUpdateLive(ErpRefundUpdateRequest param) {
        LiveOrder liveOrder = liveOrderMapper.selectLiveOrderByOrderCode(param.getTid());
        log.info("订单号: {},发货状态: {},是否发货后: {}",liveOrder.getOrderCode(),liveOrder.getStatus(),ObjectUtils.equals(liveOrder.getStatus(),2));

        // 发货后退款
        if(ObjectUtils.equals(param.getOrderStatus(),2) || ObjectUtils.equals(param.getOrderStatus(),3)){

            FsJstAftersalePush fsJstAftersalePush = new FsJstAftersalePush();
            fsJstAftersalePush.setOrderId(liveOrder.getOrderCode());
            fsJstAftersalePush.setTaskStatus(com.fs.hisStore.enums.TaskStatusEnum.PENDING.getCode());
            fsJstAftersalePush.setType(String.valueOf(AfterSalesOrderStatusEnum.WAIT_SELLER_AGREE.getIndex()));
            fsJstAftersalePush.setRetryCount(0);
            fsJstAftersalePush.setAfterSaleId(String.valueOf(param.getStoreAfterSalesId()));
            fsJstAftersalePushScrmMapper.insert(fsJstAftersalePush);

        } else {
            // 如果是发货前退款，直接走取消订单流程
            // 如果是发货后退款，走售后流程
            OrderCancelRequestDTO requestDTO = new OrderCancelRequestDTO();
            requestDTO.setOIds(Collections.singletonList(Integer.valueOf(liveOrder.getExtendOrderId())));
            requestDTO.setCancelType("用户退款");
            requestDTO.setRemark("用户退款");

            jstErpHttpService.cancel(requestDTO);
        }

        BaseResponse baseResponse = new BaseResponse();
        baseResponse.setSuccess(true);

        return baseResponse;
    }

    @Override
    public ErpOrderResponse finishOrder(ErpOrder order) {
        return null;
    }

    @Override
    public void getOrderDeliveryStatus(FsStoreOrder order) {

    }

    @Override
    public void getOrderScrmDeliveryStatus(FsStoreOrderScrm order) {

    }

    @Override
    public void getOrderLiveDeliveryStatus(LiveOrder order) {

    }

    /**
     * 批量查询直播订单
     * @param orderList 订单列表
     * @return 查询结果
     */
    @Override
    public ErpOrderQueryResponse batchGetLiveOrder(List<LiveOrder> orderList) {
        if (CollectionUtils.isEmpty(orderList)) {
            ErpOrderQueryResponse response = new ErpOrderQueryResponse();
            response.setOrders(Collections.emptyList());
            response.setSuccess(true);
            return response;
        }

        // 提取所有 extendOrderId
        List<Long> extendOrderIds = orderList.stream()
                .filter(order -> StringUtils.isNotEmpty(order.getExtendOrderId()))
                .map(order -> Long.valueOf(order.getExtendOrderId()))
                .collect(Collectors.toList());

        if (CollectionUtils.isEmpty(extendOrderIds)) {
            ErpOrderQueryResponse response = new ErpOrderQueryResponse();
            response.setOrders(Collections.emptyList());
            response.setSuccess(true);
            return response;
        }

        // 构建批量查询请求
        OrderQueryRequestDTO requestDTO = new OrderQueryRequestDTO();
        requestDTO.setOIds(extendOrderIds);
        requestDTO.setOrderItemFlds(Arrays.asList("status"));

        // 调用ERP服务查询订单
        OrderQueryResponseDTO query = jstErpHttpService.query(requestDTO);

        // 构建响应对象
        ErpOrderQueryResponse response = new ErpOrderQueryResponse();
        List<Map<String, Object>> channelUpdateList = new ArrayList<>();
        List<ErpOrderQuery> erpOrders = new ArrayList<>();

        if (query.getOrders() != null && !query.getOrders().isEmpty()) {
            // 创建订单映射，方便查找
            Map<String, LiveOrder> orderMap = orderList.stream()
                    .collect(Collectors.toMap(
                            LiveOrder::getExtendOrderId,
                            order -> order,
                            (existing, replacement) -> existing
                    ));

            List<LiveOrder> splitOrders = new ArrayList<>();
            // 收集需要更新channel字段的订单（其他状态）


            // 处理查询结果
            for (OrderQueryResponseDTO.Order order : query.getOrders()) {
                String status = order.getStatus();
                LiveOrder liveOrder = orderMap.get(String.valueOf(order.getOId()));

                if (liveOrder == null) {
                    continue;
                }

                // 如果是 sent 状态，正常处理
                if (ErpQueryOrderStatusEnum.SENT.getCode().equals(status)) {
                    ErpOrderQuery erpOrder = convertToErpOrderQueryLive(order);
                    erpOrders.add(erpOrder);
                }
                // 如果是 split 状态，收集起来后续处理
                else if ("Split".equals(status)) {
                    splitOrders.add(liveOrder);
                }
                // 其他状态，收集起来最后统一批量更新
                else {
                    Map<String, Object> updateMap = new HashMap<>();
                    updateMap.put("orderId", liveOrder.getOrderId());
                    updateMap.put("channel", status);
                    channelUpdateList.add(updateMap);
                    log.info("订单状态待写入channel字段，orderCode: {}, status: {}", liveOrder.getOrderCode(), status);
                }
            }

            // 处理 split 状态的订单，按照 getLiveOrder 的逻辑处理
            if (!splitOrders.isEmpty()) {
                // 对每个拆分订单，使用 soId 重新查询聚水潭，获取所有相关订单
                for (LiveOrder splitLiveOrder : splitOrders) {
                    try {
                        // 使用订单号（soId）重新查询聚水潭，获取所有相关订单
                        OrderQueryRequestDTO splitRequestDTO = new OrderQueryRequestDTO();
                        splitRequestDTO.setSoIds(Collections.singletonList(splitLiveOrder.getOrderCode()));
                        splitRequestDTO.setOrderItemFlds(Arrays.asList("status"));

                        // 重新查询聚水潭
                        OrderQueryResponseDTO splitQuery = jstErpHttpService.query(splitRequestDTO);

                        if (splitQuery != null && splitQuery.getOrders() != null && !splitQuery.getOrders().isEmpty()) {
                            // 查找状态不为拆分并且已发货的订单
                            OrderQueryResponseDTO.Order sentOrder = splitQuery.getOrders().stream()
                                    .filter(order -> !"Split".equals(order.getStatus())
                                            && ErpQueryOrderStatusEnum.SENT.getCode().equals(order.getStatus()))
                                    .findFirst()
                                    .orElse(null);

                            if (sentOrder != null) {
                                // 找到符合条件的订单，同步物流状态并转换
                                // 同步物流状态 - 更新订单的物流信息
                                LiveOrder updateOrder = new LiveOrder();
                                updateOrder.setOrderId(splitLiveOrder.getOrderId());
                                if (StringUtils.isNotEmpty(sentOrder.getLogisticsCompany())) {
                                    updateOrder.setDeliveryName(sentOrder.getLogisticsCompany());
                                }
                                if (StringUtils.isNotEmpty(sentOrder.getLId())) {
                                    updateOrder.setDeliverySn(sentOrder.getLId());
                                }
                                if (StringUtils.isNotEmpty(sentOrder.getLcId())) {
                                    updateOrder.setDeliveryCode(sentOrder.getLcId());
                                }
                                if (StringUtils.isNotEmpty(sentOrder.getSendDate())) {
                                    try {
                                        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                        Date sendDate = formatter.parse(sentOrder.getSendDate());
                                        updateOrder.setDeliverySendTime(sendDate);
                                        updateOrder.setDeliveryTime(sentOrder.getSendDate());
                                    } catch (Exception e) {
                                        log.error("解析发货时间失败: {}", sentOrder.getSendDate(), e);
                                    }
                                }
                                liveOrderMapper.updateLiveOrder(updateOrder);
                                log.info("拆分订单查询：找到已发货订单并同步物流状态，orderCode: {}, status: {}, logisticsCompany: {}, deliverySn: {}",
                                        sentOrder.getSoId(), sentOrder.getStatus(), sentOrder.getLogisticsCompany(), sentOrder.getLId());

                                // 转换并添加到结果中
                                ErpOrderQuery erpOrder = convertToErpOrderQueryLive(sentOrder);
                                erpOrders.add(erpOrder);
                            } else {
                                // 如果没有找到已发货的订单，记录日志
                                log.warn("拆分订单查询：未找到已发货的非拆分订单，orderCode: {}", splitLiveOrder.getOrderCode());
                            }
                        } else {
                            // 重新查询失败，记录日志
                            log.error("拆分订单查询：重新查询聚水潭失败，orderCode: {}", splitLiveOrder.getOrderCode());
                        }
                    } catch (Exception e) {
                        log.error("处理拆分订单异常，orderCode: {}", splitLiveOrder.getOrderCode(), e);
                    }
                }
            }

            response.setOrders(erpOrders);
        } else {
            response.setOrders(Collections.emptyList());
        }

        // 统一批量更新其他状态的订单channel字段
        if (!channelUpdateList.isEmpty()) {
            batchUpdateChannel(channelUpdateList);
        }

        response.setSuccess(true);
        return response;
    }

    /**
     * 批量更新订单channel字段
     * @param channelUpdateList 订单ID和channel的映射列表
     */
    private void batchUpdateChannel(List<Map<String, Object>> channelUpdateList) {
        try {
            liveOrderMapper.batchUpdateChannelByOrderIds(channelUpdateList);
            log.info("批量更新订单channel字段完成，共更新{}条记录", channelUpdateList.size());
        } catch (Exception e) {
            log.error("批量更新订单channel字段失败", e);
            // 如果批量更新失败，可以降级为单个更新
            for (Map<String, Object> updateMap : channelUpdateList) {
                try {
                    LiveOrder updateOrder = new LiveOrder();
                    updateOrder.setOrderId((Long) updateMap.get("orderId"));
                    updateOrder.setChannel((String) updateMap.get("channel"));
                    liveOrderMapper.updateLiveOrder(updateOrder);
                } catch (Exception ex) {
                    log.error("单个更新订单channel字段失败，orderId: {}, channel: {}",
                            updateMap.get("orderId"), updateMap.get("channel"), ex);
                }
            }
        }
    }
}

