package com.fs.erp.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.fs.erp.domain.ErpDeliverys;
import com.fs.erp.domain.ErpOrder;
import com.fs.erp.domain.ErpOrderQuery;
import com.fs.erp.domain.ErpRefundOrder;
import com.fs.erp.dto.*;
import com.fs.erp.dto.sdk.wangdian.enums.DeliveryTerm;
import com.fs.erp.dto.sdk.wangdian.enums.PaymentStatus;
import com.fs.erp.dto.sdk.wangdian.enums.RefundStatus;
import com.fs.erp.dto.sdk.wangdian.enums.TradeStatus;
import com.fs.erp.dto.sdk.wangdianTwo.Pager;
import com.fs.erp.dto.sdk.wangdianTwo.api.WdtTradeAPI;
import com.fs.erp.dto.sdk.wangdianTwo.api.dto.*;
import com.fs.erp.dto.sdk.wangdianTwo.impl.ApiFactory;
import com.fs.erp.dto.sdk.wangdianTwo.impl.WdtTwoClient;
import com.fs.erp.service.IErpOrderService;
import com.fs.his.domain.FsStoreOrder;
import com.fs.his.domain.FsUser;
import com.fs.his.mapper.FsUserMapper;
import com.fs.his.utils.ConfigUtil;
import com.fs.hisStore.config.FsErpConfig;
import com.fs.hisStore.domain.FsStoreOrderScrm;
import com.fs.hisStore.domain.FsStoreProductScrm;
import com.fs.hisStore.service.IFsStoreOrderItemScrmService;
import com.fs.hisStore.service.IFsStoreOrderScrmService;
import com.fs.hisStore.service.IFsStoreProductScrmService;
import com.fs.hisStore.vo.FsStoreOrderItemVO;
import com.fs.live.domain.LiveOrder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.http.client.utils.DateUtils;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;

@Slf4j
@Service
@Primary
public class WdtTwoErpOrderServiceImpl implements IErpOrderService {

    @Autowired
    ConfigUtil configUtil;

    @Autowired
    private IFsStoreOrderScrmService fsStoreOrderScrmService;

    @Autowired
    private IFsStoreOrderItemScrmService fsStoreOrderItemScrmService;

    @Autowired
    private IFsStoreProductScrmService fsStoreProductScrmService;

    @Autowired
    private FsUserMapper fsUserMapper;



    // 延迟初始化这些字段
    private WdtTwoClient client;
    private WdtTradeAPI api;

//    @PostConstruct
//    private void init() {
//        // 在 Spring 容器完成依赖注入后初始化
//        this.client = (WdtTwoClient)WdtTwoClient.get(
//                configUtil.getErpConfig().getErpWdSid(),
//                configUtil.getSysConfig().getErpWdBaseUrl(),
//                configUtil.getErpConfig().getErpWdAppKey(),
//                configUtil.getErpConfig().getErpWdAppsecret()
//        );
//        this.api = ApiFactory.get(client, WdtTradeAPI.class);
//    }

    // 使用双重检查锁的懒加载
    private WdtTwoClient getClient() {
        if (client == null) {
            synchronized (this) {
                if (client == null) {
                    client = (WdtTwoClient)WdtTwoClient.get(
                            configUtil.getErpConfig().getErpWdSid(),
                            configUtil.getSysConfig().getErpWdBaseUrl(),
                            configUtil.getErpConfig().getErpWdAppKey(),
                            configUtil.getErpConfig().getErpWdAppsecret()
                    );
                }
            }
        }
        return client;
    }

    private WdtTradeAPI getApi() {
        if (api == null) {
            synchronized (this) {
                if (api == null) {
                    api = ApiFactory.get(getClient(), WdtTradeAPI.class);
                }
            }
        }
        return api;
    }


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


