package com.yami.shop.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.yami.shop.bean.dto.OrderRefundDto;
import com.yami.shop.bean.dto.hb.HBBaseReq;
import com.yami.shop.bean.dto.hb.OrderPaymentRequest;
import com.yami.shop.bean.dto.hb.ProductRequest;
import com.yami.shop.bean.dto.hb.ThirdPartyRefundRequest;
import com.yami.shop.bean.enums.*;
import com.yami.shop.bean.event.OrderRefundSuccessEvent;
import com.yami.shop.bean.event.ReceiptOrderEvent;
import com.yami.shop.bean.model.*;
import com.yami.shop.bean.param.*;
import com.yami.shop.bean.pay.RefundInfoDto;
import com.yami.shop.bean.vo.ExportContext;
import com.yami.shop.bean.vo.OrderRefundSkuVo;
import com.yami.shop.bean.vo.OrderRefundVo;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.enums.PayType;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.util.Arith;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.R;
import com.yami.shop.common.util.hb.HBR;
import com.yami.shop.dao.*;
import com.yami.shop.service.*;
import com.yami.shop.service.hb.impl.HBOrderService;
import com.yami.shop.utils.ExportUtils;
import com.yami.shop.utils.HBSignUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import ma.glasnost.orika.MapperFacade;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.rmi.server.ExportException;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.yami.shop.common.util.HttpUtil.post;

@Slf4j
@Service
@AllArgsConstructor
public class OrderRefundServiceImpl extends ServiceImpl<OrderRefundMapper, OrderRefund> implements OrderRefundService {

    private final OrderRefundMapper orderRefundMapper;

    private final OrderRefundRecordMapper orderRefundRecordMapper;
    private final OrderRefundSkuMapper orderRefundskuMapper;
    private final OrderService orderService;
    private final ProductService productService;
    private final SkuService skuService;
    private final OrderItemService orderItemService;
    private final RefundOrderSettlementService refundOrderSettlementService;
    private final RefundDeliveryService refundDeliveryService;
    private final OrderSettlementService orderSettlementService;
    private final OrderSettlementMapper orderSettlementMapper;
    private final ShopDetailService shopDetailService;
    private final ShopWalletMapper shopWalletMapper;
    private final OrderMapper orderMapper;
    private final OrderItemMapper orderItemMapper;
    private final MapperFacade mapperFacade;
    private final ShopWalletLogService shopWalletLogService;
    private final ApplicationContext applicationContext;
    private final PayManagerService payManagerService;
    private final Snowflake snowflake;
    private final HBSignUtil hbSignUtil;
    private final OrderRefundSkuMapper orderRefundSkuMapper;

    @Autowired
    private ExportTaskService exportTaskService;

    //导出
    // 线程池配置
    private final ExecutorService exportExecutor = Executors.newFixedThreadPool(
            5,
            new ThreadFactoryBuilder()
                    .setNameFormat("refund-order-export-thread-%d")
                    .setDaemon(true)
                    .build()
    );
    /**
     * 获取分页对象
     */
    @Override
    public IPage<OrderRefundDto> getPage(Page page, OrderRefundDto orderRefundDto, String startTime, String endTime) {
        IPage<OrderRefundDto> orderRefundDtoIPage = orderRefundMapper.getPage(page, orderRefundDto, startTime, endTime);
        List<OrderRefundDto> records = orderRefundDtoIPage.getRecords();
        for (OrderRefundDto record : records) {
            getRefundTypeByOrderItem2(record);
        }
        return orderRefundDtoIPage;
    }

