package com.fs.erp.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fs.common.core.redis.RedisCache;
import com.fs.common.event.TemplateBean;
import com.fs.common.event.TemplateEvent;
import com.fs.common.event.TemplateListenEnum;
import com.fs.common.utils.DateUtils;
import com.fs.company.service.ICompanyService;
import com.fs.erp.domain.ErpDeliverys;
import com.fs.erp.domain.ErpOrder;
import com.fs.erp.domain.ErpOrderItem;
import com.fs.erp.domain.ErpRefundOrder;
import com.fs.erp.dto.*;
import com.fs.erp.dto.df.*;
import com.fs.erp.dto.sdk.df.DfClient;
import com.fs.erp.dto.sdk.df.enums.RequestUrlEnum;
import com.fs.erp.service.IErpOrderService;
import com.fs.fastGpt.domain.FastGptRole;
import com.fs.fastGpt.service.IFastGptRoleService;
import com.fs.his.config.FsSysConfig;
import com.fs.his.domain.*;
import com.fs.his.enums.FsStoreOrderLogEnum;
import com.fs.his.enums.FsStoreOrderStatusEnum;
import com.fs.his.mapper.*;
import com.fs.his.param.FsStoreOrderSalesParam;
import com.fs.his.service.IFsExpressService;
import com.fs.his.service.IFsIntegralOrderService;
import com.fs.his.service.IFsStoreOrderLogsService;
import com.fs.his.service.IFsStoreOrderService;
import com.fs.his.utils.ConfigUtil;
import com.fs.hisStore.domain.FsExpressScrm;
import com.fs.hisStore.domain.FsStoreOrderItemScrm;
import com.fs.hisStore.domain.FsStoreOrderScrm;
import com.fs.hisStore.domain.FsStoreProductScrm;
import com.fs.hisStore.enums.OrderInfoEnum;
import com.fs.hisStore.enums.OrderLogEnum;
import com.fs.hisStore.enums.ShipperCodeEnum;
import com.fs.hisStore.mapper.FsStoreOrderItemScrmMapper;
import com.fs.hisStore.mapper.FsStoreOrderScrmMapper;
import com.fs.hisStore.mapper.FsStoreProductScrmMapper;
import com.fs.hisStore.param.FsStoreAfterSalesParam;
import com.fs.hisStore.service.IFsExpressScrmService;
import com.fs.hisStore.service.IFsStoreOrderScrmService;
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 com.fs.qw.domain.QwExternalContact;
import com.fs.qw.domain.QwUser;
import com.fs.qw.mapper.QwUserMapper;
import com.fs.qw.service.IQwExternalContactService;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
import com.fs.utils.OrderContextHolder;
import com.fs.wxwork.dto.WxWorkResponseDTO;
import com.fs.wxwork.dto.WxWorkSendTextMsgDTO;
import com.fs.wxwork.dto.WxWorkUserId2VidDTO;
import com.fs.wxwork.dto.WxWorkVid2UserIdRespDTO;
import com.fs.wxwork.service.WxWorkService;
import com.hc.openapi.tool.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.Asserts;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

import static com.fs.hisStore.constants.StoreConstants.DELIVERY;

@Service
@Slf4j
public class DfOrderServiceImpl implements IErpOrderService {
//    @Autowired
//    ConfigUtil configUtil;

    @Autowired
    FsDfAccountMapper fsDfAccountMapper;

    @Autowired
    private FsStoreOrderMapper fsStoreOrderMapper;

    @Autowired
    private FsStoreOrderScrmMapper fsStoreOrderScrmMapper;

    @Autowired
    private FsStoreOrderItemMapper fsStoreOrderItemMapper;

    @Autowired
    private FsStoreOrderItemScrmMapper fsStoreOrderItemScrmMapper;

    @Autowired
    private FsStoreProductMapper fsStoreProductMapper;

    @Autowired
    private FsStoreProductScrmMapper fsStoreProductScrmMapper;

    @Autowired
    private FsStoreOrderDfMapper fsStoreOrderDfMapper;

    @Autowired
    private FsExpressMapper fsExpressMapper;

    @Autowired
    private DfClient client;

    @Autowired
    private IFsStoreOrderLogsService fsStoreOrderLogsService;

    @Autowired
    private IFsStoreOrderScrmService fsStoreOrderScrmLogsService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private FsStoreMapper fsStoreMapper;

    @Autowired
    private IFsExpressService expressService;

    @Autowired
    private IFsExpressScrmService expressScrmService;

    @Autowired
    private IFsStoreOrderService fsStoreOrderService;

    @Autowired
    private IFsStoreOrderScrmService fsStoreOrderScrmService;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Autowired
    private RedisCache redisCache;
    @Autowired
    private IQwExternalContactService externalContactService;
    @Autowired
    private QwUserMapper qwUserMapper;
    @Autowired
    private IFastGptRoleService fastGptRoleService;
    @Autowired
    private WxWorkService wxWorkService;
    @Autowired
    private FsIntegralOrderMapper fsIntegralOrderMapper;

    @Autowired
    private LiveOrderMapper liveOrderMapper;

    @Autowired
    private FsIntegralOrderLogsMapper fsIntegralOrderLogsMapper;
    @Autowired
    private LiveOrderItemMapper liveOrderItemMapper;

    @Override
    public ErpOrderResponse addOrder(ErpOrder order) {
        if (!Objects.isNull(order.getIsIntegralOrder()) && order.getIsIntegralOrder())
            return getErpIntegralOrderResponse(order);
        return getErpOrderResponse(order);
    }

    @Override
    public ErpOrderResponse addOrderScrm(ErpOrder order) {
        return getScrmErpOrderResponse(order);
    }

    @Override
    public ErpOrderResponse addLiveOrder(ErpOrder order) {
        return getLiveErpOrderResponse(order);
    }

