package com.yami.shop.service.xsb.impl;


import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yami.shop.bean.dto.OrderRefundDto;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.enums.RefundStatusEnum;
import com.yami.shop.bean.enums.RefundType;
import com.yami.shop.bean.enums.ReturnMoneyStsType;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.vo.xsb.OmsOrderRefundSkuVo;
import com.yami.shop.bean.vo.xsb.RefundOrderPushVo;
import com.yami.shop.common.bean.smqjh.OrderRefundCancelVo;
import com.yami.shop.common.bean.smqjh.OrderRefundExpressParamVo;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.R;
import com.yami.shop.common.util.RefundSnUtils;
import com.yami.shop.dao.*;
import com.yami.shop.service.OrderRefundService;
import com.yami.shop.service.OrderService;
import com.yami.shop.service.hb.IHBOrderService;
import com.yami.shop.service.xsb.XSBRefundOrderService;
import com.yami.shop.utils.CullenUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Slf4j
@Service
@AllArgsConstructor
public class XSBRefundOrderServiceImpl implements XSBRefundOrderService {

//    @Autowired
//    private  SkuMapper skuMapper;//商品sku
    @Autowired
    private ShopDetailMapper shopDetailMapper;//门店详情信息
    @Autowired
    private OrderMapper orderMapper;//订单信息

    @Lazy
    @Autowired
    private OrderRefundService orderRefundService;

    private final OrderRefundSkuMapper orderRefundSkuMapper;

    private final OrderService orderService;

    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    PointsRecordMapper pointsRecordMapper;

    private final OrderRefundRecordMapper orderRefundRecordMapper;
    @Autowired
    private RefundDeliveryMapper refundDeliveryMapper;

    @Autowired
    private IHBOrderService hbOrderService;




    /**
     * 申请退款订单
     * @param refundOrderPushVo
     * @return
     */
    @Transactional
    @Override
    public R<String> applyAfterSales(RefundOrderPushVo refundOrderPushVo,String logId) {
        return applyAfterSalesInternal(refundOrderPushVo, logId, true);
    }

    @Transactional
    @Override
    public R<String> applySmqjhAfterSales(RefundOrderPushVo refundOrderPushVo, String logId) {
        return applyAfterSalesInternal(refundOrderPushVo, logId, false);
    }