    /**
     * @Description: 物流推送
     * @Param:
     * @Return:
     * @Author xgb
     * @Date 2026/1/27 11:35
     */
    @Override
    public ErpOrderResponse addOrderScrm(ErpOrder order) {
        PushSelf2Request request = new PushSelf2Request();
        if (StringUtils.isNotEmpty(order.getShopNo())) {
            request.setShopNo(order.getShopNo());
        }

        PushSelf2Request.RawTrade rawTrade = new PushSelf2Request.RawTrade();

        FsStoreOrderScrm fsStoreOrder = fsStoreOrderScrmService.selectFsStoreOrderByOrderCode(order.getPlatform_code());
        BigDecimal couponPrice = fsStoreOrder.getCouponPrice();

        // 订单id
        rawTrade.setTid(order.getPlatform_code());
        // 平台状态
        rawTrade.setTradeStatus(TradeStatus.PAID_WAITING_FOR_SHIPMENT.getValue());
        // 是否执行自动递交以系统配置为准 10: 待递交, 20: 已递交，30: 部分发货，40: 已发货，60: 已完成，70: 已取消
        rawTrade.setProcessStatus(10);
        // 0无退款 1申请退款 2部分退款 3全部退款
        rawTrade.setRefundStatus(0);

        // 1在线转帐 2现金，3银行转账，4邮局汇款 5预付款 6刷卡 7支付宝 8微信支付
        rawTrade.setPayMethod(1);
        // 下单时间
        rawTrade.setTradeTime(order.getDeal_datetime());
        // 支付时间
        rawTrade.setPayTime(order.getDeal_datetime());
        // 交易结束时间
        rawTrade.setEndTime(null);
        // 买家昵称/客户网名
        rawTrade.setBuyerNick(order.getReceiver_name());
        // 买家备注
        rawTrade.setBuyerMessage(order.getBuyer_memo());
        // 买家邮箱
        rawTrade.setBuyerEmail("");
        // 买家地区
        rawTrade.setBuyerArea("");
        // 收件人姓名
        rawTrade.setReceiverName(order.getReceiver_name());
        // 省市区空格分隔，示例【北京 北京市 朝阳区】，省市区推送旺店通地址库
        rawTrade.setReceiverArea(order.getReceiver_province() + " " + order.getReceiver_city() + " " + order.getReceiver_district());
        // 收件人详细地址，不包含省市区
        rawTrade.setReceiverAddress(order.getReceiver_address());
        // 收件人邮编
        rawTrade.setReceiverZip("");
        // 收件人手机
        rawTrade.setReceiverMobile(order.getReceiver_mobile());
        // 收件人电话
        rawTrade.setReceiverTelno("");
        // 邮费
        rawTrade.setPostAmount(fsStoreOrder.getFreightPrice());
        // 其他费用
        rawTrade.setOtherAmount(BigDecimal.ZERO);
        // 优惠金额
        rawTrade.setDiscount(BigDecimal.ZERO);
        // 应收金额
        rawTrade.setReceivable(fsStoreOrder.getPayPrice());
        // 平台费用
        rawTrade.setPlatformCost(BigDecimal.ZERO);
        // 发票类别 0:不需要,1:普通发票,2:增值税普通发票电子,3:增值税普通发票纸质,4:增值税专用发票
//        rawTrade.setInvoiceType();
        // 线下支付金额 发票内容
        rawTrade.setInvoiceContent(String.valueOf(fsStoreOrder.getOfflinePayAmount()));
        // 物流类别
//        rawTrade.setLogisticsType();
        // 物流编号
//        rawTrade.setCustData();


        // 如果是货到付款
        if ("2".equals(fsStoreOrder.getPayType())) {
            // 支付状态
            rawTrade.setPayStatus(PaymentStatus.PARTIALLY_PAID.getValue());
            // 发货条件
            rawTrade.setDeliveryTerm(DeliveryTerm.CASH_ON_DELIVERY.getValue());
            // 货到付款金额 = 物流代收金额-优惠金额
            rawTrade.setCodAmount(fsStoreOrder.getPayDelivery().subtract(couponPrice));

        } else if ("3".equals(fsStoreOrder.getPayType())) {
            // 支付状态
            rawTrade.setPayStatus(PaymentStatus.UNPAID.getValue());
            // 发货条件
            rawTrade.setDeliveryTerm(DeliveryTerm.CASH_ON_DELIVERY.getValue());
            // 货到付款金额 = 物流代收金额-优惠金额
            rawTrade.setCodAmount(fsStoreOrder.getPayDelivery().subtract(couponPrice));
        } else { // 如果是线上付款
            // 支付状态
            rawTrade.setPayStatus(PaymentStatus.FULLY_PAID.getValue());
            // 发货条件
            rawTrade.setDeliveryTerm(DeliveryTerm.PAYMENT_BEFORE_DELIVERY.getValue());
        }
        // 平台支付订单ID
        rawTrade.setPayId(String.valueOf(fsStoreOrder.getOrderCode()));
        // 客服备注
        rawTrade.setRemark(order.getSeller_memo());
        // 客服备注标记 标旗（1 红、2 黄、3 绿、4 蓝、5 紫 无则填0）
        rawTrade.setRemarkFlag(0);
        // 是否是自流转 true自流转，false 非自流转
        rawTrade.setIsAutoWms(false);
        // 仓库编号
        rawTrade.setWarehouseNo("");
        if (fsStoreOrder.getPayMoney() != null) {
            // 已付
            rawTrade.setPaid(fsStoreOrder.getPayMoney());
        }

        // 还有的字段看接口文档 ....
        request.setRawTrades(Collections.singletonList(rawTrade));

        // 商品总价
        BigDecimal totalPrice = fsStoreOrder.getTotalPrice();
        // 总折扣金额 = 优惠券金额 + 折扣金额
        BigDecimal totalDiscountPrice = BigDecimal.ZERO;
        // 折扣金额
        BigDecimal discountPrice = totalPrice.subtract(fsStoreOrder.getPayPrice());
        totalDiscountPrice = couponPrice.add(discountPrice);

        // 防止除零错误
        if (totalPrice.compareTo(BigDecimal.ZERO) == 0) {
            totalPrice = BigDecimal.ONE;
        }

        List<FsStoreOrderItemVO> fsStoreOrderItemVOS = fsStoreOrderItemScrmService.selectFsStoreOrderItemListByOrderId(fsStoreOrder.getId());
        List<PushSelf2Request.RawTradeOrder> rawTradeOrders = new ArrayList<>();
        BigDecimal nummber = BigDecimal.ZERO;
        for (FsStoreOrderItemVO fsStoreOrderItem : fsStoreOrderItemVOS) {
            PushSelf2Request.RawTradeOrder rawTradeOrder = new PushSelf2Request.RawTradeOrder();
            // 原始订单号
            rawTradeOrder.setTid(order.getPlatform_code());

            // 原始子单号
            rawTradeOrder.setOid(String.format("%s%s", fsStoreOrderItem.getOrderCode(), fsStoreOrderItem.getItemId()));
            // 状态
            rawTradeOrder.setStatus(TradeStatus.PAID_WAITING_FOR_SHIPMENT.getValue());
            // 退款状态
            rawTradeOrder.setRefundStatus(RefundStatus.NO_REFUND.getValue());

            FsStoreProductScrm fsStoreProduct = fsStoreProductScrmService.selectFsStoreProductById(fsStoreOrderItem.getProductId());
            if (fsStoreProduct == null) {
                log.error("该商品不存在! 商品id[{}] ", fsStoreOrderItem.getProductId());
                throw new RuntimeException("该商品不存在!");
            }

            // 平台货品ID
            rawTradeOrder.setGoodsId(String.valueOf(fsStoreProduct.getProductId()));
            JSONObject jsonObject = JSON.parseObject(fsStoreOrderItem.getJsonInfo());
            rawTradeOrder.setSpecId(jsonObject.getString("sku"));
            rawTradeOrder.setGoodsNo(jsonObject.getString("barCode"));
            rawTradeOrder.setSpecNo(jsonObject.getString("sku"));
            // 货品名称
            rawTradeOrder.setGoodsName(fsStoreProduct.getProductName());
            // 子单类型 0正常货品 1虚拟货品 2服务
            rawTradeOrder.setOrderType(0);
            // 平台类目
//            rawTradeOrder.setCid();
            // 数量
            rawTradeOrder.setNum(BigDecimal.valueOf(fsStoreOrderItem.getNum()));
            nummber = nummber.add(rawTradeOrder.getNum());
            // 单价
            //由于商品改价 用item里面的单价
            rawTradeOrder.setPrice(jsonObject.getBigDecimal("price"));
            // 调整
            rawTradeOrder.setAdjustAmount(BigDecimal.ZERO);
            // 优惠
            rawTradeOrder.setDiscount(BigDecimal.ZERO);

            // 分摊优惠
            // 分摊比例
            BigDecimal price = fsStoreProduct.getPrice().multiply(BigDecimal.valueOf(fsStoreOrderItem.getNum()));
            BigDecimal divide = price.divide(totalPrice, RoundingMode.HALF_UP);
            rawTradeOrder.setShareDiscount(divide.multiply(totalDiscountPrice));

            // 总价格
            rawTradeOrder.setTotalAmount(rawTradeOrder.getPrice().multiply(rawTradeOrder.getNum()));
            // 退款金额
            rawTradeOrder.setRefundAmount(BigDecimal.ZERO);
            // 备注
            rawTradeOrder.setRemark("");
            // json串
            rawTradeOrder.setJson("");
            // 赠品方式 赠品方式 0非赠品1自动赠送2手工赠送4周期购赠送8平台赠送32阶梯满赠64CRM追加赠送65 主品
            rawTradeOrder.setGiftType(0);

            rawTradeOrders.add(rawTradeOrder);
        }

        // 最后一个商品的分摊优惠等于总优惠减去前面分摊优惠之和
        Asserts.check(CollectionUtils.isNotEmpty(rawTradeOrders), "订单 {} 商品不能为空!", order.getPlatform_code());
        long size = rawTradeOrders.size();
        if (size > 1) {
            PushSelf2Request.RawTradeOrder rawTradeOrder = rawTradeOrders.get(rawTradeOrders.size() - 1);
            rawTradeOrder.setShareDiscount(totalDiscountPrice.subtract(rawTradeOrders.stream()
                    .limit(size - 1L)
                    .map(item -> Optional.ofNullable(item.getShareDiscount()).orElse(BigDecimal.ZERO))
                    .reduce(BigDecimal.ZERO, BigDecimal::add)));
        }


        request.setRawTradeOrders(rawTradeOrders);

        // 原始单包含的子订单数，rawTradeOrderList节点下所有子单数之和
        rawTrade.setOrderCount(fsStoreOrderItemVOS.size());
        // 货品总数量，rawTradeOrderList节点下所有“num”数量之和
        rawTrade.setGoodsCount(nummber);

        // 优惠券 目前不添加
        PushSelf2Response response = getApi().pushSelf2(request.getShopNo(), request.getRawTrades(), request.getRawTradeOrders(), request.getDiscountInfos());
        if (response.getChgCount() <= 0 && response.getNewCount()<=0) {
            log.info("订单推送失败: [{}]", response.getErrorList().get(0).getError());
            throw new RuntimeException(String.format("订单推送失败, 原因: %s", response.getErrorList().get(0).getError()));
        } else {
            log.info("订单推送成功!");
            ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
            erpOrderResponse.setCode(order.getPlatform_code());
            erpOrderResponse.setSuccess(true);
            erpOrderResponse.setRequestRawData(JSON.toJSONString(request));
            erpOrderResponse.setResponseRawData(JSON.toJSONString(response));
            return erpOrderResponse;
        }
    }


