package com.fs.erp.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.fs.common.exception.CustomException;
import com.fs.common.utils.StringUtils;
import com.fs.company.domain.CompanyUser;
import com.fs.company.mapper.CompanyUserMapper;
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.dto.OrderCancelRequestDTO;
import com.fs.erp.dto.tl.TlCreateOrderRequest;
import com.fs.erp.dto.tl.TlOptions;
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.erp.service.TlErpOrderService;
import com.fs.his.domain.FsStoreOrder;
import com.fs.his.domain.FsStoreOrderItem;
import com.fs.his.domain.FsStoreProduct;
import com.fs.his.domain.FsStoreProductAttrValue;
import com.fs.his.mapper.FsStoreAfterSalesMapper;
import com.fs.his.mapper.FsStoreProductAttrValueMapper;
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.FsStoreProductAttrValueScrm;
import com.fs.hisStore.domain.FsStoreProductScrm;
import com.fs.hisStore.mapper.FsStoreProductAttrValueScrmMapper;
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.huifuPay.sdk.opps.core.utils.StringUtil;
import com.fs.jd.dto.*;
import com.fs.jd.http.IJdHttpService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.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.stream.Collectors;

import static com.fs.erp.utils.TlOrderConverter.toTlOrderItem;

@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 TlErpOrderService tlErpOrderService;

    @Autowired
    private FsStoreProductAttrValueScrmMapper fsStoreProductAttrValueScrmMapper;

    @Autowired
    private FsStoreProductAttrValueMapper fsStoreProductAttrValueMapper;

    @Autowired
    private CompanyUserMapper companyUserMapper;

    @Autowired
    private IJdHttpService jdHttpService;

    @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");
            if (StringUtil.isEmpty(barCode)) {
                List<FsStoreProductAttrValue> values = fsStoreProductAttrValueMapper.selectFsStoreProductAttrValueByProductId(item.getProductId());
                if (!CollectionUtils.isEmpty(values)) {
                    barCode = values.get(0).getBarCode();
                }
            }
            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());
            if (order.getErpType() == null || order.getErpType() == 1) {
                // ERP类型为null或者1的才添加到fsJstCodPush推送
                fsJstCodPushMapper.insert(fsJstCodPush);
            }

        }
        log.info("推送ERP参数: {}",JSON.toJSONString(shopOrderDTO));
        ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
        if (order.getErpType() == null || order.getErpType() == 1) {
            ErpOrderResponseDTO upload = jstErpHttpService.upload(shopOrderDTO);
            ErpOrderResponseDTO.OrderData orderData = upload.getDatas().get(0);
            erpOrderResponse.setSuccess(true);
            erpOrderResponse.setCode(String.valueOf(orderData.getOId()));
            if(CollectionUtils.isEmpty(upload.getDatas())) {
                log.info("推送ERP返回结果: {}",upload);
                throw new IllegalArgumentException("推送ERP返回数不应该为0");
            }
        } else if (order.getErpType() == 2) {
            TlCreateOrderRequest request = new TlCreateOrderRequest();
            //兔灵要求推送业务员名称
            if (fsStoreOrder.getCompanyUserId()== null){
                log.warn("业务员ID为空,订单id:{},订单编号:{}",fsStoreOrder.getOrderId(),fsStoreOrder.getOrderCode());
            }else {
                shopOrderDTO.setCompanyUserId(fsStoreOrder.getCompanyUserId());
                CompanyUser companyUser = companyUserMapper.selectCompanyUserById(fsStoreOrder.getCompanyUserId());
                if (companyUser != null){
                    shopOrderDTO.setCompanyUserName(companyUser.getNickName());
                }

            }
            request.setData(Arrays.asList(toTlOrderItem(shopOrderDTO)));
            request.setCorpId("LwMAMdlBIH7agxn2t9N4Zv40");
            //兔灵的聚水潭服务器id
            TlOptions options = new TlOptions();
            options.setJstServerId(1);
            request.setOptions(options);
            Boolean syncedOrderToJst = tlErpOrderService.syncOrderToJst(request);
            if (syncedOrderToJst){
                erpOrderResponse.setSuccess(true);
                erpOrderResponse.setCode("兔灵ERP");
            } else {
                erpOrderResponse.setSuccess(false);
            }
            //HttpResponse response = tlErpOrderService.syncOrderToJst(request);
            //upload = parseResponse(response,  new TypeReference<CommonResponse<ErpOrderResponseDTO>>() {});
        } else if (order.getErpType() == 3) {
            pushJDOrder(order, itemDTOList, erpOrderResponse);
        }
        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().trim());
        // 支付金额
        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");
            if (StringUtil.isEmpty(barCode)) {
                List<FsStoreProductAttrValueScrm> fsStoreProductAttrValueScrms = fsStoreProductAttrValueScrmMapper.selectFsStoreProductAttrValueByProductId(item.getProductId());
                if (!CollectionUtils.isEmpty(fsStoreProductAttrValueScrms)) {
                    barCode = fsStoreProductAttrValueScrms.get(0).getBarCode();
                }
            }
            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.getPayMoney()).doubleValue());

            // 货到付款要推两次
            PaymentDTO paymentDTO2 = new PaymentDTO();
            // 物流代收金额
            paymentDTO2.setAmount(fsStoreOrder.getTotalPrice().subtract(fsStoreOrder.getPayMoney()).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());
            if (order.getErpType() == null || order.getErpType() == 1) {
                // ERP类型为null或者1的才添加到fsJstCodPush推送
                fsJstCodPushMapper.insert(fsJstCodPush);
            }
            //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()));
        log.info("推送ERP参数: {}",JSON.toJSONString(shopOrderDTO));
        ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
        if (order.getErpType() == null || order.getErpType() == 1) {
            ErpOrderResponseDTO upload = jstErpHttpService.upload(shopOrderDTO);
            ErpOrderResponseDTO.OrderData orderData = upload.getDatas().get(0);
            erpOrderResponse.setSuccess(true);
            erpOrderResponse.setCode(String.valueOf(orderData.getOId()));
            if(CollectionUtils.isEmpty(upload.getDatas())) {
                log.info("推送ERP返回结果: {}",upload);
                throw new IllegalArgumentException("推送ERP返回数不应该为0");
            }
        } else if (order.getErpType() == 2) {
            TlCreateOrderRequest request = new TlCreateOrderRequest();
            //兔灵要求推送业务员名称
            if (fsStoreOrder.getCompanyUserId()== null){
                log.warn("业务员ID为空,订单id:{},订单编号:{}",fsStoreOrder.getId(),fsStoreOrder.getOrderCode());
            }else {
                shopOrderDTO.setCompanyUserId(fsStoreOrder.getCompanyUserId());
                CompanyUser companyUser = companyUserMapper.selectCompanyUserById(fsStoreOrder.getCompanyUserId());
                if (companyUser != null){
                    shopOrderDTO.setCompanyUserName(companyUser.getNickName());
                }

            }
            request.setData(Arrays.asList(toTlOrderItem(shopOrderDTO)));
            request.setCorpId("LwMAMdlBIH7agxn2t9N4Zv40");
            //兔灵的聚水潭服务器id
            TlOptions options = new TlOptions();
            options.setJstServerId(1);
            request.setOptions(options);
            Boolean syncedOrderToJst = tlErpOrderService.syncOrderToJst(request);
            if (syncedOrderToJst){
                erpOrderResponse.setSuccess(true);
                erpOrderResponse.setCode("兔灵ERP");
            } else {
                erpOrderResponse.setSuccess(false);
            }
            //HttpResponse response = tlErpOrderService.syncOrderToJst(request);
            //upload = parseResponse(response,  new TypeReference<CommonResponse<ErpOrderResponseDTO>>() {});
        }  else if (order.getErpType() == 3) {
            pushJDOrder(order, itemDTOList, erpOrderResponse);
        }
        return erpOrderResponse;
    }

    private void pushJDOrder(ErpOrder order, List<OrderItemDTO> itemDTOList, ErpOrderResponse erpOrderResponse) {
         SoCreateOrderRequestDTO requestDTO = new SoCreateOrderRequestDTO();
         requestDTO.setSourceNo("ISV0020008045424");
         //订单号
         requestDTO.setErpDeliveryNo(order.getPlatform_code());
         requestDTO.setWarehouseNo("118075105");
         requestDTO.setOrderMark("00000000000000000000000000000000000000000000000000");
         requestDTO.setPin("YSY2026");
         //渠道信息
         ChannelInfoDTO channelInfoDTO = new ChannelInfoDTO();
         channelInfoDTO.setSalesPlatformSource("6");
         requestDTO.setChannelInfo(channelInfoDTO);
         //客户信息
         CustomerInfoDTO customerInfoDTO = new CustomerInfoDTO();
         customerInfoDTO.setOwnerNo("EBU4418057579814");
         customerInfoDTO.setShopNo("ESP0020010430525");
         requestDTO.setCustomerInfo(customerInfoDTO);
         //承运信息
         CarrierInfoDTO carrierInfoDTO = new CarrierInfoDTO();
         carrierInfoDTO.setCarrierNo("CYS4418046511167");
         requestDTO.setCarrierInfo(carrierInfoDTO);
         List<CargoInfoDTO> cargoInfoDTOList = new ArrayList<>();
         //商品信息
         if (!CollectionUtils.isEmpty(itemDTOList)) {
             for (OrderItemDTO orderItemDTO : itemDTOList) {
                 CargoInfoDTO cargoInfoDTO = new CargoInfoDTO();
                 cargoInfoDTO.setGoodsNo(orderItemDTO.getSkuId());
                 cargoInfoDTO.setPlanQuantity(orderItemDTO.getQty());
                 cargoInfoDTOList.add(cargoInfoDTO);
             }
         }
         requestDTO.setCargoInfos(cargoInfoDTOList);

         //收件人信息
         ReceiverInfoDTO receiverInfoDTO = new ReceiverInfoDTO();
         //收件人电话
         receiverInfoDTO.setMobile(order.getReceiver_mobile());
         //收件人姓名
         receiverInfoDTO.setName(order.getReceiver_name());
         //省
         receiverInfoDTO.setProvince(order.getReceiver_province());
         //市
         receiverInfoDTO.setCity(order.getReceiver_city());
         //区
         receiverInfoDTO.setCounty(order.getReceiver_district());
         receiverInfoDTO.setTown(order.getReceiver_address());
         receiverInfoDTO.setDetailAddress(order.getReceiver_address());
         requestDTO.setReceiverInfo(receiverInfoDTO);
         SoCreateResponseDTO dto = jdHttpService.deliveryCreate(requestDTO);
         if (!StringUtils.isEmpty(dto.getDeliveryNo())) {
             erpOrderResponse.setSuccess(true);
             erpOrderResponse.setCode(dto.getDeliveryNo());
         }
    }


    @Override
    public ErpOrderResponse refundOrder(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);
        log.info("查询聚水潭订单数据{}",query.getOrders());
        // 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 OrderQueryResponseDTO getMergeOrder(ErpOrderQueryRequert param) {
        // 1. 构建查询请求DTO
        OrderQueryRequestDTO requestDTO = new OrderQueryRequestDTO();
        requestDTO.setSoIds(Collections.singletonList(param.getSo_id()));
        // 2. 调用ERP服务查询订单
        return jstErpHttpService.query(requestDTO);
    }