    private R<String> applyAfterSalesInternal(RefundOrderPushVo refundOrderPushVo, String logId,
                                              boolean syncHbCloseOnEntireRefund) {
        R<String> stringR = checkParameter(refundOrderPushVo);
        if (!stringR.isSuccess()){
            return stringR;
        }
        log.info("【"+logId+"】"+"渠道推送申请退款参数:{}",refundOrderPushVo);
        List<OrderRefundSku> orderRefundSkuList = new ArrayList<>();
        List<OmsOrderRefundSkuVo> omsOrderRefundSkuVos = refundOrderPushVo.getOrderRefundSkuList();
        for (OmsOrderRefundSkuVo omsOrderRefundSkuVo : omsOrderRefundSkuVos) {
            OrderItem orderItem =  orderItemMapper.findBySkuIdAndOrderNumber(omsOrderRefundSkuVo.getThirdSkuId(),refundOrderPushVo.getOrderNumber());//由于王明推送订单时并没有在第三方(市民请集合)保存本系统id，并且直接将那边的skuId等相关信息直接传输过来，导致只能根据第三方的skuId和订单编号信息去进行查询
            if (orderItem==null){
                return R.FAIL("订单项;渠道订单项id："+omsOrderRefundSkuVo.getId()+";不存在");
            }
            OrderRefundSku orderRefundSku = new OrderRefundSku();
            orderRefundSku.setOrderItemId(orderItem.getOrderItemId());
            orderRefundSku.setSkuId(omsOrderRefundSkuVo.getThirdSkuId());
            orderRefundSku.setSkuPrice(omsOrderRefundSkuVo.getSkuPrice().setScale(2, RoundingMode.HALF_UP).doubleValue());
            orderRefundSku.setProductCount(omsOrderRefundSkuVo.getProductCount());
            orderRefundSkuList.add(orderRefundSku);
        }
        CullenUtils.validateDataThrowException(omsOrderRefundSkuVos.isEmpty(), "退款商品不能为空...");
        // 获取订单信息
        Order order = orderService.getOrderByOrderNumber(refundOrderPushVo.getOrderNumber());

        if (order==null){
            return R.FAIL("渠道推送申请退款：订单不存在");
        }
        if (!Objects.equals(order.getIsPayed(), 1)) {
            return R.FAIL("渠道推送申请退款：当前订单还未付款，无法申请");
        }

        // 商家取消订单触发的退款，跳过常规校验，直接创建状态70的退款单
        boolean isMerchantCancel = Boolean.TRUE.equals(refundOrderPushVo.getMerchantCancel());
        if (isMerchantCancel) {
            log.info("【"+logId+"】"+"商家取消订单触发退款，跳过常规校验，直接创建退款单");
            return createMerchantCancelRefund(refundOrderPushVo, order, orderRefundSkuList, logId);
        }

        if (Objects.equals(order.getHbOrderStatus(), OrderStatus.CLOSE.value())) {
            return R.FAIL("渠道推送申请退款：当前订单已失败，不允许退款");
        }

        if (Objects.equals(order.getHbOrderStatus(), OrderStatus.WAIT_GROUP.value())) {
            return R.FAIL("渠道推送申请退款：当前订单正在等待成团状态，需等待成团才能进行下一步操作");
        }

        if (refundOrderPushVo.getRefundAmount() .compareTo(BigDecimal.valueOf(order.getActualTotal()))>0) {
            return R.FAIL("渠道推送申请退款：退款金额已超出订单金额，无法申请");
        }

        if (!orderRefundService.checkRefundDate(order)) {
            return R.FAIL("渠道推送申请退款：当前订单已确认收货超过" + Constant.MAX_FINALLY_REFUND_TIME + "天，无法退款");
        }

        if (Objects.equals(refundOrderPushVo.getRefundType(), RefundType.ALL.value())
                && (!Objects.isNull(order.getRefundStatus())
                && !Objects.equals(order.getRefundStatus(), RefundStatusEnum.DISAGREE.value()))) {
            return R.FAIL("渠道推送申请退款：该订单已有商品正在退款中，不能再进行整单退款");
        }

        List<Integer> returnMoneySts = new ArrayList<>();
        returnMoneySts.add(ReturnMoneyStsType.APPLY.value());
        returnMoneySts.add(ReturnMoneyStsType.PROCESSING.value());
        returnMoneySts.add(ReturnMoneyStsType.CONSIGNMENT.value());
        returnMoneySts.add(ReturnMoneyStsType.RECEIVE.value());
        int count = orderRefundService.count(new LambdaQueryWrapper<OrderRefund>()
                .eq(OrderRefund::getOrderId, order.getOrderId())
                .in(OrderRefund::getReturnMoneySts, returnMoneySts));

        log.info("【"+logId+"】"+"渠道推送申请退款：已存在退款订单数量{}", count);
        if (count > 0) {
            // 处理已存在退款的情况
            return R.FAIL("渠道推送申请退款：该订单已有退款正在进行中");
        }

        // 生成退款单信息
        OrderRefund newOrderRefund = new OrderRefund();

        // 获取所有正在进行中的退款订单
        List<OrderRefund> orderRefunds = orderRefundService.getProcessingOrderRefundByOrderId(order.getOrderId());

        for (OrderRefund orderRefund : orderRefunds) {
            if (Objects.equals(RefundType.ALL.value(), orderRefund.getRefundType())) {
                return R.FAIL("渠道推送申请退款：该订单正在进行整单退款，无法进行新的退款操作");
            }
        }

        // 如果存在分销订单，则计算分销总金额
        List<OrderItem> orderItemList = orderItemMapper.listByOrderNumber(order.getOrderNumber());
        // 判断退款单类型（1:整单退款,2:单个物品退款）
        if (refundOrderPushVo.getRefundType().equals(RefundType.ALL.value())) {
            // 全部物品退款
            // 计算该订单项的分销金额
            newOrderRefund.setDistributionTotalAmount(orderService.sumTotalDistributionAmountByOrderItem(orderItemList));
            // 计算平台退款金额（退款时将这部分钱退回给平台，所以商家要扣除从平台这里获取的金额）
            newOrderRefund.setPlatformRefundAmount(order.getPlatformAmount());
        }

        newOrderRefund.setShopId(refundOrderPushVo.getThirdShopId());
        newOrderRefund.setUserId(refundOrderPushVo.getMemberId().toString());
        newOrderRefund.setOrderId(order.getOrderId());
        newOrderRefund.setOrderNumber(order.getOrderNumber());
        newOrderRefund.setRefundSn(RefundSnUtils.generate());
        newOrderRefund.setRefundType(refundOrderPushVo.getRefundType());

        newOrderRefund.setRefundAmount(refundOrderPushVo.getRefundAmount().setScale(2, RoundingMode.HALF_UP).doubleValue());
        if (Objects.equals(RefundType.ALL.value(), refundOrderPushVo.getRefundType())) {
            newOrderRefund.setOrderItemId(0L);
        }
//        else {
//            newOrderRefund.setOrderItemId(refundOrderPushVo.getOrderItemId());
//            // 待发货状态-最后一件商品进行退款，退款金额 =  商品金额 + 订单运费金额
//            if (Objects.equals(order.getHbOrderStatus(), OrderStatus.PADYED.value()) && order.getFreightAmount() > 0) {
//                int orderItenCount = orderItemService.count(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, order.getOrderNumber()));
//                if (Objects.equals(orderRefunds.size(), orderItenCount - 1)) {
//                    newOrderRefund.setRefundAmount(Arith.add(newOrderRefund.getRefundAmount(), order.getFreightAmount()));
//                }
//            }
//        }
        BigDecimal refundTotalMoney=BigDecimal.ZERO;
        for (OrderRefundSku orderRefundSku : orderRefundSkuList) {
            int mul = (int) Arith.mul(orderRefundSku.getSkuPrice(), 100)*orderRefundSku.getProductCount();
            log.info("【"+logId+"】"+"转换金额为："+mul);
            BigDecimal bigDecimal = Arith.fenToYuan((long) mul, 2);
            log.info("【"+logId+"】"+"转换后金额为："+mul);
            refundTotalMoney= refundTotalMoney.add(bigDecimal);
        }
//        //计算退款订单金额 整单退款需要退运费
//        if (refundOrderPushVo.getRefundType().equals(RefundType.ALL.value())){
//            refundTotalMoney= refundTotalMoney.add(BigDecimal.valueOf(Arith.mul(order.getFreightAmount(), 100)));
//        }
        newOrderRefund.setRefundAmount(refundOrderPushVo.getRefundAmount().doubleValue());
        newOrderRefund.setRefundTotalMoney(refundTotalMoney);
        newOrderRefund.setGoodsNum(refundOrderPushVo.getGoodsNum());
        newOrderRefund.setApplyType(refundOrderPushVo.getApplyType());
        if (Objects.equals(refundOrderPushVo.getApplyType(), 2)) {
//            newOrderRefund.setIsReceiver(true);
            //第一次进来带审核的时候收货状态为未收到货
            newOrderRefund.setIsReceiver(false);
        } else {
            newOrderRefund.setIsReceiver(false);
        }
        newOrderRefund.setBuyerReason(refundOrderPushVo.getBuyerReason());
        newOrderRefund.setBuyerDesc(refundOrderPushVo.getBuyerDesc());
        newOrderRefund.setBuyerMobile(refundOrderPushVo.getBuyerMobile());
        newOrderRefund.setPhotoFiles(refundOrderPushVo.getPhotoFiles());
        newOrderRefund.setReturnMoneySts(ReturnMoneyStsType.APPLY.value());
        newOrderRefund.setApplyTime(new Date());
        newOrderRefund.setUpdateTime(new Date());
        newOrderRefund.setFreightAmount(refundOrderPushVo.getFreightAmount().setScale(2, RoundingMode.HALF_UP).doubleValue());
        newOrderRefund.setOffsetPoints(0L);
        newOrderRefund.setChannelType(refundOrderPushVo.getChannelType());
        log.info("【"+logId+"】"+"添加退款信息："+JSONObject.toJSONString(newOrderRefund));
        OrderRefund orderRefund = orderRefundService.applyRefund(newOrderRefund);
        if (!orderRefundSkuList.isEmpty()) {
            orderRefundSkuList.forEach(c -> {
                c.setOrderRefundId(orderRefund.getRefundId());
                orderRefundSkuMapper.insert(c);
            });
        }

        //生成退款记录
        addOrderRefundRecord(orderRefund.getRefundId(), 1, 1, newOrderRefund.getBuyerReason());

        //生成待商家审核记录
        addOrderRefundRecord(orderRefund.getRefundId(), 2, 2, "渠道推送申请退款：你的服务单已申请成功，待商家审核");

        //创建海博退款单
        log.info("【"+logId+"】"+"渠道推送申请退款：创建海博退款单，生成海博退款单信息{}", orderRefund);
        orderRefundService.createRefundOrder(orderRefund.getOrderNumber(), orderRefund.getRefundSn());

        // The legacy XSB flow keeps the original behavior, while the SMQJH flow
        // waits for merchant-side action before the Haibo order is closed.
        if (syncHbCloseOnEntireRefund && Objects.equals(refundOrderPushVo.getRefundType(), RefundType.ALL.value())) {
            try {
                hbOrderService.changeOrderStatus(order.getOrderNumber(), OrderStatus.CLOSE.value());
                log.info("[{}] refund apply: entire-order refund, sync Haibo status to 60", logId);
            } catch (Exception e) {
                log.error("[{}] refund apply: failed to sync Haibo status to 60", logId, e);
            }
        } else if (Objects.equals(refundOrderPushVo.getRefundType(), RefundType.ALL.value())) {
            log.info("[{}] refund apply: smqjh flow keeps Haibo order status unchanged until merchant-side action", logId);
        } else {
            log.info("[{}] refund apply: partial refund, keep Haibo order status unchanged", logId);
        }

        return R.SUCCESS(newOrderRefund.getRefundSn());
    }