    @Override
    public ErpOrderQueryResponse getOrder(ErpOrderQueryRequert param){
        QuerySelfOrderDetailRequest request = new QuerySelfOrderDetailRequest();
        request.setSrcTid(param.getCode());
        QuerySelfOrderDetailResponse response = getApi().querySelfOrderWithDetail(request, new Pager(1, 0, true));
        if (response.getTotalCount() <= 0) {
            log.info("订单信息不存在 订单号{}", param.getCode());
            throw new RuntimeException("订单信息不存在");
        }
        return toErpOrderQueryResponse(response);
    }

    /**
     * @Description: 订单查询
     * @Param:
     * @Return:
     * @Author xgb
     * @Date 2026/1/27 16:53
     */
    public ErpOrderQueryResponse getOrderScrm(ErpOrderQueryRequert param) {

        QuerySelfOrderDetailRequest request = new QuerySelfOrderDetailRequest();
        request.setSrcTid(param.getCode());
        QuerySelfOrderDetailResponse response = getApi().querySelfOrderWithDetail(request, new Pager(1, 0, true));
        if (response.getTotalCount() <= 0) {
            log.info("订单信息不存在 订单号{}", param.getCode());
            throw new RuntimeException("订单信息不存在");
        }
        return toErpOrderQueryResponse(response);

    }