    private ErpOrderResponse getLiveErpOrderResponse(ErpOrder order) {
        LiveOrder liveOrder = liveOrderMapper.selectLiveOrderByOrderCode(order.getPlatform_code());
        if (liveOrder == null) {
            return null;
        }
        Long dfAccountId = getSFAccountIndex(liveOrder.getOrderId());
        //1.获取请求参数
        ExternalOrderRequestVo vo = getCreateLiveOrderRequestParam(order, liveOrder, dfAccountId);
        if (vo == null) {
            return null;
        }
        try {
            Map<String, Object> map = JSON.parseObject(JSON.toJSONString(vo), Map.class);
            //2.请求
            log.info("开始推送订单,参数: {}", JSON.toJSONString(map));
            String response = client.execute(RequestUrlEnum.CREAT_ORDER, map, dfAccountId);
            if (StringUtils.isBlank(response)) {
                return new ErpOrderResponse();
            }
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            //3.处理请求结果
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                //存储订单推送用的哪个账户
                FsStoreOrderDf df = addDfOrderLive(liveOrder, dfAccountId);
                log.info("订单推送成功: {}", response);
                //可以回调 也可以查询订单
                Map<String, Object> orderResultQueryParam = new HashMap<>();
                orderResultQueryParam.put("orderNumber", order.getPlatform_code());
                orderResultQueryParam.put("exInterfaceType", df.getStatus());
                try {
                    getOrderLiveResult(orderResultQueryParam, dfAccountId);
                } catch (Exception e) {
                    log.info("推送订单完成，查询订单问题{}", e.getMessage());
                }
                ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
                erpOrderResponse.setCode(order.getPlatform_code());
                erpOrderResponse.setSuccess(true);
                return erpOrderResponse;
            } else {
                throw new RuntimeException(String.format("订单推送失败,原因: %s", dfApiResponse.getMsg()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ErpOrderResponse();
    }

    /**
     * 退款 取消订单
     *
     * @param order
     * @return
     */
    @Override
    public ErpOrderResponse refundOrder(ErpRefundOrder order) {
        //获取代服账户
        String orderCode = order.getOrderCode();
        FsStoreOrder fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(orderCode);
        FsStoreOrderDf df = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(fsStoreOrder.getOrderId());
        if (df == null) {
            return null;
        }
        Long dfAccountId = getSFAccountIndex(fsStoreOrder.getOrderId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("loginAccount", df.getLoginAccount());
        FsDfAccount dfAccount = fsDfAccountMapper.selectFsDfAccountById(dfAccountId);
        if (dfAccount != null && StringUtils.isNotBlank(dfAccount.getCallBackUrl())) {
            map.put("callBackUrl", dfAccount.getCallBackUrl());
        }
        map.put("orderNumber", orderCode);
        map.put("mailNumber", fsStoreOrder.getDeliverySn());
        try {
            //2.请求
            log.info("开始取消订单,参数: {}", JSON.toJSONString(map));
            String response = client.execute(RequestUrlEnum.ORDER_CANCEL, map, dfAccountId);
            if (StringUtils.isBlank(response)) {
                return new ErpOrderResponse();
            }
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            //3.处理请求结果
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                //存储订单推送用的哪个账户
                log.info("订单取消成功: {}", response);
                //修改df表
                df.setStatus(2);
                df.setUpdateTime(DateUtils.getNowDate());
                fsStoreOrderDfMapper.updateFsStoreOrderDf(df);
                //可以回调 也可以查询订单
                Map<String, Object> orderResultQueryParam = new HashMap<>();
                orderResultQueryParam.put("orderNumber", orderCode);
                orderResultQueryParam.put("exInterfaceType", 2); //2为查询取消订单结果
//                    getOrderResult(orderResultQueryParam,sfAccountIndex);
                ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
                erpOrderResponse.setCode(orderCode);
                erpOrderResponse.setSuccess(true);
                return erpOrderResponse;
            } else {
                throw new RuntimeException(String.format("订单取消失败,原因: %s", dfApiResponse.getMsg()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ErpOrderResponse();
    }

    /**
     * 退款 取消订单
     *
     * @param order
     * @return
     */
    @Override
    public ErpOrderResponse refundOrderScrm(ErpRefundOrder order) {
        //获取代服账户
        String orderCode = order.getOrderCode();
        FsStoreOrderScrm fsStoreOrder = fsStoreOrderScrmMapper.selectFsStoreOrderByOrderCode(orderCode);
        FsStoreOrderDf df = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(fsStoreOrder.getId());
        if (df == null) {
            return null;
        }
        Long dfAccountId = getSFAccountIndex(fsStoreOrder.getId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("loginAccount", df.getLoginAccount());
        FsDfAccount dfAccount = fsDfAccountMapper.selectFsDfAccountById(dfAccountId);
        if (dfAccount != null && StringUtils.isNotBlank(dfAccount.getCallBackUrl())) {
            map.put("callBackUrl", dfAccount.getCallBackUrl());
        }
        map.put("orderNumber", orderCode);
        map.put("mailNumber", fsStoreOrder.getDeliveryId());
        try {
            //2.请求
            log.info("开始取消订单,参数: {}", JSON.toJSONString(map));
            String response = client.execute(RequestUrlEnum.ORDER_CANCEL, map, dfAccountId);
            if (StringUtils.isBlank(response)) {
                return new ErpOrderResponse();
            }
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            //3.处理请求结果
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                //存储订单推送用的哪个账户
                log.info("订单取消成功: {}", response);
                //修改df表
                df.setStatus(2);
                df.setUpdateTime(DateUtils.getNowDate());
                fsStoreOrderDfMapper.updateFsStoreOrderDf(df);
                //可以回调 也可以查询订单
                Map<String, Object> orderResultQueryParam = new HashMap<>();
                orderResultQueryParam.put("orderNumber", orderCode);
                orderResultQueryParam.put("exInterfaceType", 2); //2为查询取消订单结果
//                    getOrderResult(orderResultQueryParam,sfAccountIndex);
                ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
                erpOrderResponse.setCode(orderCode);
                erpOrderResponse.setSuccess(true);
                return erpOrderResponse;
            } else {
                throw new RuntimeException(String.format("订单取消失败,原因: %s", dfApiResponse.getMsg()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ErpOrderResponse();
    }

    @Override
    public ErpOrderResponse refundLiveOrder(ErpRefundOrder order) {
        //获取代服账户
        String orderCode = order.getOrderCode();
        LiveOrder liveOrder = liveOrderMapper.selectLiveOrderByOrderCode(orderCode);
        FsStoreOrderDf df = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(liveOrder.getOrderId());
        if (df == null) {
            return null;
        }
        Long dfAccountId = getSFAccountIndex(liveOrder.getOrderId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("loginAccount", df.getLoginAccount());
        FsDfAccount dfAccount = fsDfAccountMapper.selectFsDfAccountById(dfAccountId);
        if (dfAccount != null && StringUtils.isNotBlank(dfAccount.getCallBackUrl())) {
            map.put("callBackUrl", dfAccount.getCallBackUrl());
        }
        map.put("orderNumber", orderCode);
        map.put("mailNumber", liveOrder.getDeliverySn());
        try {
            //2.请求
            log.info("开始取消订单,参数: {}", JSON.toJSONString(map));
            String response = client.execute(RequestUrlEnum.ORDER_CANCEL, map, dfAccountId);
            if (StringUtils.isBlank(response)) {
                return new ErpOrderResponse();
            }
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            //3.处理请求结果
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                //存储订单推送用的哪个账户
                log.info("订单取消成功: {}", response);
                //修改df表
                df.setStatus(2);
                df.setUpdateTime(DateUtils.getNowDate());
                fsStoreOrderDfMapper.updateFsStoreOrderDf(df);
                //可以回调 也可以查询订单
                Map<String, Object> orderResultQueryParam = new HashMap<>();
                orderResultQueryParam.put("orderNumber", orderCode);
                orderResultQueryParam.put("exInterfaceType", 2); //2为查询取消订单结果
                ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
                erpOrderResponse.setCode(orderCode);
                erpOrderResponse.setSuccess(true);
                return erpOrderResponse;
            } else {
                throw new RuntimeException(String.format("订单取消失败,原因: %s", dfApiResponse.getMsg()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ErpOrderResponse();
    }

    @Override
    public ErpDeliverysResponse getDeliver(ErpDeliverysRequest request) {
        ErpDeliverysResponse erpDeliverysResponse = new ErpDeliverysResponse();
        String orderCode = request.getCode();
        if (StrUtil.isNotBlank(orderCode)) {
            FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(orderCode);
            if (OrderContextHolder.hasIntegralOrder())
                order = new FsStoreOrder();
            if (order != null) {
                String mailNumber = order.getDeliverySn();
                Long dfAccountId = getSFAccountIndex(order.getOrderId());
                //积分商城逻辑
                if (OrderContextHolder.hasIntegralOrder()){
                    FsIntegralOrder integralOrder = OrderContextHolder.getIntegralOrder();
                    mailNumber = integralOrder.getDeliverySn();
                    FsDfAccount fsDfAccount = fsDfAccountMapper.selectFsDfAccountByAccount(integralOrder.getLoginAccount());
                    if (fsDfAccount != null)
                        dfAccountId = fsDfAccount.getId();
                    OrderContextHolder.clear();//清理threadlocalmap引用。
                }
                if (StringUtils.isNotBlank(mailNumber) && dfAccountId != null) {
                    try {
                        Map<String, Object> map = new HashMap<>();
                        map.put("mailNumber", mailNumber);
                        log.info("开始查询路由结果,参数为: {}", JSON.toJSONString(map));
                        String response = client.execute(RequestUrlEnum.ORDER_DELIVERY, map, dfAccountId);
                        if (StringUtils.isBlank(response)) {
                            return erpDeliverysResponse;
                        }
                        DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
                        if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                            dfApiResponse.setCode(mailNumber);
                            Object result = dfApiResponse.getResult();
                            String jsonStr = JSON.toJSONString(JSON.parseObject(JSONUtil.toJsonStr(result), HashMap.class).get("list"));
                            List<ErpDeliverys> dfDeliveryResponse = null;
                            try {
                                dfDeliveryResponse = JSON.parseArray(jsonStr, ErpDeliverys.class);
                            } catch (Exception e) {
                                log.info("查询路由结果异常: {},结果为:{}", e.getMessage(), jsonStr);
                                erpDeliverysResponse.setSuccess(false);
                                erpDeliverysResponse.setErrorDesc("未更新物流");
                                return erpDeliverysResponse;
                            }
                            if (dfDeliveryResponse != null && !dfDeliveryResponse.isEmpty()) {
                                for (ErpDeliverys deliveryResponse : dfDeliveryResponse) {
                                    deliveryResponse.setMail_no(deliveryResponse.getMailNo());
                                    deliveryResponse.setExpress_code(deliveryResponse.getMailNo());
                                    deliveryResponse.setExpress_name("顺丰");
                                }
                                erpDeliverysResponse.setDeliverys(dfDeliveryResponse);
                            }
                        } else {
                            erpDeliverysResponse.setErrorDesc(dfApiResponse.getMsg());
                        }
                    } catch (IOException e) {
                        log.info("代服路由查询错误{}", e.getMessage());
                    }
                } else {
                    erpDeliverysResponse.setErrorDesc("该订单不存在/顺丰账户不存在");
                }
            }


        } else {
            erpDeliverysResponse.setErrorDesc("未获取到原始订单号");
        }
        return erpDeliverysResponse;
    }

    @Autowired
    private FsIntegralOrderDfMapper integralOrderDfMapper;
    /**
     * 目前仅查询下单用户
     *
     * @param requset
     * @return
     */
    @Override
    public ErpOrderQueryResponse getOrder(ErpOrderQueryRequert requset) {
        ErpOrderQueryResponse response = new ErpOrderQueryResponse();
        String orderNumber = requset.getCode();
        if (StrUtil.isNotBlank(orderNumber)) {
            //金牛积分商品的逻辑
            if (OrderContextHolder.hasIntegralOrder()) {
                FsIntegralOrder order = fsIntegralOrderMapper.selectOne(Wrappers.<FsIntegralOrder>lambdaQuery().eq(FsIntegralOrder::getOrderCode, orderNumber));
                if (order != null) {
                    //获取下单账户
                    FsIntegralOrderDf df = integralOrderDfMapper.selectOne(Wrappers.<FsIntegralOrderDf>lambdaQuery().eq(FsIntegralOrderDf::getOrderId,order.getOrderId()));
                    if (df == null) {
                        return null;
                    }
                    Long dfAccountId = getSFAccountIndex(order.getOrderId());
                    if (dfAccountId != null) {
                        Map<String, Object> orderResultQueryParam = new HashMap<>();
                        orderResultQueryParam.put("orderNumber", orderNumber);
                        orderResultQueryParam.put("exInterfaceType", df.getStatus());
                        getIntegralOrderResult(orderResultQueryParam, dfAccountId);
                        return response;
                    }
                }
            }else {
                FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(orderNumber);
                if (order != null) {
                    //获取下单账户
                    FsStoreOrderDf df = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(order.getOrderId());
                    if (df == null) {
                        return null;
                    }
                    Long dfAccountId = getSFAccountIndex(order.getOrderId());
                    if (dfAccountId != null) {
                        Map<String, Object> orderResultQueryParam = new HashMap<>();
                        orderResultQueryParam.put("orderNumber", orderNumber);
                        orderResultQueryParam.put("exInterfaceType", df.getStatus());
                        getOrderResult(orderResultQueryParam, dfAccountId);
                        return response;
                    }
                }
            }
            response.setErrorDesc("该订单不存在/顺丰账户不存在");
        } else {
            response.setErrorDesc("未获取到原始订单号");
        }
        return response;
    }

    @Override
    public ErpOrderQueryResponse getScrmOrder(ErpOrderQueryRequert param) {
        ErpOrderQueryResponse response = new ErpOrderQueryResponse();
        String orderNumber = param.getCode();
        if (StrUtil.isNotBlank(orderNumber)) {
            FsStoreOrderScrm order = fsStoreOrderScrmMapper.selectFsStoreOrderByOrderCode(orderNumber);
            if (order != null) {
                //获取下单账户
                FsStoreOrderDf df = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(order.getId());
                if (df == null) {
                    return null;
                }
                Long dfAccountId = getSFAccountIndex(order.getId());
                if (dfAccountId != null) {
                    Map<String, Object> orderResultQueryParam = new HashMap<>();
                    orderResultQueryParam.put("orderNumber", orderNumber);
                    orderResultQueryParam.put("exInterfaceType", df.getStatus());
                    getOrderScrmResult(orderResultQueryParam, dfAccountId);
                    return response;
                }
            }
            response.setErrorDesc("该订单不存在/顺丰账户不存在");
        } else {
            response.setErrorDesc("未获取到原始订单号");
        }
        return response;
    }

    @Override
    public ErpOrderQueryResponse getLiveOrder(ErpOrderQueryRequert param) {
        ErpOrderQueryResponse response = new ErpOrderQueryResponse();
        String orderNumber = param.getCode();
        if (StrUtil.isNotBlank(orderNumber)) {
            LiveOrder order = liveOrderMapper.selectLiveOrderByOrderCode(orderNumber);
            if (order != null) {
                //获取下单账户
                FsStoreOrderDf df = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(order.getOrderId());
                if (df == null) {
                    return null;
                }
                Long dfAccountId = getSFAccountIndex(order.getOrderId());
                if (dfAccountId != null) {
                    Map<String, Object> orderResultQueryParam = new HashMap<>();
                    orderResultQueryParam.put("orderNumber", orderNumber);
                    orderResultQueryParam.put("exInterfaceType", df.getStatus());
                    getOrderLiveResult(orderResultQueryParam, dfAccountId);
                    return response;
                }
            }
            response.setErrorDesc("该订单不存在/顺丰账户不存在");
        } else {
            response.setErrorDesc("未获取到原始订单号");
        }
        return response;
    }

    @Override
    public BaseResponse refundUpdate(ErpRefundUpdateRequest request) {
        ErpRefundOrder erpRefundOrder = new ErpRefundOrder();
        erpRefundOrder.setOrderCode(request.getTid());
        return refundOrder(erpRefundOrder);
    }

    @Override
    public BaseResponse refundUpdateScrm(ErpRefundUpdateRequest request) {
        ErpRefundOrder erpRefundOrder = new ErpRefundOrder();
        erpRefundOrder.setOrderCode(request.getTid());
        return refundOrderScrm(erpRefundOrder);
    }

    @Override
    public BaseResponse refundUpdateLive(ErpRefundUpdateRequest param) {
        ErpRefundOrder erpRefundOrder = new ErpRefundOrder();
        erpRefundOrder.setOrderCode(param.getTid());
        return refundLiveOrder(erpRefundOrder);
    }

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

    @Override
    public void getOrderDeliveryStatus(FsStoreOrder order) {
        Map<String, Object> map = new HashMap<>();
        Long orderId = order.getOrderId();
        Long dfAccountId = getSFAccountIndex(orderId);
        if (dfAccountId == null){
            log.info("代服管家 getOrderDeliveryStatus-订单id: {}", orderId);
        }
        map.put("orderNumber", order.getOrderCode());
        map.put("mailNumber", order.getDeliverySn());
        try {
            String response = client.execute(RequestUrlEnum.ORDER_DELIVERY_STATUS, map, dfAccountId);
            if (StringUtils.isBlank(response)) {
                return;
            }
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            if ("运单不存在".equals(dfApiResponse.getMsg())) {

                //查看原来物流状态
                if (OrderContextHolder.hasIntegralOrder()) {
                    cancelOrder(OrderContextHolder.getIntegralOrder());
                }else {
                    cancelOrder(order);
                }
                log.info("代服管家 getOrderDeliveryStatus: {}", response);
                return;
            }
            //3.处理请求结果
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                String jsonString = JSON.toJSONString(dfApiResponse.getResult());
//                List<DFOrderStatusResultRequest> requestList = JSON.parseArray(jsonString, DFOrderStatusResultRequest.class);
                DFOrderStatusResultRequest temp = JSON.parseObject(jsonString, DFOrderStatusResultRequest.class);
                //0待揽收 1已揽收 2运输中 3派送中 4异常件 5退回件 6退回签收 7转寄件 8作废件 9已签收 10 已取消
                Integer deliveryStatus = 0;
                String stateEx = "0";
                FsStoreOrder fsStoreOrderMap = new FsStoreOrder();
                fsStoreOrderMap.setOrderId(orderId);
                Integer status = temp.getStatus();
                switch (status) {
                    case 0:
                        //0待揽收 1已揽收 2运输中
                        deliveryStatus = status;
                        stateEx = status.toString();
                        break;
                    case 1:
                        //0待揽收 1已揽收 2运输中
                        deliveryStatus = status;
                        stateEx = status.toString();
                        break;
                    case 2:
                        //0待揽收 1已揽收 2运输中
                        deliveryStatus = status;
                        stateEx = status.toString();
                        break;
                    case 3:
                        //3派送中
                        deliveryStatus = 2;
                        stateEx = "202";
                        break;
                    case 4:
                        // 4异常件
                        deliveryStatus = status;
                        stateEx = status.toString();
                        break;
                    case 5:
                        //5退回件
                        deliveryStatus = 4;
                        stateEx = "407"; //退货未签收
                        break;
                    case 6:
                        // 6退回签收 7转寄件 8作废件 9已签收 10 已取消
                        deliveryStatus = status;
                        stateEx = "406"; //退货签收
                        break;
                    case 9:
                        //已签收
                        deliveryStatus = 3;
                        stateEx = "301";
                        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.store");
                        Map<String, Object> config = (Map<String, Object>) JSON.parse(sysConfig.getConfigValue());
                        Object isUpdateOrder = config.get("isUpdateOrder");
                        if (isUpdateOrder == null || "1".equals(isUpdateOrder.toString())) {
                            if (OrderContextHolder.hasIntegralOrder()) {
                                FsIntegralOrder integralOrder = OrderContextHolder.getIntegralOrder();
                                //积分订单修改状态已完成
                                integralOrder.setStatus(3);//设置已完成状态
                                int i = fsIntegralOrderMapper.updateById(integralOrder);
                                log.info("积分订单编号{}完成订单，更新条数{}",integralOrder.getOrderCode(),i);
                            }else {
//                                fsStoreOrderService.getGoods(order.getOrderId(), "物流自动");
                            fsStoreOrderService.getGoods(orderId, "物流自动");
                            }
                        }
                        break;
                    case 10:
                        //取消订单
                        String mailNumber = temp.getMailNumber();
                        if (OrderContextHolder.hasIntegralOrder()) {
                            List<FsIntegralOrder> orders = fsIntegralOrderMapper.selectList(Wrappers.<FsIntegralOrder>lambdaQuery().eq(FsIntegralOrder::getDeliverySn, mailNumber));
                            if (orders != null && !orders.isEmpty()) {
                                orders.forEach(tempOrder->{
                                    log.info("订单状态查询取消订单{}",tempOrder.getOrderCode());
                                    cancelOrder(tempOrder);
                                    log.info("代服管家 订单取消成功: {}", response);
                                });

                            }
                        }else {
                            List<FsStoreOrder> fsStoreOrders = fsStoreOrderMapper.selectFsStoreOrderListByDeliverySn(mailNumber);
                            if (fsStoreOrders != null && !fsStoreOrders.isEmpty()) {
                                fsStoreOrders.forEach(tempOrder -> {
                                    cancelOrder(order);
                                    log.info("代服管家 订单取消成功: {}", response);
                                });
                            }
                        }
                        break;
                }


                //判断物流状态是否更新 更新ai发送物流给客户
                try {
                    aiSendExpress(order, stateEx);
                } catch (Exception e) {
                    log.error("ai发送物流信息错误：{}", e.getMessage());
                }


                if (OrderContextHolder.hasIntegralOrder()){
                    //加积分订单的字段，然后在这里更新它
                    FsIntegralOrder integralOrder = OrderContextHolder.getIntegralOrder();
                    integralOrder.setDeliveryStatus(deliveryStatus);
                    integralOrder.setDeliveryType(stateEx);
                    int i = fsIntegralOrderMapper.updateById(integralOrder);
                    log.info("更新订单{}物流状态为{}and{}更新条数{}",integralOrder.getOrderCode(),deliveryStatus,stateEx,i);
                }else {
                    fsStoreOrderMap.setDeliveryStatus(deliveryStatus); //物流状态：0-暂无轨迹信息 1-已揽收 2-在途中,3-签收,4-问题件
                    fsStoreOrderMap.setDeliveryType(stateEx);
                    fsStoreOrderMapper.updateFsStoreOrder(fsStoreOrderMap);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void aiSendExpress(FsStoreOrder order, String stateEx) {
        Long orderId = order.getOrderId();
        if (!Objects.equals(order.getDeliveryType(), stateEx)) {
            //判断是否添加相关企微员工
            if(order.getUserId() != null){
                List<QwExternalContact> qwExternalContact = externalContactService.selectQwExternalContactByFsUserIdAndCompany(order.getUserId(), order.getCompanyUserId());
                if(qwExternalContact != null && !qwExternalContact.isEmpty()) {
                    for (QwExternalContact externalContact : qwExternalContact) {
                        Long qwUserId = externalContact.getQwUserId();
                        if (qwUserId != null) {
                            QwUser qwUser = qwUserMapper.selectQwUserById(qwUserId);
                            if (qwUser != null && qwUser.getUid() != null && qwUser.getFastGptRoleId() != null && qwUser.getServerId() != null && qwUser.getServerStatus() == 1 && qwUser.getIpadStatus() == 1) {
                                FastGptRole fastGptRole = fastGptRoleService.selectFastGptRoleByRoleId(qwUser.getFastGptRoleId());
                                if (fastGptRole.getLogistics() == 0) {
                                    log.error("物流功能未开启,roleId：" + qwUser.getFastGptRoleId() + "订单号：" + orderId);
                                }
                                Long sendId = externalContact.getWxUserId();
                                if (sendId == null || sendId <= 0) {
                                    WxWorkUserId2VidDTO wxWorkUserId2VidDTO = new WxWorkUserId2VidDTO();
                                    wxWorkUserId2VidDTO.setOpenid(Collections.singletonList(externalContact.getExternalUserId()));
                                    wxWorkUserId2VidDTO.setUuid(qwUser.getUid());
                                    WxWorkResponseDTO<List<WxWorkVid2UserIdRespDTO>> WxWorkVid2UserIdRespDTO = wxWorkService.UserId2Vid(wxWorkUserId2VidDTO, qwUser.getServerId());
                                    List<WxWorkVid2UserIdRespDTO> data = WxWorkVid2UserIdRespDTO.getData();
                                    if (data != null && !data.isEmpty()) {
                                        sendId = data.get(0).getUser_id();
                                        if (sendId != null && externalContact.getId() != null) {
                                            QwExternalContact upd = new QwExternalContact();
                                            upd.setId(externalContact.getId());
                                            upd.setWxUserId(sendId);
                                            externalContactService.updateQwExternalContact(upd);
                                        }
                                    }
                                }
                                StringBuilder sBuilder = new StringBuilder();
                                if (sendId != null) {
                                    switch (order.getStatus()) {
                                        case -1:
                                            break;
                                        case -2:
                                            break;
                                        case 1:
                                            break;
                                        case 2:
                                            break;
                                        case 3:
                                            //你好，这边查询到您购买的XXX（购买套餐）在XXX（时间）已经送到了，送货员电话为XXX（送货员信息）
                                            ErpDeliverysRequest erpDeliverysRequest = new ErpDeliverysRequest();
                                            erpDeliverysRequest.setCode(order.getOrderCode());
                                            ErpDeliverysResponse express = null;
                                            express = getDeliver(erpDeliverysRequest);
                                            if (express != null && express.getDeliverys() != null && !express.getDeliverys().isEmpty()) {
                                                List<ErpDeliverys> deliverys = express.getDeliverys();
                                                ErpDeliverys tracesDTO = deliverys.get(deliverys.size() - 1);
                                                String remark = tracesDTO.getRemark();

                                                if ("0".equals(stateEx) || "1".equals(stateEx) || "2".equals(stateEx)) {
                                                    if (remark.contains("已收取快件")){
                                                        sBuilder.append("您好，您有一个包裹正在准备发货，请耐心等待;\n");
                                                        if (order.getDeliverySn() != null && !order.getDeliverySn().isEmpty()) {
                                                            sBuilder.append(" 物流单号为：").append(order.getDeliverySn()).append("\n");
                                                        }
                                                        sBuilder.append("\uD83C\uDF39\uD83C\uDF39\uD83C\uDF39");
                                                    }
                                                } else if ("202".equals(stateEx)) {
                                                    if (remark.contains("正在派送")) {
                                                        sBuilder.append("这边查询到您有一个包裹 ");
                                                        sBuilder.append("正在派送中\n");
                                                        sBuilder.append(" 物流单号为：").append(order.getDeliverySn()).append("\n");
                                                        sBuilder.append("物流信息：").append(remark).append("\n");
                                                        sBuilder.append("\uD83C\uDF39\uD83C\uDF39\uD83C\uDF39");
                                                    }

                                                } else if ("301".equals(stateEx)){
                                                    if (remark.contains("派送至本人") || remark.contains("签收")) {
                                                        sBuilder.append("这边查询到您有一个包裹 ");
                                                        sBuilder.append(" 在").append(tracesDTO.getAcceptTime()).append("已经签收了\n");
                                                        sBuilder.append(" 物流单号为：").append(order.getDeliverySn()).append("\n");
                                                        sBuilder.append("物流信息：").append(remark).append("\n");
                                                    }
                                                }
                                            }
                                            break;
                                        case 4:
                                        case 5:
                                    }
                                    if (!"".contentEquals(sBuilder)) {
                                        //2.发送模板中的文字内容
                                        String content = sBuilder.toString();
                                        content = content.replace("（有事呼叫我，勿找平台，少一次投诉，多一份感恩）", "");
                                        WxWorkSendTextMsgDTO wxWorkSendTextMsgDTO = new WxWorkSendTextMsgDTO();
                                        wxWorkSendTextMsgDTO.setSend_userid(sendId);
                                        wxWorkSendTextMsgDTO.setUuid(qwUser.getUid());
                                        wxWorkSendTextMsgDTO.setContent(content);
                                        wxWorkSendTextMsgDTO.setIsRoom(false);
                                        wxWorkService.SendTextMsg(wxWorkSendTextMsgDTO, qwUser.getServerId());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    @Override
    public void getOrderScrmDeliveryStatus(FsStoreOrderScrm order) {
        Map<String, Object> map = new HashMap<>();
        Long dfAccountId = getSFAccountIndex(order.getId());
        map.put("orderNumber", order.getOrderCode());
        map.put("mailNumber", order.getDeliveryId());
        try {
            String response = client.execute(RequestUrlEnum.ORDER_DELIVERY_STATUS, map, dfAccountId);
            if (StringUtils.isBlank(response)) {
                return;
            }
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            if ("运单不存在".equals(dfApiResponse.getMsg())) {

                //查看原来物流状态
                cancelOrderScrm(order);
                log.info("代服管家 getOrderDeliveryStatus: {}", response);
                return;
            }
            //3.处理请求结果
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                String jsonString = JSON.toJSONString(dfApiResponse.getResult());
//                List<DFOrderStatusResultRequest> requestList = JSON.parseArray(jsonString, DFOrderStatusResultRequest.class);
                DFOrderStatusResultRequest temp = JSON.parseObject(jsonString, DFOrderStatusResultRequest.class);
                //0待揽收 1已揽收 2运输中 3派送中 4异常件 5退回件 6退回签收 7转寄件 8作废件 9已签收 10 已取消
                Integer deliveryStatus = 0;
                String stateEx = "0";
                FsStoreOrderScrm fsStoreOrderMap = new FsStoreOrderScrm();
                fsStoreOrderMap.setId(order.getId());
                Integer status = temp.getStatus();
                switch (status) {
                    case 0:
                        //0待揽收 1已揽收 2运输中
                        deliveryStatus = status;
                        stateEx = status.toString();
                        break;
                    case 1:
                        //0待揽收 1已揽收 2运输中
                        deliveryStatus = status;
                        stateEx = status.toString();
                        break;
                    case 2:
                        //0待揽收 1已揽收 2运输中
                        deliveryStatus = status;
                        stateEx = status.toString();
                        break;
                    case 3:
                        //3派送中
                        deliveryStatus = 2;
                        stateEx = "202";
                        break;
                    case 4:
                        // 4异常件
                        deliveryStatus = status;
                        stateEx = status.toString();
                        break;
                    case 5:
                        //5退回件
                        deliveryStatus = 4;
                        stateEx = "407"; //退货未签收
                        break;
                    case 6:
                        // 6退回签收 7转寄件 8作废件 9已签收 10 已取消
                        deliveryStatus = status;
                        stateEx = "406"; //退货签收
                        break;
                    case 9:
                        //已签收
                        deliveryStatus = 3;
                        stateEx = "301"; //退货签收
//                        SysConfig sysConfig = sysConfigMapper.selectConfigByConfigKey("his.store");
//                        Map<String, Object> config = (Map<String, Object>) JSON.parse(sysConfig.getConfigValue());
//                        Object isUpdateOrder = config.get("isUpdateOrder");
//                        if (isUpdateOrder == null || "1".equals(isUpdateOrder.toString())) {
//                            fsStoreOrderService.getGoods(order.getId(), "物流自动");
//                        }
                        break;
                    case 10:
                        //取消订单
                        String mailNumber = temp.getMailNumber();
                        List<FsStoreOrderScrm> fsStoreOrders = fsStoreOrderScrmMapper.selectFsStoreOrderListByDeliveryId(mailNumber);
                        if (fsStoreOrders != null && !fsStoreOrders.isEmpty()) {
                            fsStoreOrders.forEach(tempOrder -> {
                                cancelOrderScrm(order);
                                log.info("代服管家 订单取消成功: {}", response);
                            });
                        }
                        break;
                }
                fsStoreOrderMap.setDeliveryStatus(deliveryStatus); //物流状态：0-暂无轨迹信息 1-已揽收 2-在途中,3-签收,4-问题件
                fsStoreOrderMap.setDeliveryType(stateEx);
                fsStoreOrderScrmMapper.updateFsStoreOrder(fsStoreOrderMap);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void getOrderLiveDeliveryStatus(LiveOrder order) {
        Map<String, Object> map = new HashMap<>();
        Long dfAccountId = getSFAccountIndex(order.getOrderId());
        map.put("orderNumber", order.getOrderCode());
        map.put("mailNumber", order.getDeliverySn());
        try {
            String response = client.execute(RequestUrlEnum.ORDER_DELIVERY_STATUS, map, dfAccountId);
            if (StringUtils.isBlank(response)) {
                return;
            }
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            if ("运单不存在".equals(dfApiResponse.getMsg())) {
                //查看原来物流状态
                cancelOrderLive(order);
                log.info("代服管家 getOrderDeliveryStatus: {}", response);
                return;
            }
            //3.处理请求结果
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                String jsonString = JSON.toJSONString(dfApiResponse.getResult());
                DFOrderStatusResultRequest temp = JSON.parseObject(jsonString, DFOrderStatusResultRequest.class);
                //0待揽收 1已揽收 2运输中 3派送中 4异常件 5退回件 6退回签收 7转寄件 8作废件 9已签收 10 已取消
                Integer deliveryStatus = 0;
                String stateEx = "0";
                LiveOrder liveOrderMap = new LiveOrder();
                liveOrderMap.setOrderId(order.getOrderId());
                Integer status = temp.getStatus();
                switch (status) {
                    case 0:
                    case 1:
                    case 2:
                        deliveryStatus = status;
                        stateEx = status.toString();
                        break;
                    case 3:
                        deliveryStatus = 2;
                        stateEx = "202";
                        break;
                    case 4:
                        deliveryStatus = status;
                        stateEx = status.toString();
                        break;
                    case 5:
                        deliveryStatus = 4;
                        stateEx = "407";
                        break;
                    case 6:
                        deliveryStatus = status;
                        stateEx = "406";
                        break;
                    case 9:
                        deliveryStatus = 3;
                        stateEx = "301";
                        break;
                    case 10:
                        String mailNumber = temp.getMailNumber();
                        List<LiveOrder> liveOrders = liveOrderMapper.selectLiveOrderList(new LiveOrder() {{
                            setDeliverySn(mailNumber);
                        }});
                        if (liveOrders != null && !liveOrders.isEmpty()) {
                            liveOrders.forEach(tempOrder -> {
                                cancelOrderLive(tempOrder);
                                log.info("代服管家 订单取消成功: {}", response);
                            });
                        }
                        break;
                }
                liveOrderMap.setDeliveryStatus(deliveryStatus);
                liveOrderMap.setDeliveryType(stateEx);
                liveOrderMapper.updateLiveOrder(liveOrderMap);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public ErpOrderQueryResponse batchGetLiveOrder(List<LiveOrder> orderList) {
        ErpOrderQueryResponse response = new ErpOrderQueryResponse();
        response.setOrders(Collections.emptyList());
        response.setSuccess(true);
        return response;
    }

    private void cancelOrderLive(LiveOrder order) {
        Integer deliveryStatus = order.getDeliveryStatus();
        if (deliveryStatus == null || deliveryStatus == 0) {
            //没有物流信息
            //修改订单状态 方便后续重新发货
            order.setStatus(1);
            order.setExtendOrderId("");
            order.setDeliverySn("");
            liveOrderMapper.updateLiveOrder(order);
        } else {
            //有物流信息->售后处理
            //取消订单
            // TODO: 实现直播订单退款逻辑
        }
        FsStoreOrderDf df = new FsStoreOrderDf();
        df.setOrderId(order.getOrderId());
        df.setStatus(2);
        df.setUpdateTime(new Date());
        fsStoreOrderDfMapper.updateFsStoreOrderDf(df);
    }

    private void cancelOrder(FsStoreOrder order) {
        Integer deliveryStatus = order.getDeliveryStatus();
        if (deliveryStatus == null || deliveryStatus == 0) {
            //没有物流信息
            //修改订单状态 方便后续重新发货
            order.setStatus(FsStoreOrderStatusEnum.STATUS_2.getValue());
            order.setExtendOrderId("");
            order.setDeliverySn("");
            fsStoreOrderMapper.updateFsStoreOrder(order);
            fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.UPDATE_ORDER_DF.getValue(),
                    "运单不存在," + FsStoreOrderLogEnum.UPDATE_ORDER_DF.getDesc());
        } else {
            //有物流信息->售后处理
            //取消订单
            FsStoreOrderSalesParam afterSalesParam = new FsStoreOrderSalesParam();
            afterSalesParam.setOrderId(order.getOrderId());
            afterSalesParam.setReasons("代服管家取消订单");
            afterSalesParam.setOperator("代服管家");
            fsStoreOrderService.afterSales(afterSalesParam);
            fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.REFUND_ORDER_DF.getValue(),
                    "运单不存在," + FsStoreOrderLogEnum.REFUND_ORDER_DF.getDesc());
        }
        FsStoreOrderDf df = new FsStoreOrderDf();
        df.setOrderId(order.getOrderId());
        df.setStatus(2);
        df.setUpdateTime(new Date());
        fsStoreOrderDfMapper.updateFsStoreOrderDf(df);
    }

    @Autowired
    private IFsIntegralOrderService integralOrderService;
    /**
     * 积分订单商品取消订单逻辑
     * */
    private void cancelOrder(FsIntegralOrder order) {
        //进入这个方法代表查询不到物流信息
        Integer deliveryStatus = order.getDeliveryStatus();
        //这个if进入代表调用代服创建运单失败，修改推送标识，由定时任务重新推送erp
        if (deliveryStatus == null || deliveryStatus == 0) {
            log.info("推送失败积分订单id：{}",order.getOrderId());
            //没有物流信息
            //修改订单状态 方便后续重新发货，让机器重新去
            order.setStatus(1);//设置待发货状态
            order.setDeliverySn("");
            integralOrderMapper.updateById(order);
            fsIntegralOrderLogsMapper.insert(FsIntegralOrderLogs.builder().orderId(order.getOrderId()).changeType(FsStoreOrderLogEnum.UPDATE_ORDER_DF.getValue()).changeMessage("运单不存在," + FsStoreOrderLogEnum.UPDATE_ORDER_DF.getDesc()).build());
        } else {
            log.info("积分订单物流被取消，退款积分订单{}",order.getOrderCode());
            //以前查询到过物流信息，现在查不到，物流被人为取消
            integralOrderService.mandatoryRefunds(order.getOrderCode());
            fsIntegralOrderLogsMapper.insert(FsIntegralOrderLogs.builder().orderId(order.getOrderId()).changeType(FsStoreOrderLogEnum.REFUND_ORDER_DF.getValue()).changeMessage("运单不存在," + FsStoreOrderLogEnum.REFUND_ORDER_DF.getDesc()).build());
        }
        log.info("取消订单代服记录更新id{}",order.getOrderCode());
        FsIntegralOrderDf df = new FsIntegralOrderDf();
        df.setOrderId(order.getOrderId());
        df.setStatus(2);
        df.setIsPush(0);
        integralOrderDfMapper.updateById(df);
    }

    private void cancelOrderScrm(FsStoreOrderScrm order) {
        Integer deliveryStatus = order.getDeliveryStatus();
        if (deliveryStatus == null || deliveryStatus == 0) {
            //没有物流信息
            //修改订单状态 方便后续重新发货
            order.setStatus(OrderInfoEnum.STATUS_1.getValue());
            order.setExtendOrderId("");
            order.setDeliveryId("");
            fsStoreOrderScrmMapper.updateFsStoreOrder(order);
            fsStoreOrderScrmLogsService.create(order.getId(), OrderLogEnum.UPDATE_ORDER_DF.getValue(),
                    "运单不存在," + OrderLogEnum.UPDATE_ORDER_DF.getDesc());
        } else {
            //有物流信息->售后处理
            //取消订单
            FsStoreAfterSalesParam afterSalesParam = new FsStoreAfterSalesParam();
//            afterSalesParam.setOrderId(order.getId());
//            afterSalesParam.setOrderCode(order.getOrderCode());
//            afterSalesParam.setReasons("代服管家取消订单");
//            afterSalesParam.setOperator("代服管家");
//            fsStoreOrderScrmService.afterSales(afterSalesParam);
            fsStoreOrderScrmService.refundOrderMoney(order.getId());
            fsStoreOrderScrmLogsService.create(order.getId(), OrderLogEnum.REFUND_ORDER_DF.getValue(),
                    "运单不存在," + OrderLogEnum.REFUND_ORDER_DF.getDesc());
        }
        FsStoreOrderDf df = new FsStoreOrderDf();
        df.setOrderId(order.getId());
        df.setStatus(2);
        df.setUpdateTime(new Date());
        fsStoreOrderDfMapper.updateFsStoreOrderDf(df);
    }

    /**
     * 获取erp推送参数
     *
     * @param order 订单参数
     * @return
     */
    private ErpOrderResponse getScrmErpOrderResponse(ErpOrder order) {

        FsStoreOrderScrm fsStoreOrder = fsStoreOrderScrmMapper.selectFsStoreOrderByOrderCode(order.getPlatform_code());
        if (fsStoreOrder == null) {
            return null;
        }
        Long dfAccountId = getSFAccountIndex(fsStoreOrder.getId());
        //1.获取请求参数
        ExternalOrderRequestVo vo = getCreateScrmOrderRequestParam(order, fsStoreOrder, dfAccountId);
        if (vo == null) {
            return null;
        }
        try {
            Map<String, Object> map = JSON.parseObject(JSON.toJSONString(vo), Map.class);
            //2.请求
            log.info("开始推送订单,参数: {}", JSON.toJSONString(map));
            String response = client.execute(RequestUrlEnum.CREAT_ORDER, map, dfAccountId);
            if (StringUtils.isBlank(response)) {
                return new ErpOrderResponse();
            }
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            //3.处理请求结果
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                //存储订单推送用的哪个账户
                FsStoreOrderDf df = addDfOrderScrm(fsStoreOrder, dfAccountId);
                log.info("订单推送成功: {}", response);
                //可以回调 也可以查询订单
                Map<String, Object> orderResultQueryParam = new HashMap<>();
                orderResultQueryParam.put("orderNumber", order.getPlatform_code());
                orderResultQueryParam.put("exInterfaceType", df.getStatus());
                try {
                    getOrderScrmResult(orderResultQueryParam, dfAccountId);
                } catch (Exception e) {
                    log.info("推送订单完成，查询订单问题{}", e.getMessage());
                }
                ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
                erpOrderResponse.setCode(order.getPlatform_code());
                erpOrderResponse.setSuccess(true);
                return erpOrderResponse;
            } else {
                throw new RuntimeException(String.format("订单推送失败,原因: %s", dfApiResponse.getMsg()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ErpOrderResponse();
    }

    /**
     * 获取erp推送参数
     *
     * @param order 订单参数
     * @return
     */
    private ErpOrderResponse getErpOrderResponse(ErpOrder order) {

        FsStoreOrder fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(order.getPlatform_code());
        if (fsStoreOrder == null) {
            return null;
        }
        Long dfAccountId = getSFAccountIndex(fsStoreOrder.getOrderId());
        //1.获取请求参数
        ExternalOrderRequestVo vo = getCreateOrderRequestParam(order, fsStoreOrder, dfAccountId);
        if (vo == null) {
            return null;
        }
        try {
            Map<String, Object> map = JSON.parseObject(JSON.toJSONString(vo), Map.class);
            //2.请求
            log.info("开始推送订单,参数: {}", JSON.toJSONString(map));
            String response = client.execute(RequestUrlEnum.CREAT_ORDER, map, dfAccountId);
            if (StringUtils.isBlank(response)) {
                return new ErpOrderResponse();
            }
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            //3.处理请求结果
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                //存储订单推送用的哪个账户
                FsStoreOrderDf df = addDfOrder(fsStoreOrder, dfAccountId);
                log.info("订单推送成功: {}", response);
                //可以回调 也可以查询订单
                Map<String, Object> orderResultQueryParam = new HashMap<>();
                orderResultQueryParam.put("orderNumber", order.getPlatform_code());
                orderResultQueryParam.put("exInterfaceType", df.getStatus());
                try {
                    getOrderResult(orderResultQueryParam, dfAccountId);
                } catch (Exception e) {
                    log.info("推送订单完成，查询订单问题{}", e.getMessage());
                }
                ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
                erpOrderResponse.setCode(order.getPlatform_code());
                erpOrderResponse.setSuccess(true);
                return erpOrderResponse;
            } else {
                throw new RuntimeException(String.format("订单推送失败,原因: %s", dfApiResponse.getMsg()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ErpOrderResponse();
    }

    @Autowired
    private FsIntegralOrderMapper integralOrderMapper;

    private ErpOrderResponse getErpIntegralOrderResponse(ErpOrder order){
        FsIntegralOrder fsIntegralOrder = integralOrderMapper.selectOne(Wrappers.<FsIntegralOrder>lambdaQuery().eq(FsIntegralOrder::getOrderCode, order.getPlatform_code()));
        if (fsIntegralOrder == null) {
            return null;
        }
        Long dfAccountId = getSFAccountIndex(fsIntegralOrder.getOrderId());
        //1.获取请求参数
        ExternalOrderRequestVo vo = getCreateOrderRequestParam(order, fsIntegralOrder, dfAccountId);
        if (vo == null) {
            return null;
        }
        try {
            Map<String, Object> map = JSON.parseObject(JSON.toJSONString(vo), Map.class);
            //2.请求
            log.info("开始推送订单,参数: {}", JSON.toJSONString(map));
            String response = client.execute(RequestUrlEnum.CREAT_ORDER, map, dfAccountId);
            if (StringUtils.isBlank(response)) {
                return new ErpOrderResponse();
            }
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            //3.处理请求结果
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                //存储订单推送用的哪个账户
                FsIntegralOrderDf df = addDfOrder(fsIntegralOrder, dfAccountId);
                log.info("订单推送成功: {}", response);
                //可以回调 也可以查询订单
                Map<String, Object> orderResultQueryParam = new HashMap<>();
                orderResultQueryParam.put("orderNumber", order.getPlatform_code());
                orderResultQueryParam.put("exInterfaceType", df.getStatus());
                try {
                    getIntegralOrderResult(orderResultQueryParam, dfAccountId);
                } catch (Exception e) {
                    log.info("推送订单完成，查询订单问题{}", e.getMessage());
                }
                ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
                erpOrderResponse.setCode(order.getPlatform_code());
                erpOrderResponse.setSuccess(true);
                return erpOrderResponse;
            } else {
                throw new RuntimeException(String.format("订单推送失败,原因: %s", dfApiResponse.getMsg()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ErpOrderResponse();
    }

    private @NotNull FsStoreOrderDf addDfOrderScrm(FsStoreOrderScrm fsStoreOrder, Long dfAccountId) {
        FsStoreOrderDf df = new FsStoreOrderDf();
        df.setOrderId(fsStoreOrder.getId());
        df.setOrderCode(fsStoreOrder.getOrderCode());
        FsDfAccount dfAccount = fsDfAccountMapper.selectFsDfAccountById(dfAccountId);
        df.setAppKey(dfAccount.getDfAppKey());
        df.setAppSecret(dfAccount.getDfAppsecret());
        df.setLoginAccount(dfAccount.getLoginAccount());
        df.setMonthlyCard(dfAccount.getMonthlyCard());
        df.setExpressProductCode(dfAccount.getExpressProductCode());
        df.setTotalPrice(fsStoreOrder.getPayMoney());
        df.setPlatformPrice(fsStoreOrder.getPayPrice());
        df.setStatus(1);
        //查询是否存在
        FsStoreOrderDf temp = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(df.getOrderId());
        if (temp != null) {
            //修改
            df.setUpdateTime(DateUtils.getNowDate());
            fsStoreOrderDfMapper.updateFsStoreOrderDf(df);
        } else {
            df.setCreateTime(DateUtils.getNowDate());
            fsStoreOrderDfMapper.insertFsStoreOrderDf(df);
        }
        return df;
    }

    private @NotNull FsStoreOrderDf addDfOrder(FsStoreOrder fsStoreOrder, Long dfAccountId) {
        FsStoreOrderDf df = new FsStoreOrderDf();
        df.setOrderId(fsStoreOrder.getOrderId());
        df.setOrderCode(fsStoreOrder.getOrderCode());
        FsDfAccount dfAccount = fsDfAccountMapper.selectFsDfAccountById(dfAccountId);
        df.setAppKey(dfAccount.getDfAppKey());
        df.setAppSecret(dfAccount.getDfAppsecret());
        df.setLoginAccount(dfAccount.getLoginAccount());
        df.setMonthlyCard(dfAccount.getMonthlyCard());
        df.setExpressProductCode(dfAccount.getExpressProductCode());
        df.setTotalPrice(fsStoreOrder.getPayMoney());
        df.setPlatformPrice(fsStoreOrder.getPayPrice());
        df.setStatus(1);
        //查询是否存在
        FsStoreOrderDf temp = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(df.getOrderId());
        if (temp != null) {
            //修改
            df.setUpdateTime(DateUtils.getNowDate());
            fsStoreOrderDfMapper.updateFsStoreOrderDf(df);
        } else {
            df.setCreateTime(DateUtils.getNowDate());
            fsStoreOrderDfMapper.insertFsStoreOrderDf(df);
        }
        return df;
    }

    private @NotNull FsIntegralOrderDf addDfOrder(FsIntegralOrder fsIntegralOrder, Long dfAccountId){
//        FsStoreOrderDf df = new FsStoreOrderDf();
        FsIntegralOrderDf df = new FsIntegralOrderDf();
        df.setOrderId(fsIntegralOrder.getOrderId());
        df.setOrderCode(fsIntegralOrder.getOrderCode());
        FsDfAccount dfAccount = fsDfAccountMapper.selectFsDfAccountById(dfAccountId);
        df.setAppKey(dfAccount.getDfAppKey());
        df.setAppSecret(dfAccount.getDfAppsecret());
        df.setLoginAccount(dfAccount.getLoginAccount());
        df.setMonthlyCard(dfAccount.getMonthlyCard());
        df.setExpressProductCode(dfAccount.getExpressProductCode());
        df.setTotalPrice(fsIntegralOrder.getPayMoney());
//        df.setPlatformPrice(fsStoreOrder.getPayPrice());
        df.setPlatformPrice(BigDecimal.ZERO);
        df.setStatus(1);
        df.setIsPush(1);//已经创建过erp订单标识
        //查询是否存在
//        FsStoreOrderDf temp = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(df.getOrderId());
        FsIntegralOrderDf temp = integralOrderDfMapper.selectById(df.getOrderId());
        if (temp != null) {
            //修改
//            df.setUpdateTime(DateUtils.getNowDate());
//            fsStoreOrderDfMapper.updateFsStoreOrderDf(df);
            df.setUpdateTime(LocalDateTime.now());
            integralOrderDfMapper.updateById(df);
        } else {
            df.setUpdateTime(LocalDateTime.now());
            integralOrderDfMapper.insert(df);
        }
        return df;
    }

    /**
     * 通用erpOrderScrm获取创建订单参数
     *
     * @param order
     * @return
     */
    private ExternalOrderRequestVo getCreateScrmOrderRequestParam(ErpOrder order, FsStoreOrderScrm fsStoreOrder, Long dfAccountId) {
        ExternalOrderRequestVo vo = new ExternalOrderRequestVo();
        FsDfAccount dfAccount = fsDfAccountMapper.selectFsDfAccountById(dfAccountId);
        if (dfAccount == null) {
            return null;
        }
        String loginAccount = dfAccount.getLoginAccount();
        vo.setMonthlyCard(dfAccount.getMonthlyCard()); //月结卡号
        vo.setExpressProductCode(dfAccount.getExpressProductCode()); //物流产品编码


        vo.setLoginAccount(loginAccount); //代服系统登录账号
        String callBackUrl = dfAccount.getCallBackUrl();
        if (StringUtils.isNotBlank(callBackUrl)) {
            vo.setCallBackUrl(callBackUrl); //订单下单后异步通知地址
        }
        FsStoreOrderDf temp = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(fsStoreOrder.getId());
        if (temp != null) {
            vo.setParcelQuantity(temp.getParcelQuantity());//包裹数量
        }

        vo.setOrderNumber(order.getPlatform_code()); //订单号（不能重复）

        int orderPayMethod = 0;
        BigDecimal couponPrice = fsStoreOrder.getCouponPrice();
        if (couponPrice == null) {
            couponPrice = BigDecimal.ZERO;
        }

        if ("1".equals(fsStoreOrder.getPayType())) {
            //在线支付
            orderPayMethod = 1;
        } else { // 如果是线上付款
            orderPayMethod = 2;
            // 货到付款金额 = 订单剩余支付金额
            vo.setCollectingMoney(fsStoreOrder.getDeliveryPayMoney().doubleValue());
            vo.setCollectionCardNumber(dfAccount.getMonthlyCard()); // 就是月结账号
        }
        //订单付款方式 1:在线支付 2:货到付款
        //如果填了2，代收金额必须大于0，代收卡号必填
        vo.setOrderPayMethod(orderPayMethod);

        vo.setConsignmentNumber(Integer.valueOf(Math.toIntExact(fsStoreOrder.getTotalNum()))); //托寄物数量 必填

        vo.setBuyerMessage(fsStoreOrder.getRemark()); //买家留言

        vo.setSenderName(dfAccount.getSenderName()); //寄件人
        vo.setSenderPhone(dfAccount.getSenderPhone()); //寄件人手机
        vo.setSenderProvince(dfAccount.getSenderProvince());//寄件人省
        vo.setSenderCity(dfAccount.getSenderCity());//寄件人市
        vo.setSenderDistrict(dfAccount.getSenderDistrict());//寄件人区
        vo.setSenderAddress(dfAccount.getSenderAddress());//寄件人地址
        vo.setReceiverName(order.getReceiver_name());//收件人
        vo.setReceiverPhone(order.getReceiver_mobile()); //收件人手机
        vo.setReceiverTelephone(order.getReceiver_phone());//收件人电话 否
        vo.setReceiverProvince(order.getReceiver_province()); //收件人省
        vo.setReceiverCity(order.getReceiver_city()); //收件人市
        vo.setReceiverDistrict(order.getReceiver_district()); //收件人区
        vo.setReceiverAddress(order.getReceiver_address()); // 收件人地址
        vo.setExpressPayMethod(1); //物流付款方式 1:寄付月结 2:寄付现结 3:收方付 4:第三方付
        //订单sku集合
        StringBuilder consignmentStr = new StringBuilder();
        List<FsStoreOrderItemVO> items = fsStoreOrderItemScrmMapper.selectFsStoreOrderItemListByOrderId(fsStoreOrder.getId());
        if (items != null && !items.isEmpty()) {
            ArrayList<ExteriorOrderSkuVo> orderSkus = new ArrayList<>();
            items.forEach(item -> {
                ExteriorOrderSkuVo skuVo = new ExteriorOrderSkuVo();
                FsStoreProductScrm product = fsStoreProductScrmMapper.selectFsStoreProductById(item.getProductId());
                Asserts.check(ObjectUtils.isNotNull(product), "该产品不存在! 产品id: {} ", item.getProductId());
                skuVo.setProductName(product.getProductName()); //商品名称
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(item.getJsonInfo());
                skuVo.setSkuCode(jsonObject.getString("sku")); //sku编码
                String barCode = jsonObject.getString("barCode");
                if (StringUtils.isNotBlank(barCode)) {
                    skuVo.setProductCode(barCode); //商品编号
                } else {
                    skuVo.setProductCode(item.getProductId().toString()); //商品编号
                }
                skuVo.setAttributeNames(jsonObject.getString("sku")); //商品规格，格式：颜色：红色，尺寸：L码....以此类推
                skuVo.setProductNumber(Math.toIntExact(item.getNum())); //商品预定数量
                skuVo.setPrice(product.getPrice().doubleValue()); //商品单价

//                skuVo.setAdjustAmount(0d); //调整金额
                // 优惠
                skuVo.setSubAmount(product.getPrice().doubleValue() * item.getNum());

                //组装寄托物
                consignmentStr.append(product.getProductName()).append("*").append(item.getNum()).append(",");
                orderSkus.add(skuVo);
            });
            if (consignmentStr.length() > 0) {
                consignmentStr.deleteCharAt(consignmentStr.length() - 1);
            }
            if (consignmentStr.length() > 100) {
                consignmentStr.delete(consignmentStr.length() - 4, consignmentStr.length());
                consignmentStr.append("...");
            }
            vo.setOrderSkus(orderSkus);
            vo.setConsignment(consignmentStr.toString()); //寄托物 必填
        }
        return vo;
    }

    /**
     * 通用erpOrder获取创建订单参数
     *
     * @param order
     * @return
     */
    private ExternalOrderRequestVo getCreateOrderRequestParam(ErpOrder order, FsStoreOrder fsStoreOrder, Long dfAccountId) {
        ExternalOrderRequestVo vo = new ExternalOrderRequestVo();
        FsDfAccount dfAccount = fsDfAccountMapper.selectFsDfAccountById(dfAccountId);
        if (dfAccount == null) {
            return null;
        }
        String loginAccount = dfAccount.getLoginAccount();
        vo.setMonthlyCard(dfAccount.getMonthlyCard()); //月结卡号
        vo.setExpressProductCode(dfAccount.getExpressProductCode()); //物流产品编码


        vo.setLoginAccount(loginAccount); //代服系统登录账号
        String callBackUrl = dfAccount.getCallBackUrl();
        if (StringUtils.isNotBlank(callBackUrl)) {
            vo.setCallBackUrl(callBackUrl); //订单下单后异步通知地址
        }
        FsStoreOrderDf temp = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(fsStoreOrder.getOrderId());
        if (temp != null) {
            vo.setParcelQuantity(temp.getParcelQuantity());//包裹数量
        }

        vo.setOrderNumber(order.getPlatform_code()); //订单号（不能重复）

        int orderPayMethod = 0;
        BigDecimal couponPrice = fsStoreOrder.getCouponPrice();
        if (couponPrice == null) {
            couponPrice = BigDecimal.ZERO;
        }

        if (ObjectUtil.equal(1, fsStoreOrder.getPayType())) {
            //在线支付
            orderPayMethod = 1;
        } else { // 如果是线上付款
            orderPayMethod = 2;
            // 货到付款金额 = 订单剩余支付金额
            vo.setCollectingMoney(fsStoreOrder.getPayRemain().doubleValue());
            vo.setCollectionCardNumber(dfAccount.getMonthlyCard()); // 就是月结账号
        }
        //订单付款方式 1:在线支付 2:货到付款
        //如果填了2，代收金额必须大于0，代收卡号必填
        vo.setOrderPayMethod(orderPayMethod);

        vo.setConsignmentNumber(Integer.valueOf(Math.toIntExact(fsStoreOrder.getTotalNum()))); //托寄物数量 必填

        vo.setBuyerMessage(fsStoreOrder.getRemark()); //买家留言

        vo.setSenderName(dfAccount.getSenderName()); //寄件人
        vo.setSenderPhone(dfAccount.getSenderPhone()); //寄件人手机
        vo.setSenderProvince(dfAccount.getSenderProvince());//寄件人省
        vo.setSenderCity(dfAccount.getSenderCity());//寄件人市
        vo.setSenderDistrict(dfAccount.getSenderDistrict());//寄件人区
        vo.setSenderAddress(dfAccount.getSenderAddress());//寄件人地址
        vo.setReceiverName(order.getReceiver_name());//收件人
        vo.setReceiverPhone(order.getReceiver_mobile()); //收件人手机
        vo.setReceiverTelephone(order.getReceiver_phone());//收件人电话 否
        vo.setReceiverProvince(order.getReceiver_province()); //收件人省
        vo.setReceiverCity(order.getReceiver_city()); //收件人市
        vo.setReceiverDistrict(order.getReceiver_district()); //收件人区
        vo.setReceiverAddress(order.getReceiver_address()); // 收件人地址
        vo.setExpressPayMethod(1); //物流付款方式 1:寄付月结 2:寄付现结 3:收方付 4:第三方付
        //订单sku集合
        StringBuilder consignmentStr = new StringBuilder();
        List<FsStoreOrderItem> items = fsStoreOrderItemMapper.selectFsStoreOrderItemListByOrderId(fsStoreOrder.getOrderId());
        if (items != null && items.size() > 0) {
            ArrayList<ExteriorOrderSkuVo> orderSkus = new ArrayList<>();
            items.forEach(item -> {
                ExteriorOrderSkuVo skuVo = new ExteriorOrderSkuVo();
                FsStoreProduct product = fsStoreProductMapper.selectFsStoreProductById(item.getProductId());
                Asserts.check(ObjectUtils.isNotNull(product), "该产品不存在! 产品id: {} ", item.getProductId());
                skuVo.setProductName(product.getProductName()); //商品名称
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(item.getJsonInfo());
                skuVo.setSkuCode(jsonObject.getString("sku")); //sku编码
                skuVo.setProductCode(jsonObject.getString("barCode")); //商品编号
                skuVo.setAttributeNames(jsonObject.getString("sku")); //商品规格，格式：颜色：红色，尺寸：L码....以此类推
                skuVo.setProductNumber(Math.toIntExact(item.getNum())); //商品预定数量
                skuVo.setPrice(product.getPrice().doubleValue()); //商品单价

//                skuVo.setAdjustAmount(0d); //调整金额
                // 优惠
                skuVo.setSubAmount(product.getPrice().doubleValue() * item.getNum());

                //组装寄托物
                consignmentStr.append(product.getProductName()).append("*").append(item.getNum()).append(",");
                orderSkus.add(skuVo);
            });
            if (consignmentStr.length() > 0) {
                consignmentStr.deleteCharAt(consignmentStr.length() - 1);
            }
            if (consignmentStr.length() > 100) {
                consignmentStr.delete(consignmentStr.length() - 4, consignmentStr.length());
                consignmentStr.append("...");
            }
            vo.setOrderSkus(orderSkus);
            vo.setConsignment(consignmentStr.toString()); //寄托物 必填
        }
        return vo;
    }

    @Autowired
    private FsIntegralGoodsMapper fsIntegralGoodsMapper;

    private ExternalOrderRequestVo getCreateOrderRequestParam(ErpOrder order, FsIntegralOrder fsIntegralOrder, Long dfAccountId) {
        ExternalOrderRequestVo vo = new ExternalOrderRequestVo();
        FsDfAccount dfAccount = fsDfAccountMapper.selectFsDfAccountById(dfAccountId);
        if (dfAccount == null) {
            return null;
        }
        String loginAccount = dfAccount.getLoginAccount();
        vo.setMonthlyCard(dfAccount.getMonthlyCard()); //月结卡号
        vo.setExpressProductCode(dfAccount.getExpressProductCode()); //物流产品编码


        vo.setLoginAccount(loginAccount); //代服系统登录账号
        String callBackUrl = dfAccount.getCallBackUrl();
//        if (StringUtils.isNotBlank(callBackUrl)) {//TODO:到时候写完了回调接口这里写死或者放配置里面
//            vo.setCallBackUrl(callBackUrl); //订单下单后异步通知地址
//        }
//        FsStoreOrderDf temp = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(fsStoreOrder.getOrderId());
        FsIntegralOrderDf temp = integralOrderDfMapper.selectById(fsIntegralOrder.getOrderId());
        if (temp != null) {
            vo.setParcelQuantity(temp.getParcelQuantity());//包裹数量
        }

        vo.setOrderNumber(order.getPlatform_code()); //订单号（不能重复）

        int orderPayMethod = 1;//默认在线支付，这个只有积分支付
//        BigDecimal couponPrice = fsIntegralOrder.getCouponPrice();
//        if (couponPrice == null) {
        BigDecimal couponPrice = BigDecimal.ZERO;
//        }

//        if (ObjectUtil.equal(1, fsIntegralOrder.getPayType())) {
//            //在线支付
//            orderPayMethod = 1;
//        } else { // 如果是线上付款
//            orderPayMethod = 2;
//            // 货到付款金额 = 订单剩余支付金额
//            vo.setCollectingMoney(fsIntegralOrder.getPayRemain().doubleValue());
//            vo.setCollectionCardNumber(dfAccount.getMonthlyCard()); // 就是月结账号
//        }
        //订单付款方式 1:在线支付 2:货到付款
        //如果填了2，代收金额必须大于0，代收卡号必填
        vo.setOrderPayMethod(orderPayMethod);

//        vo.setConsignmentNumber(Integer.valueOf(Math.toIntExact(fsIntegralOrder.getTotalNum()))); //托寄物数量 必填
        vo.setConsignmentNumber(1);
        vo.setBuyerMessage(fsIntegralOrder.getRemark()); //买家留言

        vo.setSenderName(dfAccount.getSenderName()); //寄件人
        vo.setSenderPhone(dfAccount.getSenderPhone()); //寄件人手机
        vo.setSenderProvince(dfAccount.getSenderProvince());//寄件人省
        vo.setSenderCity(dfAccount.getSenderCity());//寄件人市
        vo.setSenderDistrict(dfAccount.getSenderDistrict());//寄件人区
        vo.setSenderAddress(dfAccount.getSenderAddress());//寄件人地址
        vo.setReceiverName(order.getReceiver_name());//收件人
        vo.setReceiverPhone(order.getReceiver_mobile()); //收件人手机
        vo.setReceiverTelephone(order.getReceiver_phone());//收件人电话 否
        vo.setReceiverProvince(order.getReceiver_province()); //收件人省
        vo.setReceiverCity(order.getReceiver_city()); //收件人市
        vo.setReceiverDistrict(order.getReceiver_district()); //收件人区
        vo.setReceiverAddress(order.getReceiver_address()); // 收件人地址
        vo.setExpressPayMethod(1); //物流付款方式 1:寄付月结 2:寄付现结 3:收方付 4:第三方付
        //订单sku集合
        StringBuilder consignmentStr = new StringBuilder();
//        List<FsStoreOrderItem> items = fsStoreOrderItemMapper.selectFsStoreOrderItemListByOrderId(fsStoreOrder.getOrderId());
        List<ErpOrderItem> items = order.getDetails();
        if (items != null && items.size() > 0) {
            ArrayList<ExteriorOrderSkuVo> orderSkus = new ArrayList<>();
            items.forEach(item -> {
                ExteriorOrderSkuVo skuVo = new ExteriorOrderSkuVo();
//                FsStoreProduct product = fsStoreProductMapper.selectFsStoreProductById(item.getProductId());
                FsIntegralGoods goods = fsIntegralGoodsMapper.selectFsIntegralGoodsByGoodsId(Convert.toLong(item.getOid()));
                Asserts.check(ObjectUtils.isNotNull(goods), "该产品不存在! 产品id: {} ", item.getOid());
                skuVo.setProductName(goods.getGoodsName()); //商品名称
//                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(item.getJsonInfo());
                skuVo.setSkuCode("默认"); //sku编码
                skuVo.setProductCode(goods.getBarCode()); //商品编号
                skuVo.setAttributeNames("默认"); //商品规格，格式：颜色：红色，尺寸：L码....以此类推
                skuVo.setProductNumber(Math.toIntExact(item.getQty())); //商品预定数量
                skuVo.setPrice(Convert.toDouble(item.getPrice())); //商品单价

//                skuVo.setAdjustAmount(0d); //调整金额
                // 优惠
                skuVo.setSubAmount(Convert.toDouble(item.getPrice()) * item.getQty());

                //组装寄托物
                consignmentStr.append(goods.getGoodsName()).append("*").append(item.getQty()).append(",");
                orderSkus.add(skuVo);
            });
            if (consignmentStr.length() > 0) {
                consignmentStr.deleteCharAt(consignmentStr.length() - 1);
            }
            if (consignmentStr.length() > 100) {
                consignmentStr.delete(consignmentStr.length() - 4, consignmentStr.length());
                consignmentStr.append("...");
            }
            vo.setOrderSkus(orderSkus);
            vo.setConsignment(consignmentStr.toString()); //寄托物 必填
        }
        return vo;
    }

    /**
     * 获取账户索引 后续添加规则
     *
     * @return
     */
    private Long getSFAccountIndex(Long orderId) {
        List<FsDfAccount> fsDfAccounts = fsDfAccountMapper.selectFsDfAccountList(null);
        if (orderId != null) {
            //查询是否选择erp账户
            FsStoreOrderDf temp = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(orderId);
            if (temp != null) {
                if (fsDfAccounts != null && !fsDfAccounts.isEmpty()) {
                    for (FsDfAccount fsDfAccount : fsDfAccounts) {
                        if (temp.getLoginAccount().equals(fsDfAccount.getLoginAccount())) {
                            return fsDfAccount.getId();
                        }
                    }
                }
                return null;
            }
        }
        if (fsDfAccounts != null && !fsDfAccounts.isEmpty()) {
            return fsDfAccounts.get(0).getId();
        } else {
            return null;
        }
    }

    private void getOrderResult(Map<String, Object> map, Long dfAccountId) {
        try {
            // 上游回调可能缺字段，避免直接 toString 触发 NPE
            Object exInterfaceType = map.get("exInterfaceType");
            String status = exInterfaceType != null ? exInterfaceType.toString() : "";
            log.info("开始查询订单结果,参数为: {}", JSON.toJSONString(map));
            String response = client.execute(RequestUrlEnum.ORDER_RESULT, map, dfAccountId);
            if (StringUtils.isBlank(response)) {
                return ;
            }
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                log.info("查询订单结果,结果: {}", JSON.toJSONString(dfApiResponse));
                Object result = dfApiResponse.getResult();
                if (result != null) {
                    String jsonString = JSON.toJSONString(result);
                    //下单
                    if ("1".equals(status)) {
                        //下单结果
                        BspOrderResponseWrapper bspOrderResponse = JSONUtil.toBean(jsonString, BspOrderResponseWrapper.class);
                        if (bspOrderResponse != null) {
                            String failMsg = bspOrderResponse.getFailMsg();
                            if (StringUtils.isNotBlank(failMsg)) {
                                if (failMsg.equals("暂未结果, 请稍后再查")) {
                                    return;
                                }
                                //下单失败 返回未推送状态
                                String orderNumber = bspOrderResponse.getOrderNumber();
                                try {
                                    rollBackOrder(orderNumber, failMsg);
                                } catch (Exception e) {
                                    log.info("{}订单获取运单失败，订单状态回滚失败，失败原因：{}，失败信息为：{}", orderNumber,e.getMessage(),failMsg);
                                }
                            } else {
                                setExpress(bspOrderResponse);
                            }
                        }
                    } else if ("2".equals(status)) {
                        //取消订单
                        DFCancelOrderResultResponse cancelResponse = JSONUtil.toBean(jsonString, DFCancelOrderResultResponse.class);
                        if (cancelResponse != null) {
                            if (cancelResponse.getIsCancelSuss() == 1) {
                                log.info("查询订单取消成功,返回结果{}", JSON.toJSONString(cancelResponse));
                            } else {
                                log.info("查询订单取消失败,返回结果{}", JSON.toJSONString(cancelResponse));
                            }
                        }
                    }
                }

            } else {
                log.info(String.format("查询订单失败,原因: %s", dfApiResponse.getMsg()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void getIntegralOrderResult(Map<String, Object> map, Long dfAccountId){
        try {
            // 上游回调可能缺字段，避免直接 toString 触发 NPE
            Object exInterfaceType = map.get("exInterfaceType");
            String status = exInterfaceType != null ? exInterfaceType.toString() : "";
            log.info("开始查询订单结果,参数为: {}", JSON.toJSONString(map));
            String response = client.execute(RequestUrlEnum.ORDER_RESULT, map, dfAccountId);
            if (StringUtils.isBlank(response)) {
                return;
            }
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                log.info("查询订单结果,结果: {}", JSON.toJSONString(dfApiResponse));
                Object result = dfApiResponse.getResult();
                if (result != null) {
                    String jsonString = JSON.toJSONString(result);
                    //下单
                    if ("1".equals(status)) {
                        //下单结果
                        BspOrderResponseWrapper bspOrderResponse = JSONUtil.toBean(jsonString, BspOrderResponseWrapper.class);
                        if (bspOrderResponse != null) {
                            String failMsg = bspOrderResponse.getFailMsg();
                            if (StringUtils.isNotBlank(failMsg)) {
                                if (failMsg.equals("暂未结果, 请稍后再查")) {
                                    return;
                                }
                                //下单失败 返回未推送状态
                                String orderNumber = bspOrderResponse.getOrderNumber();
                                try {
                                    rollBackIntegralOrder(orderNumber, failMsg);
                                } catch (Exception e) {
                                    log.info("{}订单获取运单失败，订单状态回滚失败，失败原因：{}，失败信息为：{}", orderNumber,e.getMessage(),failMsg);
                                }
                            } else {
                                setIntegralExpress(bspOrderResponse);
                            }
                        }
                    } else if ("2".equals(status)) {
                        //取消订单
                        DFCancelOrderResultResponse cancelResponse = JSONUtil.toBean(jsonString, DFCancelOrderResultResponse.class);
                        if (cancelResponse != null) {
                            if (cancelResponse.getIsCancelSuss() == 1) {
                                log.info("查询订单取消成功,返回结果{}", JSON.toJSONString(cancelResponse));
                            } else {
                                log.info("查询订单取消失败,返回结果{}", JSON.toJSONString(cancelResponse));
                            }
                        }
                    }
                }

            } else {
                log.info(String.format("查询订单失败,原因: %s", dfApiResponse.getMsg()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void getOrderScrmResult(Map<String, Object> map, Long dfAccountId) {
        try {
            // 上游回调可能缺字段，避免直接 toString 触发 NPE
            Object exInterfaceType = map.get("exInterfaceType");
            String status = exInterfaceType != null ? exInterfaceType.toString() : "";
            log.info("开始查询订单结果,参数为: {}", JSON.toJSONString(map));
            String response = client.execute(RequestUrlEnum.ORDER_RESULT, map, dfAccountId);
            if (StringUtils.isBlank(response)) {
                return;
            }
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                log.info("查询订单结果,结果: {}", JSON.toJSONString(dfApiResponse));
                Object result = dfApiResponse.getResult();
                if (result != null) {
                    String jsonString = JSON.toJSONString(result);
                    //下单
                    if ("1".equals(status)) {
                        //下单结果
                        BspOrderResponseWrapper bspOrderResponse = JSONUtil.toBean(jsonString, BspOrderResponseWrapper.class);
                        if (bspOrderResponse != null) {
                            String failMsg = bspOrderResponse.getFailMsg();
                            if (StringUtils.isNotBlank(failMsg)) {
                                if (failMsg.equals("暂未结果, 请稍后再查")) {
                                    return;
                                }
                                //下单失败 返回未推送状态
                                String orderNumber = bspOrderResponse.getOrderNumber();
                                try {
                                    rollBackOrderScrm(orderNumber, failMsg);
                                } catch (Exception e) {
                                    log.info("{}订单获取运单失败，订单状态回滚失败，失败原因：{}，失败信息为：{}", orderNumber,e.getMessage(),failMsg);
                                }
                            } else {
                                setExpressScrm(bspOrderResponse);
                            }
                        }
                    } else if ("2".equals(status)) {
                        //取消订单
                        DFCancelOrderResultResponse cancelResponse = JSONUtil.toBean(jsonString, DFCancelOrderResultResponse.class);
                        if (cancelResponse != null) {
                            if (cancelResponse.getIsCancelSuss() == 1) {
                                log.info("查询订单取消成功,返回结果{}", JSON.toJSONString(cancelResponse));
                            } else {
                                log.info("查询订单取消失败,返回结果{}", JSON.toJSONString(cancelResponse));
                            }
                        }
                    }
                }

            } else {
                log.info(String.format("查询订单失败,原因: %s", dfApiResponse.getMsg()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void rollBackOrder(String orderNumber, String failMsg) {
        FsStoreOrder fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(orderNumber);
        FsStoreOrder tempOrder = new FsStoreOrder();
        tempOrder.setOrderId(fsStoreOrder.getOrderId());
        tempOrder.setExtendOrderId("");
        fsStoreOrderMapper.updateFsStoreOrder(tempOrder);
        FsStoreOrderDf df = new FsStoreOrderDf();
        df.setOrderId(fsStoreOrder.getOrderId());
        df.setStatus(0); //回到默认
        df.setFailMsg(failMsg); //失败消息
        df.setUpdateTime(new Date());
        fsStoreOrderDfMapper.updateFsStoreOrderDf(df);
        log.info("{}订单获取运单失败，失败信息为：{}", orderNumber,failMsg);
        //推送失败消息
    }

    private void rollBackIntegralOrder(String orderNumber, String failMsg){
        //积分的回退不用修改扩展id，定时任务准备使用df表的ispush字段来查询
        FsIntegralOrderDf df = integralOrderDfMapper.selectOne(Wrappers.<FsIntegralOrderDf>lambdaQuery().eq(FsIntegralOrderDf::getOrderCode, orderNumber));
        df.setStatus(0); //回到默认
        df.setFailMsg(failMsg); //失败消息
        df.setUpdateTime(LocalDateTime.now());
        df.setIsPush(0);
        integralOrderDfMapper.updateById(df);
        log.info("{}订单获取运单失败，失败信息为：{}", orderNumber,failMsg);
    }

    private void rollBackOrderScrm(String orderNumber, String failMsg) {
        FsStoreOrderScrm fsStoreOrder = fsStoreOrderScrmMapper.selectFsStoreOrderByOrderCode(orderNumber);
        FsStoreOrderScrm tempOrder = new FsStoreOrderScrm();
        tempOrder.setId(fsStoreOrder.getId());
        tempOrder.setExtendOrderId("");
        tempOrder.setDeliveryId("");
        fsStoreOrderScrmMapper.updateFsStoreOrder(tempOrder);
        FsStoreOrderDf df = new FsStoreOrderDf();
        df.setOrderId(fsStoreOrder.getId());
        df.setStatus(OrderInfoEnum.STATUS_1.getValue()); //回到默认
        df.setFailMsg(failMsg); //失败消息
        df.setUpdateTime(new Date());
        fsStoreOrderDfMapper.updateFsStoreOrderDf(df);
        log.info("{}订单获取运单失败，失败信息为：{}", orderNumber,failMsg);
        //推送失败消息
    }

    /**
     * 顺丰会有自己的轨迹推送 不使用快递鸟(代服务管家设置推送地址)
     *
     * @param bspResponse
     */
    private void setExpress(BspOrderResponseWrapper bspResponse) {
        String orderNumber = bspResponse.getOrderNumber();
        //快递单号
        String mailNumber = bspResponse.getMailNumber();
        //快递名字
        BspOrderResponse bspOrderResponse = bspResponse.getBspResponse();
        if (bspOrderResponse != null) {
            AtomicBoolean flag = new AtomicBoolean(false);
            List<OrderResponse> list = bspOrderResponse.getBody();
            if (list != null && !list.isEmpty()) {
                for (OrderResponse orderResponse : list) {
                    List<RlsInfo> rlsInfo = orderResponse.getRlsInfo();
                    if (rlsInfo != null && !rlsInfo.isEmpty()) {
                        for (RlsInfo info : rlsInfo) {
                            List<RlsDetail> rlsDetails = info.getRlsDetail();
                            if (rlsDetails != null && !rlsDetails.isEmpty()) {
                                for (RlsDetail rlsDetail : rlsDetails) {
                                    String proCode = rlsDetail.getProCode();
                                    if (StringUtils.isNotBlank(proCode)) {
                                        FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(orderNumber);
                                        if (order != null && order.getStatus() == 2) {
                                            order.setDeliverySn(mailNumber);
                                            order.setDeliveryName(proCode);
                                            order.setDeliveryCode("SF");
                                            order.setStatus(3);
                                            order.setDeliverySendTime(DateUtils.getNowDate()); //更新发货时间
                                            fsStoreOrderMapper.updateFsStoreOrder(order);
                                            fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.DELIVERY_GOODS.getValue(), FsStoreOrderLogEnum.DELIVERY_GOODS.getDesc());
                                            redisCache.deleteObject(DELIVERY+":"+order.getExtendOrderId());
                                            if (order.getCompanyId() != null && order.getCompanyId() > 0) {
                                                companyService.subtractCompanyMoney(order);
                                            }

//                                            FsStore store = fsStoreMapper.selectFsStoreByStoreId(order.getStoreId());
//                                            //订阅物流回调
//                                            String lastFourNumber = "";
//                                            if (order.getDeliveryCode().equals(ShipperCodeEnum.SF.getValue())) {
//                                                if (store != null && store.getSendPhone() != null) {
//                                                    lastFourNumber = store.getSendPhone();
//                                                } else {
//                                                    lastFourNumber = order.getUserPhone();
//                                                }
//                                                if (lastFourNumber.length() == 11) {
//                                                    lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
//                                                }
//                                            }
//                                            expressService.subscribeEspress(order.getOrderCode(), order.getDeliveryCode(), order.getDeliverySn(), lastFourNumber);
                                            flag.set(true);
                                        }
                                        break;
                                    }
                                }

                            }
                            if (flag.get()) {
                                break;
                            }
                        }

                    }
                    if (flag.get()) {
                        break;
                    }
                }
            }
        }
    }

    private void setIntegralExpress(BspOrderResponseWrapper bspResponse){
        String orderNumber = bspResponse.getOrderNumber();
        //快递单号
        String mailNumber = bspResponse.getMailNumber();
        //快递名字
        BspOrderResponse bspOrderResponse = bspResponse.getBspResponse();
        if (bspOrderResponse != null) {
            AtomicBoolean flag = new AtomicBoolean(false);
            List<OrderResponse> list = bspOrderResponse.getBody();
            if (list != null && !list.isEmpty()) {
                for (OrderResponse orderResponse : list) {
                    List<RlsInfo> rlsInfo = orderResponse.getRlsInfo();
                    if (rlsInfo != null && !rlsInfo.isEmpty()) {
                        for (RlsInfo info : rlsInfo) {
                            List<RlsDetail> rlsDetails = info.getRlsDetail();
                            if (rlsDetails != null && !rlsDetails.isEmpty()) {
                                for (RlsDetail rlsDetail : rlsDetails) {
                                    String proCode = rlsDetail.getProCode();
                                    if (StringUtils.isNotBlank(proCode)) {
//                                        FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(orderNumber);
                                        FsIntegralOrder order = fsIntegralOrderMapper.selectOne(Wrappers.<FsIntegralOrder>lambdaQuery().eq(FsIntegralOrder::getOrderCode, orderNumber));
                                        if (order != null && order.getStatus() == 1) {//等于待发货
                                            order.setDeliverySn(mailNumber);
                                            order.setDeliveryName(proCode);
                                            order.setDeliveryCode("SF");
                                            order.setStatus(2);//修改积分订单为待收货状态
                                            order.setDeliveryTime(DateUtils.getNowDate()); //更新发货时间
                                            fsIntegralOrderMapper.updateById(order);
                                            //订单发货日志
                                            fsIntegralOrderLogsMapper.insert(FsIntegralOrderLogs.builder().orderId(order.getOrderId()).changeType("delivery_goods").changeMessage(FsStoreOrderLogEnum.DELIVERY_GOODS.getDesc()).build());
//                                            fsStoreOrderLogsService.create(order.getOrderId(), FsStoreOrderLogEnum.DELIVERY_GOODS.getValue(), FsStoreOrderLogEnum.DELIVERY_GOODS.getDesc());
//                                            redisCache.deleteObject(DELIVERY+":"+order.getOrderCode());
//                                            if (order.getCompanyId() != null && order.getCompanyId() > 0) {
//                                                companyService.subtractCompanyMoney(order);
//                                            }积分商品没有这个
                                            flag.set(true);
                                        }
                                        break;
                                    }
                                }

                            }
                            if (flag.get()) {
                                break;
                            }
                        }

                    }
                    if (flag.get()) {
                        break;
                    }
                }
            }
        }
    }

    /**
     * 顺丰会有自己的轨迹推送 不使用快递鸟(代服务管家设置推送地址)
     *
     * @param bspResponse
     */
    private void setExpressScrm(BspOrderResponseWrapper bspResponse) {
        String orderNumber = bspResponse.getOrderNumber();
        //快递单号
        String mailNumber = bspResponse.getMailNumber();
        //快递名字
        BspOrderResponse bspOrderResponse = bspResponse.getBspResponse();
        if (bspOrderResponse != null) {
            AtomicBoolean flag = new AtomicBoolean(false);
            List<OrderResponse> list = bspOrderResponse.getBody();
            if (list != null && !list.isEmpty()) {
                for (OrderResponse orderResponse : list) {
                    List<RlsInfo> rlsInfo = orderResponse.getRlsInfo();
                    if (rlsInfo != null && !rlsInfo.isEmpty()) {
                        for (RlsInfo info : rlsInfo) {
                            List<RlsDetail> rlsDetails = info.getRlsDetail();
                            if (rlsDetails != null && !rlsDetails.isEmpty()) {
                                for (RlsDetail rlsDetail : rlsDetails) {
                                    String proCode = rlsDetail.getProCode();
                                    if (StringUtils.isNotBlank(proCode)) {
                                        FsStoreOrderScrm order = fsStoreOrderScrmMapper.selectFsStoreOrderByOrderCode(orderNumber);
                                        if (order != null && order.getStatus() == OrderInfoEnum.STATUS_1.getValue()) {
                                            FsExpressScrm express = expressScrmService.selectFsExpressByOmsCode(order.getDeliveryCode());
                                            if (express != null) {
                                                order.setDeliveryName(proCode);
                                                order.setDeliverySn(express.getOmsCode());
                                            }
                                            order.setStatus(OrderInfoEnum.STATUS_2.getValue());
                                            order.setDeliveryId(mailNumber);
                                            order.setDeliverySendTime(new Date());

                                            fsStoreOrderScrmMapper.updateFsStoreOrder(order);
                                            fsStoreOrderScrmLogsService.create(order.getId(), FsStoreOrderLogEnum.DELIVERY_GOODS.getValue(), FsStoreOrderLogEnum.DELIVERY_GOODS.getDesc());
                                            redisCache.deleteObject(DELIVERY+":"+order.getExtendOrderId());
                                            //订阅物流回调
//                                            String lastFourNumber = "";
//                                            if (order.getDeliverySn().equals(ShipperCodeEnum.SF.getValue())) {
//                                                lastFourNumber = order.getUserPhone();
//                                                if (lastFourNumber.length() == 11) {
//                                                    lastFourNumber = StrUtil.sub(lastFourNumber, lastFourNumber.length(), -4);
//                                                }
//                                            }
//                                            expressService.subscribeEspress(order.getOrderCode(), order.getDeliverySn(), order.getDeliveryId(), lastFourNumber);

//                                            TemplateBean templateBean = TemplateBean.builder()
//                                                    .orderId(order.getId().toString())
//                                                    .orderCode(order.getOrderCode().toString())
//                                                    .deliveryId(order.getDeliveryId())
//                                                    .deliveryName(order.getDeliveryName())
//                                                    .userId(order.getUserId())
//                                                    .templateType(TemplateListenEnum.TYPE_2.getValue())
//                                                    .build();
//                                            publisher.publishEvent(new TemplateEvent(this, templateBean));
                                        }
                                        flag.set(true);
                                    }
                                    break;
                                }
                            }

                        }
                        if (flag.get()) {
                            break;
                        }
                    }

                }
            }
        }
    }

    private ExternalOrderRequestVo getCreateLiveOrderRequestParam(ErpOrder order, LiveOrder liveOrder, Long dfAccountId) {
        ExternalOrderRequestVo vo = new ExternalOrderRequestVo();
        FsDfAccount dfAccount = fsDfAccountMapper.selectFsDfAccountById(dfAccountId);
        if (dfAccount == null) {
            return null;
        }
        String loginAccount = dfAccount.getLoginAccount();
        vo.setMonthlyCard(dfAccount.getMonthlyCard());
        vo.setExpressProductCode(dfAccount.getExpressProductCode());
        vo.setLoginAccount(loginAccount);
        String callBackUrl = dfAccount.getCallBackUrl();
        if (StringUtils.isNotBlank(callBackUrl)) {
            vo.setCallBackUrl(callBackUrl);
        }
        FsStoreOrderDf temp = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(liveOrder.getOrderId());
        if (temp != null) {
            vo.setParcelQuantity(temp.getParcelQuantity());
        }
        vo.setOrderNumber(order.getPlatform_code());
        int orderPayMethod = 0;
        BigDecimal couponPrice = liveOrder.getCouponPrice();
        if (couponPrice == null) {
            couponPrice = BigDecimal.ZERO;
        }
        if ("1".equals(liveOrder.getPayType())) {
            orderPayMethod = 1;
        } else {
            orderPayMethod = 2;
            vo.setCollectingMoney(liveOrder.getDeliveryPayMoney().doubleValue());
            vo.setCollectionCardNumber(dfAccount.getMonthlyCard());
        }
        vo.setOrderPayMethod(orderPayMethod);
        vo.setConsignmentNumber(Integer.valueOf(liveOrder.getTotalNum()));
        vo.setBuyerMessage(liveOrder.getRemark());
        vo.setSenderName(dfAccount.getSenderName());
        vo.setSenderPhone(dfAccount.getSenderPhone());
        vo.setSenderProvince(dfAccount.getSenderProvince());
        vo.setSenderCity(dfAccount.getSenderCity());
        vo.setSenderDistrict(dfAccount.getSenderDistrict());
        vo.setSenderAddress(dfAccount.getSenderAddress());
        vo.setReceiverName(order.getReceiver_name());
        vo.setReceiverPhone(order.getReceiver_mobile());
        vo.setReceiverTelephone(order.getReceiver_phone());
        vo.setReceiverProvince(order.getReceiver_province());
        vo.setReceiverCity(order.getReceiver_city());
        vo.setReceiverDistrict(order.getReceiver_district());
        vo.setReceiverAddress(order.getReceiver_address());
        vo.setExpressPayMethod(1);
        StringBuilder consignmentStr = new StringBuilder();
        List<LiveOrderItem> items = liveOrderItemMapper.selectLiveOrderItemByOrderId(liveOrder.getOrderId());
        if (items != null && !items.isEmpty()) {
            ArrayList<ExteriorOrderSkuVo> orderSkus = new ArrayList<>();
            items.forEach(item -> {
                ExteriorOrderSkuVo skuVo = new ExteriorOrderSkuVo();
                FsStoreProductScrm product = fsStoreProductScrmMapper.selectFsStoreProductById(item.getProductId());
                Asserts.check(ObjectUtils.isNotNull(product), "该产品不存在! 产品id: {} ", item.getProductId());
                skuVo.setProductName(product.getProductName());
                com.alibaba.fastjson.JSONObject jsonObject = JSON.parseObject(item.getJsonInfo());
                skuVo.setSkuCode(jsonObject.getString("sku"));
                String barCode = jsonObject.getString("barCode");
                if (StringUtils.isNotBlank(barCode)) {
                    skuVo.setProductCode(barCode);
                } else {
                    skuVo.setProductCode(item.getProductId().toString());
                }
                skuVo.setAttributeNames(jsonObject.getString("sku"));
                skuVo.setProductNumber(Math.toIntExact(item.getNum()));
                skuVo.setPrice(product.getPrice().doubleValue());
                skuVo.setSubAmount(product.getPrice().doubleValue() * item.getNum());
                consignmentStr.append(product.getProductName()).append("*").append(item.getNum()).append(",");
                orderSkus.add(skuVo);
            });
            if (consignmentStr.length() > 0) {
                consignmentStr.deleteCharAt(consignmentStr.length() - 1);
            }
            if (consignmentStr.length() > 100) {
                consignmentStr.delete(consignmentStr.length() - 4, consignmentStr.length());
                consignmentStr.append("...");
            }
            vo.setOrderSkus(orderSkus);
            vo.setConsignment(consignmentStr.toString());
        }
        return vo;
    }

    private FsStoreOrderDf addDfOrderLive(LiveOrder liveOrder, Long dfAccountId) {
        FsStoreOrderDf df = new FsStoreOrderDf();
        df.setOrderId(liveOrder.getOrderId());
        df.setOrderCode(liveOrder.getOrderCode());
        FsDfAccount dfAccount = fsDfAccountMapper.selectFsDfAccountById(dfAccountId);
        df.setAppKey(dfAccount.getDfAppKey());
        df.setAppSecret(dfAccount.getDfAppsecret());
        df.setLoginAccount(dfAccount.getLoginAccount());
        df.setMonthlyCard(dfAccount.getMonthlyCard());
        df.setExpressProductCode(dfAccount.getExpressProductCode());
        df.setTotalPrice(liveOrder.getPayMoney());
        df.setPlatformPrice(liveOrder.getPayPrice());
        df.setStatus(1);
        FsStoreOrderDf temp = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(df.getOrderId());
        if (temp != null) {
            df.setUpdateTime(DateUtils.getNowDate());
            fsStoreOrderDfMapper.updateFsStoreOrderDf(df);
        } else {
            df.setCreateTime(DateUtils.getNowDate());
            fsStoreOrderDfMapper.insertFsStoreOrderDf(df);
        }
        return df;
    }

    private void getOrderLiveResult(Map<String, Object> map, Long dfAccountId) {
        try {
            // 上游回调可能缺字段，避免直接 toString 触发 NPE
            Object exInterfaceType = map.get("exInterfaceType");
            String status = exInterfaceType != null ? exInterfaceType.toString() : "";
            log.info("开始查询订单结果,参数为: {}", JSON.toJSONString(map));
            String response = client.execute(RequestUrlEnum.ORDER_RESULT, map, dfAccountId);
            if (StringUtils.isBlank(response)) {
                return;
            }
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                log.info("查询订单结果,结果: {}", JSON.toJSONString(dfApiResponse));
                Object result = dfApiResponse.getResult();
                if (result != null) {
                    String jsonString = JSON.toJSONString(result);
                    if ("1".equals(status)) {
                        BspOrderResponseWrapper bspOrderResponse = JSONUtil.toBean(jsonString, BspOrderResponseWrapper.class);
                        if (bspOrderResponse != null) {
                            String failMsg = bspOrderResponse.getFailMsg();
                            if (StringUtils.isNotBlank(failMsg)) {
                                if (failMsg.equals("暂未结果, 请稍后再查")) {
                                    return;
                                }
                                String orderNumber = bspOrderResponse.getOrderNumber();
                                try {
                                    rollBackOrderLive(orderNumber, failMsg);
                                } catch (Exception e) {
                                    log.info("{}订单获取运单失败，订单状态回滚失败，失败原因：{}，失败信息为：{}", orderNumber,e.getMessage(),failMsg);
                                }
                            } else {
                                setExpressLive(bspOrderResponse);
                            }
                        }
                    } else if ("2".equals(status)) {
                        DFCancelOrderResultResponse cancelResponse = JSONUtil.toBean(jsonString, DFCancelOrderResultResponse.class);
                        if (cancelResponse != null) {
                            if (cancelResponse.getIsCancelSuss() == 1) {
                                log.info("查询订单取消成功,返回结果{}", JSON.toJSONString(cancelResponse));
                            } else {
                                log.info("查询订单取消失败,返回结果{}", JSON.toJSONString(cancelResponse));
                            }
                        }
                    }
                }
            } else {
                log.info(String.format("查询订单失败,原因: %s", dfApiResponse.getMsg()));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void rollBackOrderLive(String orderNumber, String failMsg) {
        LiveOrder liveOrder = liveOrderMapper.selectLiveOrderByOrderCode(orderNumber);
        LiveOrder tempOrder = new LiveOrder();
        tempOrder.setOrderId(liveOrder.getOrderId());
        tempOrder.setExtendOrderId("");
        liveOrderMapper.updateLiveOrder(tempOrder);
        FsStoreOrderDf df = new FsStoreOrderDf();
        df.setOrderId(liveOrder.getOrderId());
        df.setStatus(0);
        df.setFailMsg(failMsg);
        df.setUpdateTime(new Date());
        fsStoreOrderDfMapper.updateFsStoreOrderDf(df);
        log.info("{}订单获取运单失败，失败信息为：{}", orderNumber,failMsg);
    }

    private void setExpressLive(BspOrderResponseWrapper bspResponse) {
        String orderNumber = bspResponse.getOrderNumber();
        String mailNumber = bspResponse.getMailNumber();
        BspOrderResponse bspOrderResponse = bspResponse.getBspResponse();
        if (bspOrderResponse != null) {
            AtomicBoolean flag = new AtomicBoolean(false);
            List<OrderResponse> list = bspOrderResponse.getBody();
            if (list != null && !list.isEmpty()) {
                for (OrderResponse orderResponse : list) {
                    List<RlsInfo> rlsInfo = orderResponse.getRlsInfo();
                    if (rlsInfo != null && !rlsInfo.isEmpty()) {
                        for (RlsInfo info : rlsInfo) {
                            List<RlsDetail> rlsDetails = info.getRlsDetail();
                            if (rlsDetails != null && !rlsDetails.isEmpty()) {
                                for (RlsDetail rlsDetail : rlsDetails) {
                                    String proCode = rlsDetail.getProCode();
                                    if (StringUtils.isNotBlank(proCode)) {
                                        LiveOrder order = liveOrderMapper.selectLiveOrderByOrderCode(orderNumber);
                                        if (order != null && order.getStatus() == 1) {
                                            FsExpressScrm express = expressScrmService.selectFsExpressByOmsCode(order.getDeliveryCode());
                                            if (express != null) {
                                                order.setDeliveryName(proCode);
                                                order.setDeliverySn(express.getOmsCode());
                                            }
                                            order.setStatus(2);
                                            order.setDeliverySn(mailNumber);
                                            order.setDeliverySendTime(new Date());
                                            liveOrderMapper.updateLiveOrder(order);
                                            redisCache.deleteObject(DELIVERY+":"+order.getExtendOrderId());
                                            flag.set(true);
                                        }
                                        break;
                                    }
                                }
                            }
                            if (flag.get()) {
                                break;
                            }
                        }
                    }
                    if (flag.get()) {
                        break;
                    }
                }
            }
        }
    }

}