    /**
     * 用户修改物流公司信息
     */
    @Override
    public R<String> updateExpress(OrderRefundExpressParamVo orderRefundExpressParam) {
        OrderRefund orderRefund = orderRefundService.getOrderRefundByRefundSn(orderRefundExpressParam.getRefundSn());
        if (Objects.isNull(orderRefund)) {
            throw new GlobalException("查询不到退款信息");
        }

        if (!Objects.equals(orderRefund.getUserId(), orderRefundExpressParam.getMemberId())) {
            throw new GlobalException("申请失败，您没有此权限");
        }

        if (!Objects.equals(orderRefund.getReturnMoneySts(), ReturnMoneyStsType.CONSIGNMENT.value())) {
            throw new GlobalException("当前状态不允许更新物流信息操作");
        }

        // 填写物流信息
        RefundDelivery refundDelivery = refundDeliveryMapper.selectOne(new LambdaQueryWrapper<RefundDelivery>()
                .eq(RefundDelivery::getRefundSn, orderRefundExpressParam.getRefundSn()));
        refundDelivery.setSenderMobile(orderRefundExpressParam.getMobile());
        refundDelivery.setDeyId(orderRefundExpressParam.getExpressId());
        refundDelivery.setSenderRemarks(orderRefundExpressParam.getSenderRemarks());
        refundDelivery.setDeyNu(orderRefundExpressParam.getExpressNo());
        refundDelivery.setImgs(orderRefundExpressParam.getImgs());
        refundDelivery.setReceiverMobile(orderRefundExpressParam.getMobile());
        refundDelivery.setDeyName(orderRefundExpressParam.getExpressName());

        // 更新退款单信息
        orderRefund.setUpdateTime(new Date());

        orderRefundService.submitExpress(orderRefund, refundDelivery);
        return R.SUCCESS("修改成功");
    }