    /**
     * @Description: 只用于单个订单查询的返回结果转换
     * @Param:
     * @Return:
     * @Author xgb
     * @Date 2026/1/28 9:20
     */
    private ErpOrderQueryResponse toErpOrderQueryResponse(QuerySelfOrderDetailResponse source) {
        ErpOrderQueryResponse response = new ErpOrderQueryResponse();
        QuerySelfOrderDetailResponse.OrderInfo order = source.getOrder().get(0);

        // 订单信息
        ErpOrderQuery erpOrderQuery = new ErpOrderQuery();
        // 快递编号
        if (order.getLogisticsCode() != null) {
            erpOrderQuery.setExpress_code(order.getLogisticsCode());
        }
        // 快递名称
        if (order.getLogisticsName() != null) {
            erpOrderQuery.setExpress_name(order.getLogisticsName());
        }

        // 收货人
        if (order.getReceiverName() != null) {
            erpOrderQuery.setReceiver_name(order.getReceiverName());
        }

        // 电话
        if (order.getReceiverMobile() != null) {
            erpOrderQuery.setReceiver_mobile(order.getReceiverMobile());
        }

        //地址
        if (order.getReceiverAddress() != null) {
            erpOrderQuery.setReceiver_address(order.getReceiverAddress());
        }

        // 运单号
        if (order.getLogisticsNo() != null) {
            erpOrderQuery.setExpress_code(order.getLogisticsNo());
        }

        // 订单状态
        if (order.getTradeStatus() != null) {
            erpOrderQuery.setDelivery_state(order.getTradeStatus());
        }

        // 订单号
        if (order.getSrcTids() != null) {
            erpOrderQuery.setCode(order.getSrcTids());
        }
        // 商品数量
        if (order.getGoodsCount() != null) {
            erpOrderQuery.setQty(order.getGoodsCount().intValue());
        }
        // 商品金额
        if (order.getReceivable() != null) {
            erpOrderQuery.setAmount(order.getReceivable().doubleValue());
        }
        // 支付金额
        if (order.getPaid() != null) {
            erpOrderQuery.setPayment(order.getPaid().doubleValue());
        }

        if(order.getConsignTime() != null){
            erpOrderQuery.setConsignTime(new Date(Long.parseLong(order.getConsignTime())));
        }

        // 物流信息
        ErpDeliverys erpDeliverys = new ErpDeliverys();
        erpDeliverys.setExpress_code(order.getLogisticsCode());
        erpDeliverys.setExpress_name(order.getLogisticsName());
        erpDeliverys.setMail_no(order.getLogisticsNo());
        erpDeliverys.setDelivery(true);
        erpOrderQuery.setDeliverys(Collections.singletonList(erpDeliverys));

        response.setOrders(Collections.singletonList(erpOrderQuery));
        return response;
    }