    /**
     * 根据编码查询退款单信息
     *
     * @param refundSn 退款单编码
     * @return 退款包装对象
     */
    @Override
    public OrderRefundDto getOrderRefundByRefundSn(String refundSn) {
        OrderRefundDto orderRefundDto = orderRefundMapper.getOrderRefundByRefundSn(refundSn);
        if (orderRefundDto == null) {
            return null;
        }
        //获取总数，如果为0则为全部
        if (orderRefundDto.getGoodsNum() == 0) {
            Order order = orderService.getOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNumber, orderRefundDto.getOrderNumber()));
            orderRefundDto.setGoodsNum(order.getProductNums());
        }
        // 判断退款单类型（1:整单退款,2:单个物品退款）
        getRefundTypeByOrderItem2(orderRefundDto);
        orderRefundDto.setIsCancel(true);
        // 如果是单项退款,且订单状态为待发货，则判断退款操作是否可以取消
        if (orderRefundDto.getRefundType().equals(RefundType.SINGLE.value()) && orderRefundDto.getStatus().equals(OrderStatus.PADYED.value())) {
            Integer orderRefundNums = orderRefundMapper.getOrderRefundCountByRefundSn(orderRefundDto.getRefundSn());
            int orderItemNums = orderItemService.count(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, orderRefundDto.getOrderNumber()));
            //订单退款项等于订单项(多个订单项) -> 该订单已全部进行退款申请 -> 不能进行取消退款操作
            if (orderItemNums > 1 && orderRefundNums.equals(orderItemNums)) {
                orderRefundDto.setIsCancel(false);
            }
        }
        orderRefundDto.setRecords(orderRefundRecordMapper.selectList(new LambdaQueryWrapper<OrderRefundRecord>()
                .eq(OrderRefundRecord::getOrderRefundId, orderRefundDto.getRefundId())
                .orderByDesc(OrderRefundRecord::getSort)));
        return orderRefundDto;
    }

    /**
     * 根据退款ID获取退款单信息
     *
     * @param refundId 退款单ID
     * @return
     */
    @Override
    public OrderRefundDto getOrderRefundById(Long refundId, Long shopId) {
        OrderRefundDto orderRefundDto = orderRefundMapper.getById(refundId, shopId);
        if (orderRefundDto == null) {
            throw new GlobalException("无法获取退款订单信息");
        }
        // 判断退款单类型（1:整单退款,2:单个物品退款）
        getRefundTypeByOrderItem(orderRefundDto);

        //收货地址对象
        orderRefundDto.setRefundDelivery(refundDeliveryService.getOne(
                new LambdaQueryWrapper<RefundDelivery>().eq(RefundDelivery::getRefundSn, orderRefundDto.getRefundSn())));
        return orderRefundDto;
    }

    /**
     * 生成退款信息和比率信息
     *
     * @param shopId 商家id
     */
    @Override
    public StatisticsRefundParam getOrderRefundByShopId(Long shopId, Date startTime, Date endTime) {
        StatisticsRefundParam refundParam = orderRefundMapper.getRefundByShopId(shopId, startTime, endTime);
        OrderPayParam oderParam = orderService.getPayUserCountByshopId(shopId, startTime, endTime);
        StatisticsRefundParam yesterdayRefundParam = orderRefundMapper.getRefundByShopId(shopId, DateUtil.beginOfDay(DateUtil.yesterday()),
                DateUtil.endOfDay(DateUtil.yesterday()));
        OrderPayParam yesterdayOderParam = orderService.getPayUserCountByshopId(shopId, DateUtil.beginOfDay(DateUtil.yesterday()),
                DateUtil.endOfDay(DateUtil.yesterday()));
        StatisticsRefundParam lastWeekRefundParam = orderRefundMapper.getRefundByShopId(shopId, DateUtil.beginOfDay(DateUtil.lastWeek()),
                DateUtil.endOfDay(DateUtil.lastWeek()));
        OrderPayParam lastWeekOderParam = orderService.getPayUserCountByshopId(shopId, DateUtil.beginOfDay(DateUtil.lastWeek()),
                DateUtil.endOfDay(DateUtil.lastWeek()));
        double yesterdayRate = 0.00;
        double lastWeekRate = 0.00;
        double refundRate = 0.00;
        double yesterdayRefundRate = 0.00;
        double lastweekRefundRate = 0.00;
        //金额比率
        if (yesterdayRefundParam.getPayActualTotal() != 0) {
            yesterdayRate = Arith.div(Arith.mul(refundParam.getPayActualTotal(), 100), yesterdayRefundParam.getPayActualTotal(), 2);
        }
        if (lastWeekRefundParam.getPayActualTotal() != 0) {
            lastWeekRate = Arith.div(Arith.mul(refundParam.getPayActualTotal(), 100), lastWeekRefundParam.getPayActualTotal(), 2);
        }
        //退款比率
        if (oderParam.getPayOrderCount() != 0) {
            refundRate = Arith.div(Arith.mul(refundParam.getRefundCount(), 100), oderParam.getPayOrderCount(), 2);
        }
        if (yesterdayOderParam.getPayOrderCount() != 0) {
            yesterdayRefundRate = Arith.div(Arith.mul(refundParam.getRefundCount(), 100), yesterdayOderParam.getPayOrderCount(), 2);
        }
        if (lastWeekOderParam.getPayOrderCount() != 0) {
            lastweekRefundRate = Arith.div(Arith.mul(lastWeekRefundParam.getRefundCount(), 100), lastWeekOderParam.getPayOrderCount(), 2);
        }
        yesterdayRefundRate = Arith.sub(refundRate, yesterdayRefundRate);
        lastweekRefundRate = Arith.sub(refundRate, lastweekRefundRate);
        refundParam.setYesterdayAmountRate(yesterdayRate);
        refundParam.setSevenDayAmountRate(lastWeekRate);
        refundParam.setRefundRate(refundRate);
        refundParam.setYesterdayRefundRate(yesterdayRefundRate);
        refundParam.setSevenDayRefundRate(lastweekRefundRate);
        return refundParam;
    }


    /**
     * 生成退款信息和分段比率信息
     *
     * @param shopId 商家id
     */
    @Override
    public List<StatisticsRefundParam> getOrderRefundByShopIdAndDay(Long shopId, Date startTime, Date endTime) {
        List<StatisticsRefundParam> refundList = orderRefundMapper.getRefundByShopIdAndDay(shopId, startTime, endTime);
        List<OrderPayParam> orderList = orderMapper.getPayOrderByTime(shopId, startTime, endTime);
        List<StatisticsRefundParam> refundNewList = new ArrayList<>();
        for (int i = 0; i < refundList.size(); i++) {
            StatisticsRefundParam refundParam = refundList.get(i);
            if (i + 1 > orderList.size()) {
                break;
            }
            OrderPayParam orderParam = orderList.get(i);
            Double rate = 0.00;
            if (orderParam.getPayOrderCount() != 0) {
                rate = Arith.div(Arith.mul(refundParam.getRefundCount(), 100), orderParam.getPayOrderCount(), 2);

            } else if (refundParam.getRefundCount() != 0) {
                rate = 100.00;
            }

            refundParam.setRefundRate(rate);
            refundList.set(i, refundParam);
            if (i % 7 == 0) {
                refundParam.setRefundDateToString(DateUtil.formatDate(refundParam.getRefundDate()));
                refundNewList.add(refundParam);
            }
        }
        return refundNewList;
    }

    /**
     * 根据商品名生成退款排行
     *
     * @param shopId 商家id
     */
    @Override
    public List<StatisticsRefundParam> getRefundRankingByProd(Long shopId, Date beginTime, Date endTime) {
        List<StatisticsRefundParam> ranking = orderRefundMapper.getRefundRankingByProd(shopId, beginTime, endTime);
        return ranking;
    }

    /**
     * 根据退款原因生成退款排行
     *
     * @param shopId 商家id
     */
    @Override
    public List<StatisticsRefundParam> getRefundRankingByReason(Long shopId, Date beginTime, Date endTime) {
        List<StatisticsRefundParam> ranking = orderRefundMapper.getRefundRankingByReason(shopId, beginTime, endTime);
        List<StatisticsRefundParam> rank = new ArrayList<>();
        double sum = 0.00;
        for (StatisticsRefundParam refundParam : ranking) {
            sum = Arith.add(sum, refundParam.getPayActualTotal());
        }
        for (StatisticsRefundParam refundParam : ranking) {
            refundParam.setRefundRate(Arith.div(Arith.mul(refundParam.getPayActualTotal(), 100), sum, 2));
            rank.add(refundParam);
        }
        return rank;
    }

    /**
     * 生成退款单
     *
     * @param orderRefund 退款对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderRefund applyRefund(OrderRefund orderRefund) {
        // 生成退款单
        save(orderRefund);
        // 更新订单状态
        Order order = orderService.getById(orderRefund.getOrderId());
        Integer refundType = orderRefund.getRefundType();
        if (Objects.equals(refundType, RefundType.ALL.value())) {
            order.setRefundStatus(RefundStatusEnum.APPLY.value());
        } else {
            order.setRefundStatus(RefundStatusEnum.APPLY.value());
        }
        orderService.updateById(order);
        return orderRefund;
    }

    /**
     * 判断退款单类型（1:整单退款,2:单个物品退款）
     */
    private void getRefundTypeByOrderItem(OrderRefundDto orderRefundDto) {
        if (Objects.equals(orderRefundDto.getRefundType(), RefundType.ALL.value())) {
            List<OrderItem> items = orderItemService.getOrderItemsByOrderNumber(orderRefundDto.getOrderNumber());
            orderRefundDto.setOrderItems(items);
            orderRefundDto.setRefundScore(items.stream().mapToInt(OrderItem::getUseScore).sum());
        } else {
            OrderItem item = orderItemService.getById(orderRefundDto.getOrderItemId());
            orderRefundDto.getOrderItems().add(item);
            orderRefundDto.setRefundScore(item.getUseScore());
        }
    }

    private void getRefundTypeByOrderItem2(OrderRefundDto orderRefundDto) {
        int oldSum = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>()
                        .eq(OrderItem::getOrderNumber, orderRefundDto.getOrderNumber())).stream().mapToInt(OrderItem::getProdCount)
                .sum();
        List<OrderItem> item = orderItemService.getRefundTypeByOrderItem2(orderRefundDto.getRefundId());
        int newSum = item.stream().mapToInt(OrderItem::getProductCount).sum();
        if (!item.isEmpty()) {
            orderRefundDto.setGoodsTotal(item.stream().map(OrderItem::getGoodsTotal).reduce(0.0, Double::sum));
            if (oldSum == newSum) {
                //代表全部退，所以需要增加运费显示
                double goodsTotal = Arith.add(BigDecimal.valueOf(orderRefundDto.getGoodsTotal()), BigDecimal.valueOf(orderRefundDto.getFreightAmount()));
                orderRefundDto.setGoodsTotal(goodsTotal);
            }
            item.forEach(c -> c.setRefundCount(orderItemService.refundCount(c.getOrderItemId())));
        }
        orderRefundDto.setOrderItems(item);
    }


    /**
     * 卖家处理（退款/返回退货地址）
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderRefundDto processRefundOrder(OrderRefundParam orderRefundParam, Long shopId) {
        OrderRefundDto orderRefundDto = getOrderRefundById(orderRefundParam.getRefundId(), shopId);
        if (Objects.equals(-1, orderRefundDto.getReturnMoneySts())) {
            throw new GlobalException("买家已取消申请");
        }
        Date now = new Date();


        // 是否同意退款
        if (Objects.equals(orderRefundParam.getRefundSts(), RefundStsType.DISAGREE.value())) {
            // 不同意退款
            disagreeRefund(orderRefundParam, orderRefundDto, 1);
        } else {
            // 正在处理退款的状态
            orderRefundDto.setReturnMoneySts(ReturnMoneyStsType.PROCESSING.value());

            // 判断是退款退货/仅退款(1:仅退款 2:退款退货)
            if (Objects.equals(orderRefundDto.getApplyType(), 1)) {
                // 同意退款
                agreeRefund(orderRefundDto);
                // 减少商家结算金额
                subShopSettlementAmount(orderRefundDto);
            } else {
                // 同意退款退货操作
                // 设置退货物流信息
//                RefundAddr refundAddr = refundAddrService.getById(orderRefundParam.getRefundAddrId());
//                if (refundAddr == null) {
//                    throw new GlobalException("请设置退货物流信息");
//                }
                ShopDetail shopDetailByShopId = shopDetailService.getShopDetailByShopId(orderRefundDto.getShopId());
                RefundDelivery refundDelivery = new RefundDelivery();
                refundDelivery.setShopId(orderRefundDto.getShopId());
                refundDelivery.setRefundSn(orderRefundDto.getRefundSn());
                refundDelivery.setUserId(orderRefundDto.getUserId());
                refundDelivery.setReceiverName(shopDetailByShopId.getShopName());
                refundDelivery.setReceiverMobile(shopDetailByShopId.getMobile());
//                refundDelivery.setReceiverTelephone(refundAddr.getReceiverTelephone());
//                refundDelivery.setReceiverPostCode(refundAddr.getPostCode());
                String addr = shopDetailByShopId.getProvince() + shopDetailByShopId.getCity() + shopDetailByShopId.getArea() + shopDetailByShopId.getShopAddress();
                refundDelivery.setReceiverAddr(addr);
                refundDelivery.setCreateTime(new Date());
                refundDelivery.setPayer(orderRefundParam.getPayer());
                refundDeliveryService.save(refundDelivery);
            }
        }

        // 设置卖家备注
        orderRefundDto.setSellerMsg(orderRefundParam.getSellerMsg());
        // 受理时间
        orderRefundDto.setHandelTime(now);
        // 更新时间
        orderRefundDto.setUpdateTime(now);

        // 更新数据
        updateById(orderRefundDto);
        return orderRefundDto;
    }

    /**
     * 收到货同意退款
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderRefundDto returnMoney(OrderRefundParam orderRefundParam, Long shopId) {
        // 获取退款单信息
        OrderRefundDto orderRefundDto = getOrderRefundById(orderRefundParam.getRefundId(), shopId);

        if (!Objects.equals(ReturnMoneyStsType.CONSIGNMENT.value(), orderRefundDto.getReturnMoneySts())) {
            throw new GlobalException("订单状态已经发生改变，请勿重复操作");
        }
        if (Objects.equals(-1, orderRefundDto.getReturnMoneySts())) {
            throw new GlobalException("买家已取消申请");
        }
        Date now = new Date();

        // 是否同意退款
        if (Objects.equals(orderRefundParam.getRefundSts(), RefundStsType.AGREE.value())) {
            // 减少商家结算金额
            subShopSettlementAmount(orderRefundDto);

            // 同意操作
            orderRefundDto.setReturnMoneySts(ReturnMoneyStsType.RECEIVE.value());
            // 同意退款
            agreeRefund(orderRefundDto);

        } else {
            disagreeRefund(orderRefundParam, orderRefundDto, 2);
        }

        // 是否收到货
        orderRefundDto.setIsReceiver(orderRefundParam.getIsReceiver());
        // 收货时间
        orderRefundDto.setReceiveTime(now);
        // 更新时间
        orderRefundDto.setUpdateTime(now);

        // 更新数据
        updateById(orderRefundDto);

        return orderRefundDto;
    }

    /**
     * 减少商家结算金额/未结算金额
     */
    private void subShopSettlementAmount(OrderRefundDto orderRefundDto) {
        Long shopId = orderRefundDto.getShopId();
        // 同意退款，判断商家是否还有金额进行退款
        Order order = orderService.getOrderByOrderNumber(orderRefundDto.getOrderNumber());
        if (order == null) {
            throw new GlobalException("未找到该订单信息");
        }
        double shopRealRefundAmount = orderRefundDto.getRefundAmount();

        // 订单发起退款时，扣除商家金额应该加上平台部分
        // 如果订单100元，平台出10元给商家（如平台10元优惠券，会员折扣9折），用户支付90元，此时商家结算时，要拿到100元，。
        // 当用户进行退款，有一部分钱是平台出的，平台出的这部分钱，要将平台出的这部分钱按数据库存的平台优惠金额从商家那里扣除，如用户退90块，商家结算减少100块。
        if (Objects.nonNull(order.getPlatformAmount()) && order.getPlatformAmount() > 0) {
            if (Objects.equals(orderRefundDto.getRefundType(), RefundType.ALL.value())) {
                shopRealRefundAmount = Arith.add(shopRealRefundAmount, order.getPlatformAmount());
            } else {
                OrderItem item = orderItemService.getById(orderRefundDto.getOrderItemId());
                shopRealRefundAmount = Arith.add(shopRealRefundAmount, item.getPlatformShareReduce());
            }
        }

        // 店铺真正退款的金额是不用退分销员的那部分的
        // 如果订单100元，分销10元，10元的分销费用由商家出，此时商家结算时，拿到90元。
        // 当用户进行退款，退1块的时候，分销会无效，此时商家拿回给出去的10元分销费用，并将1元给到退款用户，此时商家因为退款赚9元。 shopRealRefundAmount = -9
        // 当用户进行退款，退11块的时候，分销会无效，此时商家拿回给出去的10元分销费用，并将11元给到退款用户，此时商家因为退款亏1元。shopRealRefundAmount = 1
        if (orderRefundDto.getDistributionTotalAmount() != null) {
            shopRealRefundAmount = Arith.sub(shopRealRefundAmount, orderRefundDto.getDistributionTotalAmount());
        }

        ShopWallet shopWallet = shopWalletMapper.selectOne(new LambdaQueryWrapper<ShopWallet>().eq(ShopWallet::getShopId, shopId));
        ShopWallet newShopWallet = mapperFacade.map(shopWallet, ShopWallet.class);

        // 已确认收货的订单扣除已结算的金额
        if (Objects.equals(order.getHbOrderStatus(), OrderStatus.SUCCESS.value())) {
            // 平台把退款金额归还商家，商家退还金额到用户
            if (shopWallet.getSettledAmount() < shopRealRefundAmount) {
                throw new GlobalException("您的可提现金额不足，无法进行退款");
            }
            newShopWallet.setSettledAmount(Arith.sub(shopWallet.getSettledAmount(), shopRealRefundAmount));
            newShopWallet.setTotalSettledAmount(Arith.sub(shopWallet.getTotalSettledAmount(), shopRealRefundAmount));
        }
        // 1. 订单未确认收货则扣未结算金额
        // 2. 商家撤销拼团活动时失效拼团时，将待成团的队伍进行退款
        if (Objects.equals(order.getHbOrderStatus(), OrderStatus.PADYED.value()) || Objects.equals(order.getHbOrderStatus(), OrderStatus.CONSIGNMENT.value()) || Objects.equals(order.getHbOrderStatus(), OrderStatus.WAIT_GROUP.value())) {

            if (shopWallet.getUnsettledAmount() < shopRealRefundAmount) {
                throw new GlobalException("您的待结算金额不足，无法进行退款");
            }
            newShopWallet.setUnsettledAmount(Arith.sub(shopWallet.getUnsettledAmount(), shopRealRefundAmount));
        }
        newShopWallet.setUpdateTime(new Date());
        // 添加钱包日志记录
        shopWalletLogService.saveShopWalletLog(shopWallet, newShopWallet, ShopWalletChangeReason.ORDER_REFUND, orderRefundDto.getOrderNumber());

        // 更新商家钱包信息
        if (shopWalletMapper.updateById(newShopWallet) != 1) {
            throw new GlobalException("更新店铺钱包信息失败");
        }
    }

    /**
     * 不同意退款
     *
     * @param orderRefundParam
     * @param orderRefundDto
     * @param type             1 用户发起是拒绝  2 商家收货后拒绝
     */
    private void disagreeRefund(OrderRefundParam orderRefundParam, OrderRefundDto orderRefundDto, Integer type) {
        // 不同意退款
        orderRefundDto.setReturnMoneySts(ReturnMoneyStsType.REJECT.value());
        orderRefundDto.setReturnMoneySts(ReturnMoneyStsType.FAIL.value());
        // 拒绝原因
        orderRefundDto.setRejectMessage(orderRefundParam.getRejectMessage());
        orderRefundDto.setRejectTime(new Date());

        // 更新订单
        Order order = orderService.getById(orderRefundDto.getOrderId());
        Integer orderRefundSuccessCount = orderRefundMapper.selectCount(new LambdaQueryWrapper<OrderRefund>()
                .eq(OrderRefund::getOrderId, orderRefundDto.getOrderId())
                .eq(OrderRefund::getReturnMoneySts, ReturnMoneyStsType.SUCCESS.value()));
        // 如果有订单项退款成功，则订单状态为部分退款成功，否则为退款失败
        if (orderRefundSuccessCount > 0) {
            order.setRefundStatus(RefundStatusEnum.PARTIAL_SUCCESS.value());
        } else {
            order.setRefundStatus(RefundStatusEnum.DISAGREE.value());
        }
        if (type == 2) {
            order.setHbOrderStatus(OrderStatus.CLOSE.value());
        }
        orderService.updateById(order);
    }

    /**
     * 买家提交物流信息
     *
     * @param orderRefund    退款单对象
     * @param refundDelivery 退款物流单对象
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitExpress(OrderRefund orderRefund, RefundDelivery refundDelivery) {
        refundDeliveryService.updateById(refundDelivery);
        updateById(orderRefund);
    }

    /**
     * 系统自动退款操作（批量）
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void systemAutoRefundBatch(List<OrderRefundDto> orderRefundDtoList) {
        for (OrderRefundDto orderRefundDto : orderRefundDtoList) {
            agreeRefund(orderRefundDto);
            update(orderRefundDto, new LambdaQueryWrapper<OrderRefund>()
                    .eq(OrderRefund::getRefundSn, orderRefundDto.getRefundSn()));
            // 减少商家未结算金额
            subShopSettlementAmount(orderRefundDto);

            try {
                submitWxRefund(orderRefundDto);
            } catch (YamiShopBindException e) {
                WxPayException wxPayException = (WxPayException) e.getObject();
                if (Objects.equals("订单已全额退款", wxPayException.getErrCodeDes())) {
                    continue;
                }
                throw e;
            }
        }
    }

    /**
     * 系统验证退款结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void verifyRefund(OrderRefundDto orderRefundDto, String payRefundId) {
        // 查询退款结算记录
        RefundOrderSettlement refundOrderSettlement = refundOrderSettlementService.getOne(
                new LambdaQueryWrapper<RefundOrderSettlement>().eq(RefundOrderSettlement::getRefundSn, orderRefundDto.getRefundSn()));

        // 判断退款结算记录是否为申请状态
        if (refundOrderSettlement == null || refundOrderSettlement.getRefundStatus() != 1) {
            throw new GlobalException("退款已处理，无需重复处理");
        }

        // 更新退款结算记录
        refundOrderSettlement.setPayRefundId(payRefundId);
        refundOrderSettlement.setRefundStatus(2);
        if (!refundOrderSettlementService.updateById(refundOrderSettlement)) {
            throw new GlobalException("服务器繁忙，请稍后再试");
        }
        // 更新订单
        Order order = orderService.getOrderByOrderNumber(orderRefundDto.getOrderNumber());
        int oldOrderStatus = order.getHbOrderStatus();

        // 退款成功（保存退款结算记录、更新订单、还原库存）
        refundSuccess(order, orderRefundDto);

        // 推送退款成功事件
        applicationContext.publishEvent(new OrderRefundSuccessEvent(orderRefundDto));

        // 非整单退款 && 以前订单没有结算（确认收货）&& 现在订单关闭了 && 因为退款导致订单关闭
        // 如果订单因为退款关闭，要进行结算给商家的操作，这个结算的计算是退款完成后结算的，所以不要随便改变顺序
        if (!Objects.equals(orderRefundDto.getRefundType(), RefundType.ALL.value())
                && !Objects.equals(oldOrderStatus, OrderStatus.SUCCESS.value())
                && Objects.equals(order.getHbOrderStatus(), OrderStatus.CLOSE.value())
                && Objects.equals(order.getCloseType(), OrderCloseType.REFUND.value())) {
            applicationContext.publishEvent(new ReceiptOrderEvent(order));
        }
    }

    /**
     * 同意退款操作（生成结算记录）
     */
    private void agreeRefund(OrderRefundDto orderRefundDto) {
        Date nowDate = new Date();
        // 查询支付记录
        OrderSettlement orderSettlement = orderSettlementService.getById(orderRefundDto.getSettlementId());
        if (orderSettlement == null) {
            throw new GlobalException("没有查询到支付记录，无法申请退款");
        }
        if (refundOrderSettlementService.count(new LambdaQueryWrapper<RefundOrderSettlement>().eq(RefundOrderSettlement::getRefundSn, orderRefundDto.getRefundSn())) > 0) {
            throw new GlobalException("订单正在进行退款结算，请勿重复操作");
        }

        // 生成退款结算记录
        RefundOrderSettlement refundOrderSettlement = new RefundOrderSettlement();
        refundOrderSettlement.setOrderNumber(orderRefundDto.getOrderNumber());
        refundOrderSettlement.setOrderPayNo(orderRefundDto.getOrderPayNo());
        refundOrderSettlement.setRefundSn(orderRefundDto.getRefundSn());
        refundOrderSettlement.setPayType(orderSettlement.getPayType());
        refundOrderSettlement.setPayTypeName(orderSettlement.getPayTypeName());
        refundOrderSettlement.setRefundAmount(orderRefundDto.getRefundAmount());
        refundOrderSettlement.setOrderTotalAmount(orderRefundDto.getOrderAmount());
        refundOrderSettlement.setUserId(orderRefundDto.getUserId());
        refundOrderSettlement.setRefundStatus(1);
        refundOrderSettlement.setCreateTime(nowDate);
        refundOrderSettlement.setUpdateTime(nowDate);
        refundOrderSettlementService.save(refundOrderSettlement);

        // 更新退款单信息
        orderRefundDto.setDecisionTime(nowDate);
        orderRefundDto.setUpdateTime(nowDate);
    }

    /**
     * 提交退款请求（向微信发起退款请求）
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void submitWxRefund(OrderRefundDto orderRefundDto) {
        // 判断是否已同意退款
        if (orderRefundDto.getDecisionTime() == null) {
            return;
        }
        // 查询支付记录
        OrderSettlement orderSettlement = orderSettlementService.getById(orderRefundDto.getSettlementId());
        RefundInfoDto refundInfo = new RefundInfoDto();
        refundInfo.setPayType(PayType.instance(orderSettlement.getPayType()));
        refundInfo.setPayNo(orderSettlement.getPayNo());
        refundInfo.setRefundSn(orderRefundDto.getRefundSn());
        refundInfo.setRefundAmount(orderRefundDto.getRefundAmount());
        refundInfo.setNotifyUrl("/order/refund/result/" + orderSettlement.getPayType());

        // 获取支付的时候的支付金额
        double payAmountWhenPay = orderSettlementMapper.getPayAmountWhenPay(orderSettlement.getPayNo());
        refundInfo.setPayAmount(payAmountWhenPay);

        boolean refundSuccess = payManagerService.doRefund(refundInfo);
        if (refundSuccess) {
            verifyRefund(orderRefundDto, "");
        }
    }

    @Override
    public double sumRefundSuccessAmountByOrderId(Long orderId) {
        return orderRefundMapper.sumRefundSuccessAmountByOrderId(orderId);
    }

    @Override
    public List<OrderRefund> getProcessingOrderRefundByOrderId(Long orderId) {
        return orderRefundMapper.getProcessingOrderRefundByOrderId(orderId);
    }

    /**
     * 退款成功（更新退款结算记录、更新订单、还原库存）
     */
    private void refundSuccess(Order order, OrderRefundDto orderRefundDto) {
        if (Objects.equals(orderRefundDto.getRefundType(), RefundType.ALL.value())) {
            order.setHbOrderStatus(OrderStatus.CLOSE.value());
            order.setCancelTime(new Date());
            order.setUpdateTime(new Date());
            order.setCloseType(OrderCloseType.REFUND.value());
            order.setRefundStatus(RefundStatusEnum.SUCCEED.value());
        } else {
            // 查看是否已经达到了所有的订单数量，如是则订单关闭
            int totalRefundNum = 0;
            // 已退款单
            List<OrderRefund> orderRefundList = orderRefundMapper.selectList(new LambdaQueryWrapper<OrderRefund>()
                    .eq(OrderRefund::getOrderId, orderRefundDto.getOrderId())
                    .eq(OrderRefund::getReturnMoneySts, ReturnMoneyStsType.SUCCESS.value())
            );
            if (CollectionUtils.isNotEmpty(orderRefundList)) {
                totalRefundNum += orderRefundList.stream().mapToInt(OrderRefund::getGoodsNum).sum();
            }

            // 整个订单完成退款的时候
            if (totalRefundNum + orderRefundDto.getGoodsNum() >= order.getProductNums()) {
                order.setHbOrderStatus(OrderStatus.CLOSE.value());
                order.setCancelTime(new Date());
                order.setUpdateTime(new Date());
                order.setCloseType(OrderCloseType.REFUND.value());
                order.setRefundStatus(RefundStatusEnum.SUCCEED.value());
            } else {
                order.setRefundStatus(RefundStatusEnum.PARTIAL_SUCCESS.value());
            }

            // 退款成功后，订单没有关闭，且发货订单项 + 退款成功订单项 = 订单项总数量 ，订单状态改为待收货
            if (!Objects.equals(order.getHbOrderStatus(), OrderStatus.CLOSE.value()) && Objects.equals(order.getHbOrderStatus(), OrderStatus.PADYED.value())) {
                List<OrderItem> list = orderItemService.list(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderNumber, order.getOrderNumber()));
                Integer count = 0;
                for (OrderItem orderItem : list) {
                    if (Objects.equals(orderItem.getStatus(), 0)) {
                        count++;
                    }
                }
                if (orderRefundList.size() + count + orderRefundDto.getOrderItems().size() >= list.size()) {
                    order.setHbOrderStatus(OrderStatus.CONSIGNMENT.value());
                    order.setDvyTime(new Date());
                }
            }
        }
        orderService.updateById(order);

        // 还原库存
        OrderRefundDto orderRefund = getOrderRefundByRefundSn(orderRefundDto.getRefundSn());
        List<OrderItem> orderItems = orderRefund.getOrderItems();
        for (OrderItem orderItem : orderItems) {
            Product product = productService.getById(orderItem.getProdId());
            Sku productSuk = skuService.getSkuBySkuId(orderItem.getSkuId());

            int totalStocks = product.getTotalStocks();
            int skuStocks = productSuk.getStocks();
            if (Objects.equals(orderRefundDto.getRefundType(), RefundType.ALL.value())) {
                // 全部退款，还原全部数量
                totalStocks += orderItem.getProdCount();
                skuStocks += orderItem.getProdCount();
            } else {
                // 部分退款，还原退款数量
                totalStocks += orderRefund.getGoodsNum();
                skuStocks += orderRefund.getGoodsNum();
            }
            product.setTotalStocks(totalStocks);
            productSuk.setStocks(skuStocks);
            productService.updateById(product);
            skuService.updateById(productSuk);
            skuService.removeSkuCacheBySkuId(productSuk.getSkuId(), product.getProdId());
        }

        // 退款成功
        orderRefundDto.setReturnMoneySts(ReturnMoneyStsType.SUCCESS.value());
        orderRefundDto.setRefundTime(new Date());
        updateById(orderRefundDto);
        // 退款时分销需要计算 orderItems
        order.setOrderItems(orderItems);

    }

    /**
     * 取消申请超时的订单，无论该超时订单处于任何状态
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void cancelWhenTimeOut(List<OrderRefund> orderRefundList) {
        if (CollectionUtils.isEmpty(orderRefundList)) {
            return;
        }
        Date now = new Date();
        for (OrderRefund orderRefund : orderRefundList) {
            orderRefund.setReturnMoneySts(ReturnMoneyStsType.FAIL.value());
            Order order = orderService.getById(orderRefund.getOrderId());
            if (ObjectUtil.isNotEmpty(order)) {
                order.setRefundStatus(4);
                orderService.updateById(order);
            }
            orderRefund.setSellerMsg("申请退款超时");
            orderRefund.setShipTime(now);
            orderRefund.setUpdateTime(now);

        }
        updateBatchById(orderRefundList);
    }

    @Override
    public boolean checkRefundDate(Order order) {
        // 判断是否超过支持的退款天数
        if (Objects.equals(order.getHbOrderStatus(), OrderStatus.SUCCESS.value())) {
            long finallyTime = order.getFinallyTime().getTime();
            long currentTime = System.currentTimeMillis();
            int miniTime = Constant.MAX_FINALLY_REFUND_TIME * 24 * 60 * 60 * 1000;
            if (currentTime - finallyTime > miniTime) {
                return false;
            }
        }
        return true;
    }

    @Override
    public double sumRefundSuccessPlatformAmountByOrderId(Long orderId) {
        return orderRefundMapper.sumRefundSuccessPlatformAmountByOrderId(orderId);
    }

    @Override
    public void overTimeRefundOrder(com.yami.shop.bean.app.param.OrderRefundParam orderRefundParam) {
        // 获取订单信息
        Order order = orderService.getOrderByOrderNumber(orderRefundParam.getOrderNumber());
        if (ObjectUtil.isEmpty(order)) {
            throw new GlobalException("此订单不存在，无法退货退款");
        }
        if (!Objects.equals(order.getIsPayed(), 1)) {
            throw new GlobalException("当前订单还未付款，无法申请");
        }

        if (Objects.equals(order.getHbOrderStatus(), OrderStatus.CLOSE.value())) {
            throw new GlobalException("当前订单已失败，不允许退款");
        }

        if (Objects.equals(order.getHbOrderStatus(), OrderStatus.WAIT_GROUP.value())) {
            throw new GlobalException("当前订单正在等待成团状态，需等待成团才能进行下一步操作");
        }

        if (orderRefundParam.getRefundAmount() > order.getActualTotal()) {
            throw new GlobalException("退款金额已超出订单金额，无法申请");
        }

        //待收货 -> 整单退款 -> 退款金额 < 订单金额 - 运费金额
        if (Objects.equals(order.getHbOrderStatus(), OrderStatus.CONSIGNMENT.value()) && orderRefundParam.getRefundType().equals(RefundType.ALL.value())) {
            Double refundAmount = Arith.sub(order.getActualTotal(), order.getFreightAmount());
            if (orderRefundParam.getRefundAmount() > refundAmount) {
                throw new GlobalException("退款金额已超出订单金额，无法申请");
            }
        }

        if (Objects.equals(order.getOrderType(), Constant.ORDER_TYPE_SCORE)) {
            throw new GlobalException("积分商品，无法退款");
        }
        if (Objects.equals(orderRefundParam.getRefundType(), RefundType.ALL.value()) && (!Objects.isNull(order.getRefundStatus()) && !Objects.equals(order.getRefundStatus(), RefundStatusEnum.DISAGREE.value()))) {
            throw new GlobalException("66该订单已有商品正在退款中，不能再进行整单退款");
        }

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

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

        for (OrderRefund orderRefund : orderRefunds) {
            if (Objects.equals(RefundType.ALL.value(), orderRefund.getRefundType())) {
                throw new GlobalException("该订单正在进行整单退款，无法进行新的退款操作");
            }
            if (Objects.equals(orderRefund.getOrderItemId(), orderRefundParam.getOrderItemId())) {
                throw new GlobalException("该商品正在进行退款中，无法进行新的退款操作");
            }
        }

        // 如果存在分销订单，则计算分销总金额
        List<OrderItem> orderItemList = orderItemService.getOrderItemsByOrderNumber(order.getOrderNumber());
        // 判断退款单类型（1:整单退款,2:单个物品退款）
        if (orderRefundParam.getRefundType().equals(RefundType.ALL.value())) {
            // 全部物品退款
            // 计算该订单项的分销金额
            newOrderRefund.setDistributionTotalAmount(orderService.sumTotalDistributionAmountByOrderItem(orderItemList));
            // 计算平台退款金额（退款时将这部分钱退回给平台，所以商家要扣除从平台这里获取的金额）
            newOrderRefund.setPlatformRefundAmount(order.getPlatformAmount());
        } else {
            // 部分物品退款
            OrderItem orderItem = orderItemService.getOne(new LambdaQueryWrapper<OrderItem>()
                    .eq(OrderItem::getOrderItemId, orderRefundParam.getOrderItemId())
                    .eq(OrderItem::getOrderNumber, orderRefundParam.getOrderNumber()));
            if (orderItem == null) {
                throw new GlobalException("该物品在订单中不存在");
            }
            boolean isCanRefund = false;
            //  查看是否有支付金额和积分都为空的订单，有则抛出异常
            for (OrderItem item : orderItemList) {
                if (item.getActualTotal() <= 0.0 && item.getUseScore() <= 0.0) {
                    isCanRefund = true;
                    break;
                }
            }
            if (isCanRefund) {
                throw new GlobalException("该订单部分订单项支付金额和积分为0，无法使用部分退款！");
            }

            if (order.getPlatformAmount() > 0 && !Arith.isEquals(orderRefundParam.getRefundAmount(), orderItem.getActualTotal())) {
                throw new GlobalException("该订单有使用平台优惠，无法使用部分退款！");
            }
            // 计算该订单项的分销金额
            newOrderRefund.setDistributionTotalAmount(orderService.sumTotalDistributionAmountByOrderItem(Collections.singletonList(orderItem)));

            // 计算平台退款金额（退款时将这部分钱退回给平台，所以商家要扣除从平台这里获取的金额）
            //此处设置实际平台抵现金额
            newOrderRefund.setPlatformRefundAmount(orderItem.getPlatformShareReduce());

            // 退款物品数量为null或者0时，则为退款全部数量
            if (orderRefundParam.getGoodsNum() <= 0) {
                orderRefundParam.setGoodsNum(orderItem.getProdCount());
            }

            // 判断退款数量是否溢出
            if (orderRefundParam.getGoodsNum() > orderItem.getProdCount()) {
                throw new GlobalException("退款物品数量已超出订单中的数量，不允许申请");
            }

            // 判断退款金额是否超出订单金额
            double refundSingleAmount = Arith.div(orderRefundParam.getRefundAmount(), orderRefundParam.getGoodsNum(), 3);
            double singleAmount = Arith.div(orderItem.getActualTotal(), orderItem.getProdCount(), 3);
            if (refundSingleAmount > orderItem.getProductTotalAmount() || refundSingleAmount > singleAmount) {
                throw new GlobalException("退款金额已超出订单金额，无法申请");
            }

            // 一个订单项只能申请一次退款
            for (OrderRefund orderRefund : orderRefunds) {
                if (Objects.equals(orderRefund.getOrderId(), orderItem.getOrderItemId())) {
                    throw new GlobalException("退款订单项已处理，请勿重复申请");
                }
            }
        }

        newOrderRefund.setShopId(order.getShopId());
        newOrderRefund.setUserId(order.getUserId());
        newOrderRefund.setOrderId(order.getOrderId());
        newOrderRefund.setRefundSn(String.valueOf(snowflake.nextId()));
        newOrderRefund.setRefundType(orderRefundParam.getRefundType());

        newOrderRefund.setRefundAmount(orderRefundParam.getRefundAmount());
        if (Objects.equals(RefundType.ALL.value(), orderRefundParam.getRefundType())) {
            newOrderRefund.setOrderItemId(0L);
        } else {
            newOrderRefund.setOrderItemId(orderRefundParam.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()));
                }
            }
        }

        newOrderRefund.setGoodsNum(orderRefundParam.getGoodsNum());
        newOrderRefund.setApplyType(orderRefundParam.getApplyType());
        if (Objects.equals(orderRefundParam.getApplyType(), 2)) {
            newOrderRefund.setIsReceiver(true);
        } else {
            newOrderRefund.setIsReceiver(orderRefundParam.getIsReceiver());
        }
        newOrderRefund.setBuyerReason(orderRefundParam.getBuyerReason());
        newOrderRefund.setBuyerDesc(orderRefundParam.getBuyerDesc());
        newOrderRefund.setBuyerMobile(orderRefundParam.getBuyerMobile());
        newOrderRefund.setPhotoFiles(orderRefundParam.getPhotoFiles());
        newOrderRefund.setReturnMoneySts(ReturnMoneyStsType.APPLY.value());
        newOrderRefund.setApplyTime(new Date());
        newOrderRefund.setUpdateTime(new Date());
        this.applyRefund(newOrderRefund);
    }


    //*************************** 售后接口 ***************************
    @Override
    public String createRefundOrder(String channelOrderId, String afterSaleOrder) {
        log.info("createRefundOrder 退款单推送单号开始channelOrderId：{},afterSaleOrder:{}", channelOrderId, afterSaleOrder);
        HBBaseReq<Object> build = HBBaseReq.create();
        build.setAppId(hbSignUtil.getAppId());

        // 3. 构建外层请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("channelOrderId", channelOrderId);
        requestBody.put("afterSaleOrder", afterSaleOrder);
        // 4. 将整个JSON对象序列化为字符串并设置
        build.setBody(JSON.toJSONString(requestBody));

        build.setSign(hbSignUtil.signMd5(build));
        log.info("post 退款单推送单号参数：{}", JSON.toJSONString(build));
        String post = post(hbSignUtil.getHBHost() + "/api/refund/asyncSave", build);
        log.info("post 退款单推送结果：{}", post);
        return post;
    }

    @Override
    public String changeStatus(String afterSaleOrder, Integer refundStatus) {
        HBBaseReq<Object> build = HBBaseReq.create();
        build.setAppId(hbSignUtil.getAppId());
        OrderRefund orderRefund = orderRefundMapper.selectOne(new LambdaQueryWrapper<OrderRefund>().eq(OrderRefund::getRefundSn, afterSaleOrder));
        // 3. 构建外层请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("afterSaleOrder", afterSaleOrder);
//        退款单状态 10:待审核 20:处理中 30:驳回退款 40:撤销退款 60:待退货（一审同意） 65:待确认收货（二审待审核） 70:退款完成
        requestBody.put("refundStatus", refundStatus);
        requestBody.put("timestamp", orderRefund.getApplyTime().getTime());

//        deliveryMan 退货的配送员名称
//        deliveryMobile 退货的配送员电话
//        deliveryManNo 退货的配送员编号

        // 4. 将整个JSON对象序列化为字符串并设置
        build.setBody(JSON.toJSONString(requestBody));
        build.setSign(hbSignUtil.signMd5(build));
        log.info("post 退款单推送单号参数：{}", JSON.toJSONString(build));
        String post = post(hbSignUtil.getHBHost() + "/api/refund/changeStatus", build);
        log.info("post 退款单推送结果：{}", post);

        return post;
    }

    @Override
    public HBR details(JSONObject hBRequest) {
        ThirdPartyRefundRequest thirdPartyRefundRequest = new ThirdPartyRefundRequest();
        try {
            JSONObject bodyStr = hBRequest.getJSONObject("body");
            log.info("退款订单信息，body：{}", bodyStr);
            String channelOrderId = bodyStr.getString("channelOrderId");
            Order order = orderMapper.getOrderByOrderNumber(channelOrderId);
            OrderRefund orderRefund = orderRefundMapper.selectOne(new LambdaQueryWrapper<OrderRefund>().eq(OrderRefund::getRefundSn, bodyStr.getString("afterSaleOrder")));
            ShopDetail shopDetailByShopId = shopDetailService.getShopDetailByShopId(orderRefund.getShopId());

            thirdPartyRefundRequest.setChannelOrderId(channelOrderId);
            thirdPartyRefundRequest.setOutStationNo(shopDetailByShopId.getHbStationNo());
            thirdPartyRefundRequest.setAfterSaleOrder(orderRefund.getRefundSn());
            thirdPartyRefundRequest.setSaleType(1);//售前售后标 1:售前 2:售后
            if (order.getHbOrderStatus().equals(OrderStatus.SUCCESS.value())) {
                thirdPartyRefundRequest.setSaleType(2);
            }
            thirdPartyRefundRequest.setReason(orderRefund.getBuyerReason());
            thirdPartyRefundRequest.setProblemDescription(orderRefund.getBuyerDesc());

            thirdPartyRefundRequest.setRefundStatus(orderRefund.getReturnMoneySts());
            Integer applyType = orderRefund.getApplyType();
            if (Objects.equals(applyType, 1)) {
                thirdPartyRefundRequest.setApplyDeal(10);
            } else if (Objects.equals(applyType, 2)) {
                thirdPartyRefundRequest.setApplyDeal(40);
            } else {
                thirdPartyRefundRequest.setApplyDeal(50);
            }

            thirdPartyRefundRequest.setPickAddress(orderRefund.getBuyerMobile());
            thirdPartyRefundRequest.setRefundType(orderRefund.getRefundType());
            thirdPartyRefundRequest.setMoney((long) (orderRefund.getRefundAmount() == null ? 0 : orderRefund.getRefundAmount() * 100));
            thirdPartyRefundRequest.setTimestamp(orderRefund.getApplyTime().getTime());
            thirdPartyRefundRequest.setRefundSource(1);

            List<ProductRequest> productRequests = new ArrayList<>();
            orderRefundSkuMapper.selectList(new LambdaQueryWrapper<OrderRefundSku>().eq(OrderRefundSku::getOrderRefundId, orderRefund.getRefundId())).forEach(orderRefundSku -> {
                Sku sku = skuService.getById(orderRefundSku.getSkuId());
                ProductRequest productRequest = new ProductRequest();
                productRequest.setSkuName(sku.getSkuName());
                productRequest.setSkuId(orderRefundSku.getSkuId());
                productRequest.setChannelSkuId(sku.getHbSkuId());
                productRequest.setRefundCount(orderRefundSku.getProductCount());
                productRequest.setRefundMoney((long) (orderRefundSku.getSkuPrice() == null ? 0 : orderRefundSku.getProductCount() * orderRefundSku.getSkuPrice() * 100));
                productRequest.setTransId(sku.getSkuId().toString());
                productRequests.add(productRequest);

            });
            thirdPartyRefundRequest.setProducts(productRequests);

            List<OrderPaymentRequest> orderPaymentRequests = new ArrayList<>();
            OrderPaymentRequest orderPaymentRequest = new OrderPaymentRequest();
            orderPaymentRequest.setPaymentType(1002);
            orderPaymentRequest.setPaymentAmount((long) (orderRefund.getRefundAmount() == null ? 0 : orderRefund.getRefundAmount() * 100));
            orderPaymentRequest.setPaymentNum(1);
            orderPaymentRequests.add(orderPaymentRequest);
            thirdPartyRefundRequest.setOrderPayments(orderPaymentRequests);
            log.info("退款订单信息，参数：{}", thirdPartyRefundRequest);
            // 返回退款单信息
            log.info("退款订单状态：{}", orderRefund.getReturnMoneySts());
            //TODO 退款单完成处理积分
            if (orderRefund.getReturnMoneySts().equals(70)) {
                //推送商家审核状态后 同步退款单状态
                changeStatus(orderRefund.getRefundSn(), orderRefund.getReturnMoneySts());
                orderService.returnRefund(orderRefund.getOrderNumber());
            }
        } catch (Exception e) {
            log.error("海博退款订单查询异常：{}", e);
            HBR.error("未知异常");
        }

        log.info("退款订单信息，返回：{}", thirdPartyRefundRequest);
        return HBR.success(thirdPartyRefundRequest);
    }

    @Override
    public HBR audit(JSONObject hBRequest) {
        try {
            JSONObject bodyStr = hBRequest.getJSONObject("body");
            log.info("售后审核接口-回调接口，body：{}", bodyStr);
            String afterSaleOrder = bodyStr.getString("afterSaleOrder");
            String channelOrderId = bodyStr.getString("channelOrderId");
            Integer auditType = bodyStr.getInteger("auditType");
            Integer applyDeal = bodyStr.getInteger("applyDeal");

            if (ObjectUtil.isNotEmpty(applyDeal)) {
                if (applyDeal == 40) {
                    //40:退货退款
                    applyDeal = 2;
                } else {
                    applyDeal = 1;
                }
            }
            OrderRefund orderRefund = orderRefundMapper.selectOne(new LambdaQueryWrapper<OrderRefund>().eq(OrderRefund::getRefundSn, afterSaleOrder));
            if (auditType == 3) {
                //3：驳回
                String reason = bodyStr.getString("reason");
                orderRefund.setReturnMoneySts(ReturnMoneyStsType.REJECT.value());
                orderRefund.setRejectMessage(reason);
                orderRefundMapper.updateById(orderRefund);

                Order orderByOrderNumber = orderService.getOrderByOrderNumber(channelOrderId);
                orderByOrderNumber.setRefundStatus(4);
                orderService.updateById(orderByOrderNumber);

                //生成退款驳回记录
                addOrderRefundRecord(orderRefund.getRefundId(), 20, 3, reason);
            } else {
                //审核通过
                orderRefund.setApplyType(applyDeal);
                if (applyDeal == 1) {
                    orderRefund.setReturnMoneySts(ReturnMoneyStsType.SUCCESS.value());
                } else {
                    //退货退款需要处理二审
                    orderRefund.setReturnMoneySts(ReturnMoneyStsType.CONSIGNMENT.value());
                }
                orderRefundMapper.updateById(orderRefund);

                //生成待商家审核记录
                if (applyDeal == 1) {
                    addOrderRefundRecord(orderRefund.getRefundId(), 5, 3, "你的申请已通过，退款处理中");
                } else {
                    addOrderRefundRecord(orderRefund.getRefundId(), 6, 3, "申请已通过，请及时填写配送信息");
                }
            }

            if (applyDeal == 1) {
                //订单退款金额或者积分处理
                orderService.returnRefund(orderRefund.getOrderNumber());
            }

            //推送商家审核状态后 同步退款单状态
            changeStatus(orderRefund.getRefundSn(), orderRefund.getReturnMoneySts());
        } catch (Exception e) {
            log.error("海博退款订单查询异常：{}", e);
            HBR.error("未知异常");
        }

        return HBR.success();
    }

    @Override
    public HBR confirmOrder(JSONObject hBRequest) {
        try {
            JSONObject bodyStr = hBRequest.getJSONObject("body");
            log.info("售后确认接口-回调接口，body：{}", bodyStr);
            String afterSaleOrder = bodyStr.getString("afterSaleOrder");
            String channelOrderId = bodyStr.getString("channelOrderId");
            Integer auditType = bodyStr.getInteger("auditType");

            OrderRefund orderRefund = orderRefundMapper.selectOne(new LambdaQueryWrapper<OrderRefund>().eq(OrderRefund::getRefundSn, afterSaleOrder));
            if (auditType == 3) {
                //3：驳回
                Order orderByOrderNumber = orderService.getOrderByOrderNumber(channelOrderId);
                orderByOrderNumber.setRefundStatus(4);
                orderService.updateById(orderByOrderNumber);

                orderRefund.setReturnMoneySts(ReturnMoneyStsType.REJECT.value());
                orderRefund.setRejectMessage(bodyStr.getString("reason"));
            } else {
                orderRefund.setIsReceiver(true);
                orderRefund.setReceiveTime(new Date());
                orderRefund.setReturnMoneySts(ReturnMoneyStsType.SUCCESS.value());
            }
            orderRefundMapper.updateById(orderRefund);


            //订单退款金额或者积分处理
            orderService.returnRefund(orderRefund.getOrderNumber());

            //推送商家审核状态后 同步退款单状态
            changeStatus(orderRefund.getRefundSn(), orderRefund.getReturnMoneySts());
          } catch (Exception e) {
            log.error("海博退款订单查询异常：{}", e);
            HBR.error("未知异常");
        }

        return HBR.success();
    }

    @Override
    public 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);
    }

    @Override
    public HBR partRefund(JSONObject hBRequest) {
        try {
            JSONObject bodyStr = hBRequest.getJSONObject("body");
            log.info("部分退款接口-回调接口，body：{}", bodyStr);
            String channelOrderId = bodyStr.getString("channelOrderId");
            Integer applyDeal = bodyStr.getInteger("applyDeal");

            OrderRefundParam orderRefundParam = new OrderRefundParam();
            Order order = orderMapper.getOrderAndOrderItemByOrderNumber(channelOrderId);
            orderRefundParam.setOrderNumber(channelOrderId);
            orderRefundParam.setRefundType(RefundType.SINGLE.value());
            orderRefundParam.setApplyType(1);
            orderRefundParam.setRefundType(2);
            orderRefundParam.setIsReceiver(false);
            orderRefundParam.setBuyerReason("17");
            orderRefundParam.setBuyerDesc(bodyStr.getString("reason"));
            orderRefundParam.setBuyerMobile(order.getUserMobile());
            orderRefundParam.setRefundAmount(order.getActualTotal());

            OrderRefund orderRefund = new OrderRefund();
            if (ObjectUtil.isNotEmpty(applyDeal)) {
                if (applyDeal == 10) {
                    orderRefund.setApplyType(1);
                } else {
                    orderRefund.setApplyType(5);
                }
            }
            JSONArray products = bodyStr.getJSONArray("products");
            log.info("部分退款接口-回调接口，products：{}", products);

            List<OrderRefundSku> orderRefundSkuList = new ArrayList<>();
            int goodsNum = 0;
            for (Object product : products) {
                JSONObject productJson = JSON.parseObject(product.toString());
                long channelSkuId = Long.parseLong(productJson.getString("channelSkuId"));
                OrderRefundSku orderRefundSku = new OrderRefundSku();
//                String skuId = productJson.getString("skuId");
                skuService.getOne(new LambdaQueryWrapper<Sku>().eq(Sku::getHbSkuId, channelSkuId));
                OrderItem orderItem = orderItemService.getOne(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getSkuId, channelSkuId)
                        .eq(OrderItem::getOrderNumber, channelOrderId));

                orderRefundSku.setSkuId(orderItem.getSkuId());
                orderRefundSku.setOrderItemId(orderItem.getOrderItemId());
                orderRefundSku.setSkuPrice(orderItem.getPrice());
                int count = Integer.parseInt(productJson.getString("productCount"));
                goodsNum += count;
                orderRefundSku.setProductCount(count);
                orderRefundSkuList.add(orderRefundSku);
            }
            orderRefund.setGoodsNum(goodsNum);
            orderRefundParam.setOrderRefundSkuList(orderRefundSkuList);

            OrderRefund orderRefund1 = orderService.applyAgain(orderRefundParam, ReturnMoneyStsType.SUCCESS.value());
            //推送海博创建订单
            createRefundOrder(order.getOrderNumber(), orderRefund1.getRefundSn());
        } catch (Exception e) {
            log.error("海博退款订单查询异常：{}", e);
            HBR.error("未知异常");
        }

        return HBR.success();
    }

    @Override
    public HBR createResult(JSONObject hBRequest) {
//        try {
//            JSONObject bodyStr = hBRequest.getJSONObject("body");
//            log.info("创建退款结果接口-回调接口，body：{}", bodyStr);
//            String afterSaleO
//            OrderRefund orderRefund = orderRefundMapper.selectOne(new LambdaQueryWrapper<OrderRefund>().eq(OrderRefund::getRefundSn, afterSaleOrder));
//            orderRefund.setReturnMoneySts(ReturnMoneyStsType.SUCCESS.value());
//            orderRefundMapper.updateById(orderRefund);
//            Order orderByOrderNumber = orderService.getById(orderRefund.getOrderId());
//            orderByOrderNumber.setRefundStatus(2);
//            orderService.updateById(orderByOrderNumber);
//        } catch (Exception e) {
//            log.error("海博退款订单查询异常：{}", e);
//            HBR.error("未知异常");
//        }

        return HBR.success();
    }

    @Override
    public OrderRefundCountParam orderRefundCount(OrderRefundStaisticsParam orderRefund) {
        return orderRefundMapper.orderRefundCount(orderRefund);
    }

    @Override
    public IPage<OrderRefundVo> orderRefundPage(PageParam<OrderRefund> page, OrderRefundStaisticsParam orderRefund) {
        return orderRefundMapper.orderRefundPage(page, orderRefund);
    }

    @Override
    public OrderRefundVo selectInfoById(Long refundId) {
        return orderRefundMapper.selectInfoById(refundId);
    }
    /**
     * 导出售后订单
     * @param orderRefund
     * @param userId
     */
    @Override
    public R<String> export(OrderRefundStaisticsParam orderRefund,Long userId) {

        List<OrderRefundVo> orderRefundList= orderRefundMapper.findOrderRefund(orderRefund);
        for (OrderRefundVo record : orderRefundList) {
            record.setOrderRefundSkuList(orderRefundskuMapper.selectByRefundId(record.getRefundId()));
        }
        if (orderRefundList.isEmpty()){
            throw new GlobalException("该次导出未查询到数据,不允许导出");
        }
        String taskId = UUID.randomUUID().toString();
        ExportTask exportTask = new ExportTask();
        exportTask.setUserId(userId);
        exportTask.setExportStatus(0);//导出状态进行中
        exportTask.setTaskId(taskId);
        exportTask.setExportType(2);//导出类型
        exportTask.setTaskName("售后订单导出");
        exportTask.setExportMsg("导出中");
        exportTask.setCreateTime(new Date());
        exportTask.setUpdateTime(new Date());
        exportTaskService.save(exportTask);
        // 异步执行导出
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            Thread currentThread = Thread.currentThread();
            ExportContext context = new ExportContext(null, currentThread, false, 0);
            exportTaskService.putTaskId(taskId,context);
            try {
                // 记录任务开始
                log.info("开始执行导出任务，用户ID: {}", userId);
                exportNormalOrders(orderRefundList,exportTask,"refundOrder",context);
                // 记录任务完成
                log.info("导出任务完成，用户ID: {}", userId);
            } catch (Exception e) {
                log.error("导出任务异常，用户ID: {}", userId, e);
                exportTask.setExportStatus(2);
                exportTask.setExportMsg("导出失败,"+e.getMessage());
                exportTaskService.updateById(exportTask);
            }finally {
                exportTaskService.removeTaskId(taskId);
            }
        }, exportExecutor);
        // 存储任务上下文
        exportTaskService.putTaskId(taskId, new ExportContext(future, null, false, 0));
        return R.SUCCESS("成功");
    }

    /**
     * 导出正常订单数据到Excel（直接输出到HttpServletResponse）
     */
    public void exportNormalOrders(List<OrderRefundVo> orderList,
                                   ExportTask exportTask,
                                   String fileName, ExportContext context) {
        // 2. 生成安全的文件名
        String safeFileName = ExportUtils.generateSafeFileName(fileName);
        // 3. 准备文件路径
        try {
            ExportUtils.prepareExportFile(safeFileName, exportTask);
        } catch (ExportException e) {
            exportTask.setExportStatus(2);//处理失败
            exportTask.setExportMsg(e.getMessage());
            exportTaskService.updateById(exportTask);
            return;
        }
        File file = new File(exportTask.getFileUrl());
        try (Workbook workbook = new SXSSFWorkbook(100)) {
            // 创建Sheet
            Sheet sheet = workbook.createSheet("售后订单");

            // 设置列宽
            setupColumnWidth(sheet);

            // 创建表头样式
            CellStyle headerStyle = ExportUtils.createHeaderStyle(workbook);

            // 创建数据样式
            CellStyle dataStyle = ExportUtils.createDataStyle(workbook);
            CellStyle numberStyle = ExportUtils.createNumberStyle(workbook);
            CellStyle dateStyle = ExportUtils.createDateStyle(workbook);


            String[] headers = {
                    "序号","订单编号", "退款编号", "申请时间", "申请方式", "售后状态",
                    "订单类型", "退款商品名称", "规格", "购买单价(元)","退款数量", "小计(元)",
                    "退款商品总数量", "退款总金额(元)", "退还现金(元)", "退还积分(元)","退还积分中过期积分(分)",
                    "所属企业", "买家姓名", "买家电话"
            };
            // 创建合并单元格的表头
            ExportUtils.createMergedHeader(sheet, headerStyle,"售后订单",19);

            // 创建列标题行
            ExportUtils.createColumnHeaders(sheet, headerStyle,headers);

            // 填充数据
            fillOrderData(sheet, orderList, dataStyle, numberStyle, dateStyle,context);
            // 写入文件
            try (FileOutputStream fos = new FileOutputStream(file);
                 BufferedOutputStream bos = new BufferedOutputStream(fos)) {
                workbook.write(bos);
            }
            // 检查是否被中断
            if (context.isCancelled() || Thread.currentThread().isInterrupted()) {
                log.info("导出任务 {} 被中断，已处理 {} 行", exportTask.getTaskId(), context.getProcessedRows());
                exportTask.setExportStatus(1); // 3-已取消
                exportTask.setExportMsg("导出被用户取消，已处理" + context.getProcessedRows() + "行");
                exportTaskService.updateById(exportTask);
                return;
            }
            log.info("订单导出成功，文件：{}，记录数：{}", fileName, orderList.size());
            exportTask.setExportStatus(1);
            exportTask.setExportMsg("导出成功");
            exportTask.setUpdateTime(new Date());
            exportTaskService.updateById(exportTask);
        } catch (InterruptedException e) {
            log.error("导出任务 {} 被中断", exportTask.getTaskId());
            Thread.currentThread().interrupt(); // 重新设置中断状态
            exportTask.setExportStatus(4);
            exportTask.setExportMsg("导出被用户取消");
            exportTaskService.updateById(exportTask);
        } catch (Exception e) {
            log.error("订单导出失败", e);
            exportTask.setExportStatus(2);
            exportTask.setExportMsg("导出失败：" + e.getMessage());
            exportTaskService.updateById(exportTask);
        }
    }

    /**
     * 设置列宽
     */
    private void setupColumnWidth(Sheet sheet) {
        // 根据模板设置列宽（单位：1/256字符宽度）
        sheet.setColumnWidth(0, 12 * 256);   // 序号
        sheet.setColumnWidth(1, 12 * 256);   // 订单编号
        sheet.setColumnWidth(2, 18 * 256);   // 退款编号
        sheet.setColumnWidth(3, 18 * 256);   // 申请时间
        sheet.setColumnWidth(4, 10 * 256);   // 申请方式
        sheet.setColumnWidth(5, 8 * 256);    // 售后状态
        sheet.setColumnWidth(6, 25 * 256);   // 订单类型
        sheet.setColumnWidth(7, 20 * 256);   // 退款商品名称
        sheet.setColumnWidth(8, 10 * 256);   // 规格
        sheet.setColumnWidth(9, 8 * 256);    // 购买单价(元)
        sheet.setColumnWidth(10, 10 * 256);   // 退款数量
        sheet.setColumnWidth(11, 12 * 256);  // 小计(元)
        sheet.setColumnWidth(12, 12 * 256);  // 退款商品总数量
        sheet.setColumnWidth(13, 8 * 256);   // 退款总金额(元)
        sheet.setColumnWidth(14, 12 * 256);  // 退还现金(元)
        sheet.setColumnWidth(15, 10 * 256);  // 退还积分(元)
        sheet.setColumnWidth(16, 15 * 256);  // 退还积分中过期积分(分)
        sheet.setColumnWidth(17, 15 * 256);  // 所属企业
        sheet.setColumnWidth(18, 10 * 256);  // 买家姓名
        sheet.setColumnWidth(19, 15 * 256);  // 买家电话
    }

    /**
     * 填充订单数据
     */
    private void fillOrderData(Sheet sheet, List<OrderRefundVo> orderList,
                               CellStyle dataStyle, CellStyle numberStyle, CellStyle dateStyle,ExportContext context) throws InterruptedException{
        int batchSize = 100; // 每批处理1000条
        int totalRows = orderList.size();
        int rowNum = 2; // 从第3行开始（0-based索引）
        int indexNum= 1; //序号

        for (int i = 0; i < totalRows; i += batchSize) {
            int end = Math.min(i + batchSize, totalRows);
            List<OrderRefundVo> batch = orderList.subList(i, end);

            for (OrderRefundVo orderRefundVo : orderList) {
                // 定期检查中断标志
                if (context.isCancelled() || Thread.currentThread().isInterrupted()) {
                    context.setProcessedRows(indexNum);
                    break;
                }
                Row row = sheet.createRow(rowNum++);
                row.setHeightInPoints(18);
                // 序号
                ExportUtils.createCell(sheet,row, 0,orderRefundVo.getOrderRefundSkuList().size(),rowNum, indexNum, dataStyle);
                fillOrderRowData(sheet,rowNum,row, orderRefundVo, dataStyle, numberStyle, dateStyle);
                rowNum+=orderRefundVo.getOrderRefundSkuList().size()-1;
                indexNum++;
            }

            // 定期刷新到磁盘
            if (rowNum % 100 == 0) {
                try {
                    ((SXSSFSheet) sheet).flushRows(100);
                } catch (IOException e) {
                    log.warn("刷新行数据失败", e);
                }
            }
        }

    }

    /**
     * 填充单行订单数据
     */
    private void fillOrderRowData(Sheet sheet,int rowNum,Row row, OrderRefundVo orderRefundVo,
                                  CellStyle dataStyle, CellStyle numberStyle, CellStyle dateStyle) {

        // 订单编号
        ExportUtils.createCell(sheet,row, 1,orderRefundVo.getOrderRefundSkuList().size(),rowNum, orderRefundVo.getOrderNumber(), dataStyle);

        // 退款编号
        ExportUtils.createCell(sheet,row, 2,orderRefundVo.getOrderRefundSkuList().size(),rowNum,  orderRefundVo.getRefundSn(), dateStyle);

        // 申请时间
        ExportUtils.createCell(sheet,row, 3,orderRefundVo.getOrderRefundSkuList().size(),rowNum,  ExportUtils.formatDate(orderRefundVo.getApplyTime()), dateStyle);

        // 申请方式
        ExportUtils.createCell(sheet,row, 4,orderRefundVo.getOrderRefundSkuList().size(),rowNum,getApplyType(orderRefundVo.getApplyType()), dataStyle);

        // 售后状态
        ExportUtils.createCell(sheet,row, 5,orderRefundVo.getOrderRefundSkuList().size(),rowNum, getReturnMoneySts(orderRefundVo.getReturnMoneySts()), dataStyle);
        // 订单类型
        ExportUtils.createCell(sheet,row, 6,orderRefundVo.getOrderRefundSkuList().size(),rowNum, getDvyType(orderRefundVo.getDvyType()), dataStyle);
        // 商品明细行（每个订单项一行）
        fillOrderItems(sheet, rowNum, row, orderRefundVo, dataStyle, numberStyle);

        // 退款商品总数量
        ExportUtils.createCell(sheet,row, 12,orderRefundVo.getOrderRefundSkuList().size(),rowNum, orderRefundVo.getGoodsNum(), numberStyle);

        // 退款总金额(元)
        ExportUtils.createCell(sheet,row, 13,orderRefundVo.getOrderRefundSkuList().size(),rowNum, orderRefundVo.getRefundTotalMoney(), numberStyle);

        // 退还现金(元)
        ExportUtils.createCell(sheet,row, 14,orderRefundVo.getOrderRefundSkuList().size(),rowNum, orderRefundVo.getRefundAmount(), numberStyle);

        // 退还积分(元)
        ExportUtils.createCell(sheet,row,15,orderRefundVo.getOrderRefundSkuList().size(),rowNum,"-"+(orderRefundVo.getOffsetPoints()==null?0:Arith.div(Double.valueOf(orderRefundVo.getOffsetPoints()), 100)), numberStyle);

        // 退还积分中过期积分(分)
        ExportUtils.createCell(sheet,row, 16,orderRefundVo.getOrderRefundSkuList().size(),rowNum, (orderRefundVo.getRefundExpiredScore()==null?0:orderRefundVo.getRefundExpiredScore()), numberStyle);

        // 所属企业
        ExportUtils.createCell(sheet,row, 17,orderRefundVo.getOrderRefundSkuList().size(),rowNum, orderRefundVo.getChannelName(), dataStyle);

        // 买家姓名
        ExportUtils.createCell(sheet,row, 18,orderRefundVo.getOrderRefundSkuList().size(),rowNum, orderRefundVo.getReceiver(), dataStyle);

        // 买家电话
        ExportUtils.createCell(sheet,row, 19,orderRefundVo.getOrderRefundSkuList().size(),rowNum, orderRefundVo.getBuyerMobile(), dataStyle);
    }
    /**
     * 填充订单项明细
     */
    private void fillOrderItems(Sheet sheet, int rowNum, Row row, OrderRefundVo orderRefundVo,
                                CellStyle dataStyle, CellStyle numberStyle) {
        int itemSize = orderRefundVo.getOrderRefundSkuList().size();

        for (int i = 0; i < itemSize; i++) {
            Row currentRow = (i < 1) ? row : sheet.createRow(rowNum + (i-1));
            OrderRefundSkuVo orderRefundSkuVo = orderRefundVo.getOrderRefundSkuList().get(i);
            // 退款商品名称
            ExportUtils.createCell(sheet, currentRow, 7, 0, rowNum, orderRefundSkuVo.getProdName(), dataStyle);

            // 规格
            ExportUtils.createCell(sheet, currentRow, 8, 0, rowNum, orderRefundSkuVo.getSpec(), dataStyle);

            // 购买单价(元)
            ExportUtils.createCell(sheet, currentRow, 9, 0, rowNum, orderRefundSkuVo.getSkuPrice(), numberStyle);

            // 退款数量
            ExportUtils.createCell(sheet, currentRow, 10, 0, rowNum, orderRefundSkuVo.getProductCount(), dataStyle);

            // 小计(元)
            ExportUtils.createCell(sheet, currentRow, 11, 0, rowNum,(Arith.multiply(orderRefundSkuVo.getProductCount(),orderRefundSkuVo.getSkuPrice(),2)), numberStyle);

        }
    }

    /**
     *海博订单状态
     * @param status
     * @return
     */
    private String getReturnMoneySts(Integer status) {
        switch (status) {
            case 10: return "待审核";
            case 20: return "处理中";
            case 30: return "驳回退款";
            case 40: return "撤销退款";
            case 60: return "待退货（一审同意）";
            case 65: return "待确认收货（二审待审核）";
            case 70: return "退款完成";
            default: return "未知状态";
        }
    }
    /**
     * 订单类型
     * @param dvyType
     * @return
     */
    private String getDvyType(Integer dvyType) {
        switch (dvyType) {
            case 1: return "快递";
            case 2: return "自提";
            case 3: return "及时配送";
            default: return "未知类型";
        }
    }
    /**
     * 订单类型
     * @param applyType
     * @return
     */
    private String getApplyType(Integer applyType) {
        switch (applyType) {
            case 1: return "仅退款";
            case 2: return "退货退款";
            case 5: return "差价退款";
            default: return "未知类型";
        }
    }

    @Override
    public Integer queryRemainGoodsNumber(String orderNumber) {
        return orderRefundMapper.queryRemainGoodsNumber(orderNumber);
    }


}