    /**
     * 用户撤销退货退款申请
     */
    @Override
    public R<String> cancel(OrderRefundCancelVo orderRefundCancelVo,String logId) {
        OrderRefundDto orderRefund = orderRefundService.getOrderRefundByRefundSn(orderRefundCancelVo.getRefundSn());
        log.info("【"+logId+"】"+"接收第三方取消退款订单申请推送,退款订单{}", JSONObject.toJSONString(orderRefund));
        if (Objects.isNull(orderRefund)) {
            throw new GlobalException("撤销失败 退款订单不存在");
        }
        if (Objects.equals(orderRefund.getReturnMoneySts(), ReturnMoneyStsType.PROCESSING.value())) {
            throw new GlobalException("卖家正在处理退款，不能撤销退款申请");
        }
        if (Objects.equals(orderRefund.getReturnMoneySts(), ReturnMoneyStsType.CONSIGNMENT.value())) {
            throw new GlobalException("买家已发货，不能撤销退款申请");
        }
        if (Objects.equals(orderRefund.getReturnMoneySts(), ReturnMoneyStsType.RECEIVE.value())) {
            throw new GlobalException("卖家已收货，不能撤销退款申请");
        }
        if (Objects.equals(orderRefund.getReturnMoneySts(), ReturnMoneyStsType.SUCCESS.value())) {
            throw new GlobalException("退款成功，不能撤销退款申请");
        }

        // 查看订单是否还有处于处理中的退款单，如果没有则修改订单退款状态为关闭状态
        Order order = orderService.getOrderByOrderNumber(orderRefund.getOrderNumber());

        log.info("【"+logId+"】"+"接收第三方取消退款订单申请推送,订单{}", JSONObject.toJSONString(order));
        if (!Objects.equals(orderRefund.getUserId(),orderRefundCancelVo.getUserId().toString())) {
            throw new GlobalException("申请失败，您没有此权限");
        }
        //如果订单状态为待发货、包含运费、单个商品退款，且所有订单项都进行退款，则不能再取消退款（取消退款后再退款会导致重复退运费bug）
        if (Objects.equals(order.getHbOrderStatus(), OrderStatus.PADYED.value()) && Objects.equals(orderRefund.getRefundType(), 2) && order.getFreightAmount() > 0) {
            // 退款数量
            int refundCount = orderRefundService.count(new LambdaQueryWrapper<OrderRefund>()
                    .gt(OrderRefund::getReturnMoneySts, 0)
                    .lt(OrderRefund::getReturnMoneySts, 6)
                    .eq(OrderRefund::getOrderId, order.getOrderId())
            );
            // 订单项数量
            int orderItemCount = orderItemMapper.selectCount(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, order.getOrderNumber()));
            if (refundCount == orderItemCount) {
                throw new GlobalException("该订单所有商品都进行退款，已无法取消退款");
            }
        }

