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.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.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.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
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;

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


        // 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::convertToErpOrderQueryScrm)
                    .collect(Collectors.toList());

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

        return response;
    }

    @Override
    public ErpOrderQueryResponse getLiveOrder(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::convertToErpOrderQueryLive)
                    .collect(Collectors.toList());

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

        return response;
    }

    /**
     * 将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);
        }

        // 设置金额相关信息
        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)){

            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)){

            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) {

    }
}