    //   // sales_refund_push.php
    //	@Api(value = "aftersales.refund.RawRefund.upload2", paged = true)
    //	StockSearch2Response rawRefundUpload(StockSearch2Request request, Pager pager);

    /**
     * @Description: 退款
     * @Param:
     * @Return:
     * @Author xgb
     * @Date 2026/1/28 9:23
     */
    @Override
    public BaseResponse refundUpdateScrm(ErpRefundUpdateRequest param) {


        FsErpConfig erpconfig = configUtil.getErpConfig();
        log.info("退款单更新: {}", param);
        FsStoreOrderScrm fsStoreOrder = fsStoreOrderScrmService.selectFsStoreOrderByOrderCode(param.getTid());

        ErpOrderQueryRequert queryRequert = new ErpOrderQueryRequert();
        queryRequert.setCode(fsStoreOrder.getExtendOrderId());

        // 95已发货
        //
        //96 成本确认（待录入计划成本，订单结算时有货品无计划成本）
        //
        //101 已过账
        //
        //110已完成
        Set<Integer> status = new HashSet<>();
        status.add(95);
        status.add(96);
        status.add(101);
        status.add(105);
        status.add(110);

        ErpOrderQueryResponse orderScrm = getOrderScrm(queryRequert);
        ErpOrderQuery erpOrderQuery = orderScrm.getOrders().get(0);
        Integer deliveryState = erpOrderQuery.getDelivery_state();
        // 如果是未发货
        if (!status.contains(deliveryState)) {
            log.info("售前退款 参数: {}", param);
            try {
                ErpOrder order = fsStoreOrderScrmService.getErpOrder(fsStoreOrder);

                Asserts.check(ObjectUtils.isNotNull(order), "该订单不存在!");

                return getErpOrderRefundScrmResponse(order);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        //--------------售后退款------------
        log.info("售后退款 参数: {}", param);
        Map<String, String> map = new HashMap<>();


        Asserts.check(ObjectUtils.isNotNull(fsStoreOrder), "该订单不存在! 订单id: {} ", param.getTid());

        List<FsStoreOrderItemVO> fsStoreOrderItemVOS = fsStoreOrderItemScrmService.selectFsStoreOrderItemListByOrderId(fsStoreOrder.getId());

        // 查询用户名称
        FsUser fsUser = fsUserMapper.selectFsUserById(fsStoreOrder.getUserId());

        RawRefundUpload2Request request = new RawRefundUpload2Request();
        request.setShopNo(erpconfig.getErpWdShopCode());
        List<RawRefundUpload2Request.RefundOrder> orders = new ArrayList<>();
        for (FsStoreOrderItemVO item : fsStoreOrderItemVOS) {


            RawRefundUpload2Request.RefundOrder order = new RawRefundUpload2Request.RefundOrder();
            // 原始退款单号
            order.setRefundNo(String.format("%s%s", item.getOrderCode(), item.getItemId()));
            // 货品数量
            order.setNum(BigDecimal.valueOf(item.getNum()));
            // 原始单号
            order.setTid(param.getTid());
            // 原始子单号
            order.setOid(String.format("%s%s", item.getOrderCode(), item.getItemId()));
            // 退款单类型 0取消订单1退款(未发货，退款申请)2退货3换货4退款不退货
            order.setType(2);
            // 1取消退款,2已申请退款,3等待退货,4等待收货,5退款成功
            order.setStatus(5);
            // 退款版本
            order.setRefundVersion("1");
            JSONObject jsonObject = JSON.parseObject(item.getJsonInfo());
            BigDecimal onePrice = jsonObject.getBigDecimal("price");
            // 申请退款金额
            order.setRefundAmount(onePrice.multiply(order.getNum()));
            // 实际退款金额
            order.setActualRefundAmount(order.getRefundAmount());
            // 标题，对应原始退款单页面主单货品字段，若无传空字符串
            order.setTitle("");
            // 客户网名
            order.setBuyerNick(fsUser != null ? fsUser.getNickName() : "");
            // 是否售后退款单 0：否 1：是
            order.setIsAftersale(1);
            //
            order.setReason("自研平台退款");
            // 单价
            order.setPrice(onePrice);
            // 退款创建时间
            order.setRefundTime(DateUtils.formatDate(new Date(), "yyyy-MM-dd HH:mm:ss"));
            // 退款完成时间
            order.setCurrentPhaseTimeout(order.getRefundTime());
            // 物流
            order.setLogisticsNo("");
            order.setLogisticsName("");

            orders.add(order);
        }

        request.setOrderList(orders);


        RawRefundUpload2Response response = getApi().rawRefundUpload(request.getShopNo(),request.getOrderList());
        if (response.getChgCount() <= 0 && response.getNewCount()<=0) {
            log.info("退款单更新失败: {}", response);
            throw new RuntimeException(String.format("退款单更新失败, 原因: %s", response.getErrorList().get(0).getError()));

        } else {
            log.info("退款单更新成功");
            return new BaseResponse();
        }
    }

    @Override
    public BaseResponse refundUpdateLive(ErpRefundUpdateRequest param) {
        return null;
    }


    @Override
    public BaseResponse refundUpdate(ErpRefundUpdateRequest param){
        return null;
    }

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

    @Override
    public void getOrderDeliveryStatus(FsStoreOrder order) {

    }

    @Override
    public void getOrderScrmDeliveryStatus(FsStoreOrderScrm order) {

    }

    @Override
    public void getOrderLiveDeliveryStatus(LiveOrder order) {

    }

    @Override
    public ErpOrderQueryResponse batchGetLiveOrder(List<LiveOrder> orderList) {
        return null;
    }

    /**
     * scrm 如果未发货 修改订单为退款
     *
     * @param order 订单参数
     * @return
     */
    private BaseResponse getErpOrderRefundScrmResponse(ErpOrder order) {

        PushSelf2Request request = new PushSelf2Request();
        if (StringUtils.isNotEmpty(order.getShopNo())) {
            request.setShopNo(order.getShopNo());
        }

        PushSelf2Request.RawTrade rawTrade = new PushSelf2Request.RawTrade();

        FsStoreOrderScrm fsStoreOrder = fsStoreOrderScrmService.selectFsStoreOrderByOrderCode(order.getPlatform_code());
        BigDecimal couponPrice = fsStoreOrder.getCouponPrice();

        // 订单id
        rawTrade.setTid(order.getPlatform_code());
        // 平台状态
        rawTrade.setTradeStatus(TradeStatus.REFUNDED.getValue());
        // 是否执行自动递交以系统配置为准 10: 待递交, 20: 已递交，30: 部分发货，40: 已发货，60: 已完成，70: 已取消
        rawTrade.setProcessStatus(70);
        // 0无退款 1申请退款 2部分退款 3全部退款
        rawTrade.setRefundStatus(3);

        // 1在线转帐 2现金，3银行转账，4邮局汇款 5预付款 6刷卡 7支付宝 8微信支付
        rawTrade.setPayMethod(1);
        // 下单时间
        rawTrade.setTradeTime(order.getDeal_datetime());
        // 支付时间
        rawTrade.setPayTime(order.getDeal_datetime());
        // 交易结束时间
        rawTrade.setEndTime(null);
        // 买家昵称/客户网名
        rawTrade.setBuyerNick(order.getReceiver_name());
        // 买家备注
        rawTrade.setBuyerMessage(order.getBuyer_memo());
        // 买家邮箱
        rawTrade.setBuyerEmail("");
        // 买家地区
        rawTrade.setBuyerArea("");
        // 收件人姓名
        rawTrade.setReceiverName(order.getReceiver_name());
        // 省市区空格分隔，示例【北京 北京市 朝阳区】，省市区推送旺店通地址库
        rawTrade.setReceiverArea(order.getReceiver_province() + " " + order.getReceiver_city() + " " + order.getReceiver_district());
        // 收件人详细地址，不包含省市区
        rawTrade.setReceiverAddress(order.getReceiver_address());
        // 收件人邮编
        rawTrade.setReceiverZip("");
        // 收件人手机
        rawTrade.setReceiverMobile(order.getReceiver_mobile());
        // 收件人电话
        rawTrade.setReceiverTelno("");
        // 邮费
        rawTrade.setPostAmount(fsStoreOrder.getFreightPrice());
        // 其他费用
        rawTrade.setOtherAmount(BigDecimal.ZERO);
        // 优惠金额
        rawTrade.setDiscount(BigDecimal.ZERO);
        // 应收金额
        rawTrade.setReceivable(fsStoreOrder.getPayPrice());
        // 平台费用
        rawTrade.setPlatformCost(BigDecimal.ZERO);
        // 发票类别 0:不需要,1:普通发票,2:增值税普通发票电子,3:增值税普通发票纸质,4:增值税专用发票
//        rawTrade.setInvoiceType();
        // 发票内容
//        rawTrade.setInvoiceContent("");
        // 物流类别
//        rawTrade.setLogisticsType();
        // 物流编号
//        rawTrade.setCustData();


        // 如果是货到付款
        if ("2".equals(fsStoreOrder.getPayType())) {
            // 支付状态
            rawTrade.setPayStatus(PaymentStatus.PARTIALLY_PAID.getValue());
            // 发货条件
            rawTrade.setDeliveryTerm(DeliveryTerm.CASH_ON_DELIVERY.getValue());
            // 货到付款金额 = 物流代收金额-优惠金额
            rawTrade.setCodAmount(fsStoreOrder.getPayDelivery().subtract(couponPrice));

        } else if ("3".equals(fsStoreOrder.getPayType())) {
            // 支付状态
            rawTrade.setPayStatus(PaymentStatus.UNPAID.getValue());
            // 发货条件
            rawTrade.setDeliveryTerm(DeliveryTerm.CASH_ON_DELIVERY.getValue());
            // 货到付款金额 = 物流代收金额-优惠金额
            rawTrade.setCodAmount(fsStoreOrder.getPayDelivery().subtract(couponPrice));
        } else { // 如果是线上付款
            // 支付状态
            rawTrade.setPayStatus(PaymentStatus.FULLY_PAID.getValue());
            // 发货条件
            rawTrade.setDeliveryTerm(DeliveryTerm.PAYMENT_BEFORE_DELIVERY.getValue());
        }
        // 平台支付订单ID
        rawTrade.setPayId(String.valueOf(fsStoreOrder.getOrderCode()));
        // 客服备注
        rawTrade.setRemark(order.getSeller_memo());
        // 客服备注标记 标旗（1 红、2 黄、3 绿、4 蓝、5 紫 无则填0）
        rawTrade.setRemarkFlag(0);
        // 是否是自流转 true自流转，false 非自流转
        rawTrade.setIsAutoWms(false);
        // 仓库编号
        rawTrade.setWarehouseNo("");
        if (fsStoreOrder.getPayMoney() != null) {
            // 已付
            rawTrade.setPaid(fsStoreOrder.getPayMoney());
        }

        // 还有的字段看接口文档 ....
        request.setRawTrades(Collections.singletonList(rawTrade));

        // 商品总价
        BigDecimal totalPrice = fsStoreOrder.getTotalPrice();
        // 总折扣金额 = 优惠券金额 + 折扣金额
        BigDecimal totalDiscountPrice = BigDecimal.ZERO;
        // 折扣金额
        BigDecimal discountPrice = totalPrice.subtract(fsStoreOrder.getPayPrice());
        totalDiscountPrice = couponPrice.add(discountPrice);

        // 防止除零错误
        if (totalPrice.compareTo(BigDecimal.ZERO) == 0) {
            totalPrice = BigDecimal.ONE;
        }

        List<FsStoreOrderItemVO> fsStoreOrderItemVOS = fsStoreOrderItemScrmService.selectFsStoreOrderItemListByOrderId(fsStoreOrder.getId());
        List<PushSelf2Request.RawTradeOrder> rawTradeOrders = new ArrayList<>();
        BigDecimal nummber = BigDecimal.ZERO;
        for (FsStoreOrderItemVO fsStoreOrderItem : fsStoreOrderItemVOS) {
            PushSelf2Request.RawTradeOrder rawTradeOrder = new PushSelf2Request.RawTradeOrder();
            // 原始订单号
            rawTradeOrder.setTid(order.getPlatform_code());

            // 原始子单号
            rawTradeOrder.setOid(String.format("%s%s", fsStoreOrderItem.getOrderCode(), fsStoreOrderItem.getItemId()));
            // 状态
            rawTradeOrder.setStatus(TradeStatus.PAID_WAITING_FOR_SHIPMENT.getValue());
            // 退款状态
            rawTradeOrder.setRefundStatus(RefundStatus.NO_REFUND.getValue());

            FsStoreProductScrm fsStoreProduct = fsStoreProductScrmService.selectFsStoreProductById(fsStoreOrderItem.getProductId());
            if (fsStoreProduct == null) {
                log.error("该商品不存在! 商品id[{}] ", fsStoreOrderItem.getProductId());
                throw new RuntimeException("该商品不存在!");
            }

            // 平台货品ID
            rawTradeOrder.setGoodsId(String.valueOf(fsStoreProduct.getProductId()));
            JSONObject jsonObject = JSON.parseObject(fsStoreOrderItem.getJsonInfo());
            rawTradeOrder.setSpecId(jsonObject.getString("sku"));
            rawTradeOrder.setGoodsNo(jsonObject.getString("barCode"));
            rawTradeOrder.setSpecNo(jsonObject.getString("sku"));
            // 货品名称
            rawTradeOrder.setGoodsName(fsStoreProduct.getProductName());
            // 子单类型 0正常货品 1虚拟货品 2服务
            rawTradeOrder.setOrderType(0);
            // 平台类目
//            rawTradeOrder.setCid();
            // 数量
            rawTradeOrder.setNum(BigDecimal.valueOf(fsStoreOrderItem.getNum()));
            nummber = nummber.add(rawTradeOrder.getNum());
            // 单价
            //由于商品改价 用item里面的单价
            rawTradeOrder.setPrice(jsonObject.getBigDecimal("price"));
            // 调整
            rawTradeOrder.setAdjustAmount(BigDecimal.ZERO);
            // 优惠
            rawTradeOrder.setDiscount(BigDecimal.ZERO);

            // 分摊优惠
            // 分摊比例
            BigDecimal price = fsStoreProduct.getPrice().multiply(BigDecimal.valueOf(fsStoreOrderItem.getNum()));
            BigDecimal divide = price.divide(totalPrice, RoundingMode.HALF_UP);
            rawTradeOrder.setShareDiscount(divide.multiply(totalDiscountPrice));

            // 总价格
            rawTradeOrder.setTotalAmount(rawTradeOrder.getPrice().multiply(rawTradeOrder.getNum()));
            // 退款金额
            rawTradeOrder.setRefundAmount(BigDecimal.ZERO);
            // 备注
            rawTradeOrder.setRemark("");
            // json串
            rawTradeOrder.setJson("");
            // 赠品方式 赠品方式 0非赠品1自动赠送2手工赠送4周期购赠送8平台赠送32阶梯满赠64CRM追加赠送65 主品
            rawTradeOrder.setGiftType(0);

            rawTradeOrders.add(rawTradeOrder);
        }

        // 最后一个商品的分摊优惠等于总优惠减去前面分摊优惠之和
        Asserts.check(CollectionUtils.isNotEmpty(rawTradeOrders), "订单 {} 商品不能为空!", order.getPlatform_code());
        long size = rawTradeOrders.size();
        if (size > 1) {
            PushSelf2Request.RawTradeOrder rawTradeOrder = rawTradeOrders.get(rawTradeOrders.size() - 1);
            rawTradeOrder.setShareDiscount(totalDiscountPrice.subtract(rawTradeOrders.stream()
                    .limit(size - 1L)
                    .map(item -> Optional.ofNullable(item.getShareDiscount()).orElse(BigDecimal.ZERO))
                    .reduce(BigDecimal.ZERO, BigDecimal::add)));
        }


        request.setRawTradeOrders(rawTradeOrders);

        // 原始单包含的子订单数，rawTradeOrderList节点下所有子单数之和
        rawTrade.setOrderCount(fsStoreOrderItemVOS.size());
        // 货品总数量，rawTradeOrderList节点下所有“num”数量之和
        rawTrade.setGoodsCount(nummber);

        // 优惠券 目前不添加
        PushSelf2Response response = getApi().pushSelf2(request.getShopNo(), request.getRawTrades(), request.getRawTradeOrders(), request.getDiscountInfos());
        if (response.getChgCount() <= 0 && response.getNewCount()<=0) {
            log.info("未发货退款单更新失败: {}", response);
            throw new RuntimeException(String.format("退款单更新失败, 原因: %s", response.getErrorList().get(0).getError()));
        } else {
            log.info("未发货退款单更新成功");
            ErpOrderResponse erpOrderResponse = new ErpOrderResponse();
            erpOrderResponse.setCode(order.getPlatform_code());
            erpOrderResponse.setSuccess(true);
            erpOrderResponse.setRequestRawData(JSON.toJSONString(request));
            erpOrderResponse.setResponseRawData(JSON.toJSONString(response));
            return erpOrderResponse;
        }
    }

    @Override
    public Map<String,Object>  stockOutOrderQueryTrade(ErpOrderQueryRequert param){
        return null;
    }

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


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

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

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

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


    @Override
    public ErpOrderQueryResponse getScrmOrder(ErpOrderQueryRequert param) {
        return null;
    }

    @Override
    public ErpOrderQueryResponse getLiveOrder(ErpOrderQueryRequert param) {
        return null;
    }
}