        if (Objects.equals(orderRefund.getReturnMoneySts(), ReturnMoneyStsType.SUCCESS.value()) ||
                Objects.equals(orderRefund.getReturnMoneySts(), ReturnMoneyStsType.FAIL.value()) ||
                Objects.equals(orderRefund.getReturnMoneySts(), ReturnMoneyStsType.REJECT.value()) ||
                Objects.equals(orderRefund.getReturnMoneySts(), ReturnMoneyStsType.CANCEL.value())) {
            throw new GlobalException("撤销失败 当前状态不允许此操作");
        }

        Date now = new Date();
        orderRefund.setReturnMoneySts(ReturnMoneyStsType.CANCEL.value());
        //orderRefund.setReturnMoneySts(ReturnMoneyStsType.FAIL.value());
        orderRefund.setCancelTime(now);
        orderRefund.setUpdateTime(now);
        orderRefundService.updateById(orderRefund);


        List<OrderRefund> orderRefundList = orderRefundService.list(new LambdaQueryWrapper<OrderRefund>()
                .eq(OrderRefund::getOrderId, order.getOrderId()));
        long count = orderRefundList.stream().filter(item -> Objects.equals(item.getReturnMoneySts(), ReturnMoneyStsType.APPLY.value())
                || Objects.equals(item.getReturnMoneySts(), ReturnMoneyStsType.PROCESSING.value())
                || Objects.equals(item.getReturnMoneySts(), ReturnMoneyStsType.CONSIGNMENT.value())
                || Objects.equals(item.getReturnMoneySts(), ReturnMoneyStsType.RECEIVE.value())).count();
        if (count == 0) {
            order.setRefundStatus(RefundStatusEnum.DISAGREE.value());
            orderService.updateById(order);
        }
        orderRefundService.changeStatus(orderRefundCancelVo.getRefundSn(), 40);

        addOrderRefundRecord(orderRefund.getRefundId(), 4, 4, "用户主动撤回申请，退货退款关闭。");