//    @Override
//    public OrderQueryResponseDTO getMergeOrderScrm(ErpOrderQueryRequert param) {
//        return null;
//    }

    /**
     * 将OrderQueryResponseDTO.Order转换为ErpOrderQuery
     *
     * @param order 订单数据
     * @return ErpOrderQuery 转换后的订单数据
     */
    private ErpOrderQuery convertToErpOrderQuery(OrderQueryResponseDTO.Order order) {
        ErpOrderQuery erpOrder = new ErpOrderQuery();
        String userName;
        String userPhone;
        String address;
        FsStoreOrder fsStoreOrder = fsStoreOrderService.selectFsStoreOrderByOrderCode(order.getSoId());
        if (fsStoreOrder == null) {
            FsStoreOrderScrm fsStoreOrderScrm = fsStoreOrderService.selectFsStoreOrderScrmByOrderCode(order.getSoId());
            if (fsStoreOrderScrm != null) {
                userName = fsStoreOrderScrm.getRealName();
                userPhone = fsStoreOrderScrm.getUserPhone();
                address = fsStoreOrderScrm.getUserAddress();
            } else {
                throw new CustomException("该订单号没有找到！销售订单号："+order.getSoId()+",ERP订单号："+order.getOId());
            }
        } else {
            userName = fsStoreOrder.getUserName();
            userPhone = fsStoreOrder.getUserPhone();
            address = fsStoreOrder.getUserAddress();
        }
        //Asserts.notNull(fsStoreOrder,"该订单号没有找到！销售订单号："+order.getSoId()+",ERP订单号："+order.getOId());

        // 设置基本订单信息
        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(userName);
        erpOrder.setReceiver_phone(userPhone);
        erpOrder.setReceiver_mobile(userPhone);

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

        // 如果是已发货
        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());
            //发货日期
            delivery.setSend_date(order.getSendDate());

            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();
        String userName;
        String userPhone;
        String address;
        FsStoreOrderScrm fsStoreOrder = fsStoreOrderService.selectFsStoreOrderScrmByOrderCode(order.getSoId());
        if (fsStoreOrder == null) {
            FsStoreOrder storeOrder = fsStoreOrderService.selectFsStoreOrderByOrderCode(order.getSoId());
            if (storeOrder != null) {
                userName = storeOrder.getUserName();
                userPhone = storeOrder.getUserPhone();
                address = storeOrder.getUserAddress();
            } else {
                throw new CustomException("该订单号没有找到！销售订单号："+order.getSoId()+",ERP订单号："+order.getOId());
            }
        } else {
            userName = fsStoreOrder.getRealName();
            userPhone = fsStoreOrder.getUserPhone();
            address = fsStoreOrder.getUserAddress();
        }
        //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(userName);
        erpOrder.setReceiver_phone(userPhone);
        erpOrder.setReceiver_mobile(userPhone);

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

        // 如果是已发货
        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());
            //发货日期
            delivery.setSend_date(order.getSendDate());

            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 ErpOrderResponse finishOrder(ErpOrder order) {
        return null;
    }

    @Override
    public void getOrderDeliveryStatus(FsStoreOrder order) {

    }


    private <T> T parseResponse(HttpResponse response, TypeReference<CommonResponse<T>> typeReference) {
        String body = response.body();
        log.debug("解析响应体: {}", body);

        CommonResponse<T> commonResponse = JSON.parseObject(body, typeReference);

//        if (ObjectUtils.notEqual(commonResponse.getCode(), 0)) {
        if (!Integer.valueOf(0).equals(commonResponse.getCode())) {
            log.error("API请求失败 - 错误码: {}, 错误信息: {}", commonResponse.getCode(), commonResponse.getMsg());
            throw new RuntimeException("请求接口失败！原因：" + commonResponse.getMsg());
        }

        T result = commonResponse.getData();
        log.info("API请求成功 - 结果: {}", JSON.toJSONString(result));
        return result;
    }

    public static void main(String[] args) {
        String s = "{\"image\":\"https://ysy-1329817240.cos.ap-guangzhou.myqcloud.com/ysy/20250920/5d0b2bc5d7f946f1a9d3e6f8bda7d04f.jpg\",\"productId\":151,\"num\":1,\"productName\":\"甘油二酯食用油2瓶+运费38元\",\"price\":38}";
        JSONObject jsonObject = JSON.parseObject(s);

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

