package com.fs.erp.service.impl;

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.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.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.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.IFsStoreOrderLogsService;
import com.fs.his.service.IFsStoreOrderService;
import com.fs.his.utils.ConfigUtil;
import com.fs.system.domain.SysConfig;
import com.fs.system.mapper.SysConfigMapper;
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.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

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

    @Autowired
    private FsStoreOrderMapper fsStoreOrderMapper;

    @Autowired
    private FsStoreOrderItemMapper fsStoreOrderItemMapper;

    @Autowired
    private FsStoreProductMapper fsStoreProductMapper;

    @Autowired
    private FsStoreOrderDfMapper fsStoreOrderDfMapper;

    @Autowired
    private FsExpressMapper fsExpressMapper;

    @Autowired
    private DfClient client;

    @Autowired
    private IFsStoreOrderLogsService fsStoreOrderLogsService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private FsStoreMapper fsStoreMapper;

    @Autowired
    private IFsExpressService expressService;
    @Autowired
    private IFsStoreOrderService fsStoreOrderService;

    @Autowired
    private SysConfigMapper sysConfigMapper;


    @Override
    public ErpOrderResponse addOrder(ErpOrder order) {
        return getErpOrderResponse(order);
    }

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

    /**
     * 退款 取消订单
     *
     * @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;
        }
        Integer sfAccountIndex = getSFAccountIndex(fsStoreOrder.getOrderId());
        HashMap<String, Object> map = new HashMap<>();
        map.put("loginAccount", df.getLoginAccount());
        DFConfigVo config = getconfig(sfAccountIndex);
        if (config != null && StringUtils.isNotBlank(config.getCallBackUrl())) {
            map.put("callBackUrl", config.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, sfAccountIndex);
            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 ErpDeliverysResponse getDeliver(ErpDeliverysRequest request) {
        ErpDeliverysResponse erpDeliverysResponse = new ErpDeliverysResponse();
        String orderCode = request.getCode();
        if (StrUtil.isNotBlank(orderCode)) {
            FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(orderCode);
            if (order != null) {
                String mailNumber = order.getDeliverySn();
                Integer sfAccountIndex = getSFAccountIndex(order.getOrderId());
                if (StringUtils.isNotBlank(mailNumber) && sfAccountIndex > -1) {
                    try {
                        Map<String, Object> map = new HashMap<>();
                        map.put("mailNumber", mailNumber);
                        log.info("开始查询路由结果,参数为: {}", JSON.toJSONString(map));
                        String response = client.execute(RequestUrlEnum.ORDER_DELIVERY, map, sfAccountIndex);
                        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;
    }


    /**
     * 目前仅查询下单用户
     *
     * @param requset
     * @return
     */
    @Override
    public ErpOrderQueryResponse getOrder(ErpOrderQueryRequert requset) {
        ErpOrderQueryResponse response = new ErpOrderQueryResponse();
        String orderNumber = requset.getCode();
        if (StrUtil.isNotBlank(orderNumber)) {
            FsStoreOrder order = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(orderNumber);
            if (order != null) {
                //获取下单账户
                FsStoreOrderDf df = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(order.getOrderId());
                if(df == null){
                    return null;
                }
                Integer sfAccountIndex = getSFAccountIndex(order.getOrderId());
                if (sfAccountIndex > -1) {
                    Map<String, Object> orderResultQueryParam = new HashMap<>();
                    orderResultQueryParam.put("orderNumber", orderNumber);
                    orderResultQueryParam.put("exInterfaceType", df.getStatus());
                    getOrderResult(orderResultQueryParam, sfAccountIndex);
                    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 param) {
        return null;
    }

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

    @Override
    public void getOrderDeliveryStatus(FsStoreOrder order) {
        Map<String, Object> map = new HashMap<>();
        Integer sfAccountIndex = getSFAccountIndex(order.getOrderId());
        map.put("orderNumber", order.getOrderCode());
        map.put("mailNumber", order.getDeliverySn());
        try {
            String response = client.execute(RequestUrlEnum.ORDER_DELIVERY_STATUS, map, sfAccountIndex);
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            if ("运单不存在".equals(dfApiResponse.getMsg())){

                //查看原来物流状态
                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(order.getOrderId());
                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.getOrderId(),"物流自动");
                        }
                        break;
                    case 10:
                        //取消订单
                        String mailNumber = temp.getMailNumber();
                        List<FsStoreOrder> fsStoreOrders = fsStoreOrderMapper.selectFsStoreOrderListByDeliverySn(mailNumber);
                        if (fsStoreOrders != null && !fsStoreOrders.isEmpty()) {
                            fsStoreOrders.forEach(tempOrder -> {
                                cancelOrder(order);
                                log.info("代服管家 订单取消成功: {}", response);
                            });
                        }
                        break;
                }
                fsStoreOrderMap.setDeliveryStatus(deliveryStatus); //物流状态：0-暂无轨迹信息 1-已揽收 2-在途中,3-签收,4-问题件
                fsStoreOrderMap.setDeliveryType(stateEx);
                fsStoreOrderMapper.updateFsStoreOrder(fsStoreOrderMap);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

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

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

        FsStoreOrder fsStoreOrder = fsStoreOrderMapper.selectFsStoreOrderByOrderCode(order.getPlatform_code());
        if (fsStoreOrder == null) {
            return null;
        }
        int sfAccountIndex = getSFAccountIndex(fsStoreOrder.getOrderId());
        //1.获取请求参数
        ExternalOrderRequestVo vo = getCreateOrderRequestParam(order, fsStoreOrder, sfAccountIndex);
        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, sfAccountIndex);
            DFApiResponse dfApiResponse = JSON.parseObject(response, DFApiResponse.class);
            //3.处理请求结果
            if (dfApiResponse != null && "ok".equals(dfApiResponse.getCode())) {
                //存储订单推送用的哪个账户
                FsStoreOrderDf df = addDfOrder(fsStoreOrder, sfAccountIndex);
                log.info("订单推送成功: {}", response);
                //可以回调 也可以查询订单
                Map<String, Object> orderResultQueryParam = new HashMap<>();
                orderResultQueryParam.put("orderNumber", order.getPlatform_code());
                orderResultQueryParam.put("exInterfaceType", df.getStatus());
                try {
                    getOrderResult(orderResultQueryParam,sfAccountIndex);
                } 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 addDfOrder(FsStoreOrder fsStoreOrder, int sfAccountIndex) {
        FsStoreOrderDf df = new FsStoreOrderDf();
        df.setOrderId(fsStoreOrder.getOrderId());
        df.setOrderCode(fsStoreOrder.getOrderCode());
        DFConfigVo config = getconfig(sfAccountIndex);
        df.setAppKey(config.getDfAppKey());
        df.setAppSecret(config.getDfAppsecret());
        df.setLoginAccount(config.getLoginAccount());
        df.setMonthlyCard(config.getMonthlyCard());
        df.setExpressProductCode(config.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;
    }

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


        vo.setLoginAccount(loginAccount); //代服系统登录账号
        String callBackUrl = config.getCallBackUrl();
        if (StringUtils.isNotBlank(callBackUrl)) {
            vo.setCallBackUrl(callBackUrl); //订单下单后异步通知地址
        }
        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(config.getMonthlyCard()); // 就是月结账号
        }
        //订单付款方式 1:在线支付 2:货到付款
        //如果填了2，代收金额必须大于0，代收卡号必填
        vo.setOrderPayMethod(orderPayMethod);

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

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

        vo.setSenderName(config.getSenderName()); //寄件人
        vo.setSenderPhone(config.getSenderPhone()); //寄件人手机
        vo.setSenderProvince(config.getSenderProvince());//寄件人省
        vo.setSenderCity(config.getSenderCity());//寄件人市
        vo.setSenderDistrict(config.getSenderDistrict());//寄件人区
        vo.setSenderAddress(config.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;
    }

    private @Nullable DFConfigVo getconfig(int index) {
        List<DFConfigVo> dfConfigVos = getDfConfigVos();
        DFConfigVo config = null;
        if (dfConfigVos != null && !dfConfigVos.isEmpty()) {
            config = dfConfigVos.get(index);
        }
        return config;
    }

    private @Nullable List<DFConfigVo> getDfConfigVos() {
        FsSysConfig sysConfig = configUtil.getSysConfig();
        String dfConfigVo = sysConfig.getDfAccounts();
        List<DFConfigVo> dfConfigVos = JSON.parseArray(dfConfigVo, DFConfigVo.class);
        return dfConfigVos;
    }


    /**
     * 获取账户索引 后续添加规则
     *
     * @return
     */
    private int getSFAccountIndex(Long orderId) {
        if (orderId != null) {
            //查询是否选择erp账户
            FsStoreOrderDf temp = fsStoreOrderDfMapper.selectFsStoreOrderDfByOrderId(orderId);
            if (temp != null) {
                FsSysConfig sysConfig = configUtil.getSysConfig();
                String dfConfigVo = sysConfig.getDfAccounts();
                List<DFConfigVo> dfConfigVos = JSON.parseArray(dfConfigVo, DFConfigVo.class);
                if (dfConfigVos != null && !dfConfigVos.isEmpty()) {
                    for (int i = 0; i < dfConfigVos.size(); i++) {
                        if (temp.getLoginAccount().equals(dfConfigVos.get(i).getLoginAccount())) {
                            return i;
                        }
                    }
                }
                return dfConfigVos.indexOf(temp);
            }
        }
        //默认用第一个
        return 0;

    }

    private void getOrderResult(Map<String, Object> map, Integer sfAccountIndex) {
        try {
            String status = map.get("exInterfaceType").toString();
            log.info("开始查询订单结果,参数为: {}", JSON.toJSONString(map));
            String response = client.execute(RequestUrlEnum.ORDER_RESULT, map, sfAccountIndex);
            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();
                                rollBackOrder(orderNumber,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 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);
        //推送失败消息
    }

    /**
     * 顺丰会有自己的轨迹推送 不使用快递鸟(代服务管家设置推送地址)
     *
     * @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());
                                            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;
                    }
                }
            }
        }
    }
}