        return R.SUCCESS("撤销成功");
    }

    /**
     * 变更海博订单状态
     * @param orderNumber 订单编号
     * @param status 目标状态
     * @return
     */
    @Override
    public R<String> changeHbOrderStatus(String orderNumber, Integer status) {
        try {
            hbOrderService.changeOrderStatus(orderNumber, status);
            Order order = orderService.getOrderByOrderNumber(orderNumber);
            order.setHbOrderStatus(status);
            orderService.updateById(order);
            log.info("变更海博订单状态成功, orderNumber: {}, status: {}", orderNumber, status);
            return R.SUCCESS("变更成功");
        } catch (Exception e) {
            log.error("变更海博订单状态失败, orderNumber: {}, status: {}, error: {}", orderNumber, status, e.getMessage());
            return R.FAIL("变更失败: " + e.getMessage());
        }
    }

    /**
     * 变更退款订单状态
     * @param refundSn
     * @param status
     * @return
     */
    @Override
    public R<String> changeHbRefundOrderStatus(String refundSn, Integer status) {
        OrderRefund orderRefund = orderRefundService.getOne(new LambdaQueryWrapper<OrderRefund>().eq(OrderRefund::getRefundSn,refundSn));
        if (orderRefund==null){
            return R.FAIL("【星闪豹】退款订单信息不存在");
        }
        orderRefund.setReturnMoneySts(status);
        orderRefundService.updateById(orderRefund);
        orderRefundService.changeStatus(refundSn,status);
        return  R.SUCCESS("变更退款订单状态成功");
    }

    /**
     * 参数校验
     * @param refundOrderPushVo
     * @return
     */
    private R<String> checkParameter(RefundOrderPushVo refundOrderPushVo){
        if (refundOrderPushVo==null){
            return R.FAIL("退款推送到星闪豹失败,请求参数为空");
        }
        if (StringUtils.isEmpty(refundOrderPushVo.getOrderNumber())){
            return R.FAIL("退款推送到星闪豹失败,请求参数订单编号为空");
        }
        Order orderByOrderNumber = null;
        try {
            orderByOrderNumber = orderMapper.getOrderByOrderNumber(refundOrderPushVo.getOrderNumber());
        } catch (Exception e) {
            log.error(e.getMessage());
            log.error("报错信息为,{}",e);
            return R.FAIL("退款推送到星闪豹失败,查询订单信息报错");
        }
        if (orderByOrderNumber==null){
            return R.FAIL("退款推送到星闪豹失败,订单信息不存在");
        }
        if (ObjectUtils.isEmpty(orderByOrderNumber.getChannelId())){
            return R.FAIL("退款推送到星闪豹失败,订单信息渠道编号为空");
        }
        if (!Objects.equals(orderByOrderNumber.getIsPayed(), 1)) {
            throw new GlobalException("退款推送到星闪豹失败,当前订单还未付款，无法申请");
        }

        if (ObjectUtils.isEmpty(refundOrderPushVo.getThirdShopId())){
            return R.FAIL("退款推送到星闪豹失败,请求参数门店编号为空");
        }
        ShopDetail shopDetail = shopDetailMapper.selectShopDetailById(refundOrderPushVo.getThirdShopId());
        if (shopDetail==null){
            return R.FAIL("退款推送到星闪豹失败,门店信息不存在");
        }
        List<OmsOrderRefundSkuVo> orderRefundSkuList = refundOrderPushVo.getOrderRefundSkuList();
        if (orderRefundSkuList==null||orderRefundSkuList.isEmpty()){
            return R.FAIL("退款推送到星闪豹失败,退款订单明细信息不存在");
        }
//        for (OmsOrderRefundSkuVo omsOrderRefundSkuVo : orderRefundSkuList) {
//            Sku sku = skuMapper.listBySukIdAndPlatform(omsOrderRefundSkuVo.getThirdSkuId(), orderByOrderNumber.getChannelId());
//            if (sku==null){
//                return R.FAIL("退款推送到星闪豹失败,该渠道"+orderByOrderNumber.getChannelId()+"的该商品"+omsOrderRefundSkuVo.getThirdSkuId()+"不存在");
//            }
//        }
        return R.SUCCESS();
    }


    /**
     * 商家取消订单触发的退款：跳过常规校验，直接创建状态为70(退款完成)的退款单
     */
    private R<String> createMerchantCancelRefund(RefundOrderPushVo refundOrderPushVo, Order order,
                                                  List<OrderRefundSku> orderRefundSkuList, String logId) {
        OrderRefund newOrderRefund = new OrderRefund();
        newOrderRefund.setShopId(refundOrderPushVo.getThirdShopId());
        newOrderRefund.setUserId(refundOrderPushVo.getMemberId().toString());
        newOrderRefund.setOrderId(order.getOrderId());
        newOrderRefund.setOrderNumber(order.getOrderNumber());
        newOrderRefund.setRefundSn(RefundSnUtils.generate());
        newOrderRefund.setRefundType(refundOrderPushVo.getRefundType());
        newOrderRefund.setRefundAmount(refundOrderPushVo.getRefundAmount().setScale(2, RoundingMode.HALF_UP).doubleValue());
        if (Objects.equals(RefundType.ALL.value(), refundOrderPushVo.getRefundType())) {
            newOrderRefund.setOrderItemId(0L);
        }
        newOrderRefund.setRefundTotalMoney(refundOrderPushVo.getRefundTotalMoney());
        newOrderRefund.setGoodsNum(refundOrderPushVo.getGoodsNum());
        newOrderRefund.setApplyType(refundOrderPushVo.getApplyType());
        newOrderRefund.setIsReceiver(false);
        newOrderRefund.setBuyerReason(refundOrderPushVo.getBuyerReason());
        newOrderRefund.setBuyerDesc(refundOrderPushVo.getBuyerDesc());
        newOrderRefund.setBuyerMobile(refundOrderPushVo.getBuyerMobile());
        newOrderRefund.setPhotoFiles(refundOrderPushVo.getPhotoFiles());
        newOrderRefund.setReturnMoneySts(ReturnMoneyStsType.SUCCESS.value()); // 70:直接退款完成
        newOrderRefund.setApplyTime(new Date());
        newOrderRefund.setUpdateTime(new Date());
        newOrderRefund.setFreightAmount(refundOrderPushVo.getFreightAmount() != null
                ? refundOrderPushVo.getFreightAmount().setScale(2, RoundingMode.HALF_UP).doubleValue() : 0d);
        newOrderRefund.setOffsetPoints(0L);
        newOrderRefund.setChannelType(refundOrderPushVo.getChannelType());

        log.info("【"+logId+"】"+"商家取消-添加退款信息："+JSONObject.toJSONString(newOrderRefund));
        OrderRefund orderRefund = orderRefundService.applyRefund(newOrderRefund);
        if (!orderRefundSkuList.isEmpty()) {
            orderRefundSkuList.forEach(c -> {
                c.setOrderRefundId(orderRefund.getRefundId());
                orderRefundSkuMapper.insert(c);
            });
        }

        // 生成退款记录
        addOrderRefundRecord(orderRefund.getRefundId(), 1, 1, "商家取消订单");
        addOrderRefundRecord(orderRefund.getRefundId(), 30, 10, "商家取消订单，系统自动完成退款。");

        // 创建海博退款单
        log.info("【"+logId+"】"+"商家取消-创建海博退款单，退款单信息{}", orderRefund);
        orderRefundService.createRefundOrder(orderRefund.getOrderNumber(), orderRefund.getRefundSn());

        return R.SUCCESS(newOrderRefund.getRefundSn());
    }


    /**
     * 保存日志
     * @param refundId
     * @param auditStatus
     * @param sort
     * @param instructions
     */
    private void addOrderRefundRecord(Long refundId, Integer auditStatus, Integer sort, String instructions) {
        OrderRefundRecord orderRefundRecord = new OrderRefundRecord();
        orderRefundRecord.setOrderRefundId(refundId);
        orderRefundRecord.setInstructions(instructions);
        Date date = new Date();
        orderRefundRecord.setCreateTime(date);
        orderRefundRecord.setUpdateTime(date);
        orderRefundRecord.setAuditStatus(auditStatus);
        orderRefundRecord.setSort(sort);
        orderRefundRecordMapper.insert(orderRefundRecord);
    }

}
