package com.repair.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.repair.api.RepairPayRecordControllerAPI;
import com.repair.common.utils.*;
import com.repair.model.enumModel.*;
import com.repair.model.pojo.*;
import com.repair.model.request.RefundReviewRequest;
import com.repair.model.request.RefundableAmountRequest;
import com.repair.model.request.repairPayRequest;
import com.repair.model.result.CommonResult;
import com.repair.model.result.PageUtils;
import com.repair.model.vo.ProsperityRepairPayRecordsVo;
import com.repair.model.vo.QueryExportVo;
import com.repair.model.vo.StatisticsVo;
import com.repair.services.*;
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.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.repair.common.utils.StrUtils.getUUIDBits;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ceshi
 * @since 2023-07-20
 */
@RestController
public class RepairPayRecordController implements RepairPayRecordControllerAPI {

    @Autowired
    private RepairAdminService repairAdminService;
    @Autowired
    private RepairRecordService repairRecordService;
    @Autowired
    private RepairUserService repairUserService;
    @Autowired
    private RepairPayRecordService repairPayRecordService;
    @Autowired
    private RepairTrackRecordService repairTrackRecordService;
    @Autowired
    private RepairRefundRecordService repairRefundRecordService;
    @Autowired
    private RepairSystemMessagesService repairSystemMessagesService;

    /**
     * 新增支付记录
     *
     * @param rc            支付记录数据
     * @param bindingResult 是否为空判断
     * @return
     */
    @Override
    public CommonResult insertRepairPayRecord(RepairPayRecord rc, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        int result = repairPayRecordService.insertRepairPayRecord(rc);

        return result > 0 ? CommonResult.ok("添加成功") : CommonResult.fail("添加失败");
    }

    /**
     * 根据维修单id更新支付记录
     *
     * @param rc            支付记录
     * @param bindingResult 是否为空判断
     * @return
     */
    @Override
    public CommonResult updateRepairPayRecordById(RepairPayRecord rc, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        int result = repairPayRecordService.updateRepairPayRecord(rc);

        return result > 0 ? CommonResult.ok("修改成功") : CommonResult.fail("修改失败");
    }

    /**
     * 根据数据ID删除支付记录
     *
     * @param id 数据ID
     * @return
     */
    @Override
    public CommonResult deleteRepairPayRecordById(int id) {
        RepairPayRecord data = repairPayRecordService.getRepairById(id);
        if (data == null) {
            return CommonResult.fail("当前数据不存在，删除失败！");
        }

        int result = repairPayRecordService.deleteRepairPayRecordById(id);

        return result > 0 ? CommonResult.ok("删除成功") : CommonResult.fail("删除失败");
    }

    /**
     * 假的报修工单支付
     *
     * @param rpr           报修工单支付
     * @param bindingResult 是否为空判断
     * @return
     */
    @Override
    public CommonResult repairPayment(repairPayRequest rpr, BindingResult bindingResult) {
        System.out.println("开始支付" + JSON.toJSON(rpr));
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        RepairRecord data = repairRecordService.getRepairById(rpr.getRecordId());
        if (data == null) {
            return CommonResult.fail("维修单数据异常,支付失败");
        }

        if (data.getMaintenanceState() != eRecordStatu.ToConfirmed.getValue()) {
            return CommonResult.fail("订单状态异常，支付失败");
        }

        if (data.getPrice().compareTo(rpr.getPrice()) != 0) {
            return CommonResult.fail("支付金额与订单金额不一致");
        }

        //查找是否存在支付成功的数据，有的话提示已经支付过了
        RepairPayRecord payData = repairPayRecordService.getRepairPaySuccessByRecordId(rpr.getRecordId());
        if (payData != null) {
            return CommonResult.fail("该订单已支付，请勿重复操作");
        }
        String payResult = null;
        try {
            //支付金额和订单都为0元的时候不唤起支付模块
            payResult = notifyPay(TimeExchange.DateToString(new Date(), "yyyyMMddHHmmss"), data.getRecordNo(), rpr.getPrice().toString(), getUUIDBits(15), "02", "2", "1234567891");
            if (!payResult.equals("success")) {
                return CommonResult.fail("支付失败");
            }
        } catch (Exception e) {
            return CommonResult.fail("支付失败");
        }

        System.out.println("支付结束" + JSON.toJSON(CommonResult.ok("支付成功")));
        return CommonResult.ok("支付成功");
    }

    /**
     * 支付回调接口
     *
     * @param orderDate   交易日期时间 格式为：yyyyMMddHHmmss 24小时制
     * @param orderNo     订单号
     * @param amount      订单金额
     * @param jylsh       支付平台交易流水号
     * @param tranStat    订单支付状态
     * @param return_type 通知类型
     * @param sign        订单签名数据
     * @return
     */
    @Transactional(rollbackFor = {Exception.class})
    public String notifyPay(String orderDate, String orderNo, String amount, String jylsh, String tranStat, String return_type, String sign) throws Exception {

        try {
            // 除去sign参数外，通知接口各参数皆是待签名参数。按照参数列表顺序，以“key=value&key1=value1”方式生成待签名字符串，再拼接密钥。进行MD5运算生成签名。
            // 示例：
            // 密钥：key=umz4aea6g97skeect0jtxigvjkrimd0o
            // 待签名字符串：
            // orderDate=20140319163131&orderNo=1403190004&amount=10.00&jylsh=1303190000001&tranStat=1&return_type=1
            // 报文：
            // orderDate=20140319163131&orderNo=1403190004&amount=10.00&jylsh=1303190000001&tranStat=1&return_type=1umz4aea6g97skeect0jtxigvjkrimd0o
            // 签名：3c797055ef08c16f296d1c28b696f301

            RepairPayRecord data = repairPayRecordService.queryPaymentData(orderNo);

            RepairRecord rr = repairRecordService.queryRepairByRecordno(orderNo);
            if (rr == null) {
                throw new Exception("支付回调失败！");
            }

            if (rr.getPrice().compareTo(new BigDecimal(amount)) != 0) {
                throw new Exception("支付回调失败！");
            }
            //是否支付成功 未支付/等待支付：1；支付成功：2；支付失败：3
            //可能支付平台会重复回调 所以原来支付成功的订单就不用处理了
            if (data != null) {
                if (data.getIsSuccess().equals(2)) {
                    return "success";
                }
                data.setIsSuccess(Integer.valueOf(tranStat));
                data.setRemark(data.getRemark() + " " + tranStat);

                int updateData = repairPayRecordService.updateRepairPayRecord(data);
                if (updateData <= 0) {
                    throw new Exception("支付回调失败！");
                }

            } else {
                data = new RepairPayRecord();
                data.setRecordId(rr.getId());
                data.setUserId(rr.getUserId());
                data.setPayNo(jylsh);
                data.setPayPrice(new BigDecimal(amount));
                data.setIsSuccess(Integer.valueOf(tranStat));
                data.setRemark(return_type);
                int insertData = repairPayRecordService.insertRepairPayRecord(data);

                if (insertData <= 0) {
                    throw new Exception("支付回调失败！");
                }
            }

            if (tranStat.equals("02")) {
                //用户成功支付完成后将维修单状态由待确认改为维修中
                rr.setMaintenanceState(eRecordStatu.Maintenance.getValue());
                int rrData = repairRecordService.updateRepairRecord(rr);
                if (rrData <= 0) {
                    throw new Exception("支付回调失败！");
                }
                //将支付成功消息发送给师傅
                String[] userIds = rr.getMaintenancerId().split(",");
                if (userIds.length > 0) {
                    List<RepairSystemMessages> rsms = new ArrayList<>();
                    for (int i = 0; i < userIds.length; i++) {
                        RepairSystemMessages rsm = new RepairSystemMessages();
                        rsm.setIsRead(0);
                        rsm.setRecordId(data.getId());
                        rsm.setRecipientId(Integer.valueOf(userIds[i]));
                        rsm.setContent("用户已支付，请尽快处理！");
                        rsms.add(rsm);
                    }
                    boolean insertRsm = repairSystemMessagesService.inserBatchSystemMessage(rsms);
                    if (!insertRsm) {
                        throw new Exception("支付回调失败！");
                    }
                }
                //添加跟踪记录
                RepairTrackRecord rtr = new RepairTrackRecord();
                rtr.setRecordId(rr.getId());
                rtr.setMaintenanceState(eRecordStatu.Maintenance.getValue());
                rtr.setContent("订单支付");
                rtr.setUserId(rr.getUserId());
                rtr.setUserZzstr("用户");
                int insertRtr = repairTrackRecordService.insertRepairTrackRecord(rtr);
                if (insertRtr <= 0) {
                    throw new Exception("支付回调失败！");
                }
            }

        } catch (Exception e) {
            throw new Exception("支付回调失败！");
        }

        return "success";
    }

    /**
     * 支付成功分页
     *
     * @param userhead    用户请求头
     * @param currentPage 当前页数
     * @param pageCount   一页数据条数
     * @param keyWord     关键字
     * @param startTime   开始时间
     * @param endTime     结束时间
     * @return
     */
    @Override
    public CommonResult queryProsperityRepairPayRecords(String userhead, int currentPage, int pageCount, String keyWord, String startTime, String endTime) {
        if (currentPage <= 0 && pageCount <= 0) {
            currentPage = 1;
            pageCount = 10;
        }

        //查看是否是超级管理员
        //超级管理员能审核
        boolean isSuper = false;
        String userID = AesUtils.decrypt(userhead);
        RepairAdmin operateData = repairAdminService.getRepairById(userID);
        if (operateData == null) {
            return CommonResult.fail("操作人信息不合法，无法获取工单数据！");
        }
        if (operateData.getIsSuper().equals(eIsSuper.Super.getValue())) {
            isSuper = true;
        }

        //重写
        PageUtils<ProsperityRepairPayRecordsVo> result = repairPayRecordService.queryPayPage(currentPage, pageCount, keyWord, startTime, endTime);
        //需要把退款加入到进度中
        List<RepairRefundRecord> refunds = repairRefundRecordService.getRepairsByStatu();

        for (ProsperityRepairPayRecordsVo data : result.getList()) {
            List<RepairRefundRecord> ownerRefunds = refunds.stream().filter(e -> e.getRecordId().equals(data.getRecordId())).collect(Collectors.toList());
            Integer state = ePayPageStatu.HavePaid.getValue();
            //退款总金额
            BigDecimal sum = BigDecimal.ZERO;
            //已到账的退款金额
            BigDecimal reachSum = BigDecimal.ZERO;
            //审核状态的退款申请数量
            int apply = 0;
            //审核记录
            List<RepairRefundRecord> approves = new ArrayList<>();
            //说明有退款
            if (ownerRefunds != null && ownerRefunds.size() > 0) {
                for (RepairRefundRecord owner : ownerRefunds) {
                    if (owner.getIsSuccess().intValue() == 1) {
                        //已到账的退款金额
                        reachSum = reachSum.add(owner.getRefundPrice());
                    }
                    if (owner.getApprove().intValue() == 0) {
                        apply = apply + 1;
                        approves.add(owner);
                    }
                    if(owner.getApprove().intValue() != 2){
                        sum = sum.add(owner.getRefundPrice());
                    }

                }
                //退款进度
                ownerRefunds.sort(Comparator.comparing(RepairRefundRecord::getCreateTime));
                data.setRepairRefundRecordList(ownerRefunds);


                long NoRefuse = ownerRefunds.stream().filter(e -> e.getApprove().intValue() != 2).count();
                if(NoRefuse > 0){
                    //是否存在还在退款中的
                    if (reachSum.compareTo(data.getPayPrice()) == 0) {
                        state = ePayPageStatu.Refunded.getValue();//已退款
                    } else {
                        //查看是否有存在审核中的
                        if (apply > 0) {
                            state = ePayPageStatu.Apply.getValue();//退款中
                        } else {
                            if (reachSum.compareTo(BigDecimal.ZERO) == 0) {
                                state = ePayPageStatu.Refund.getValue();//退款中
                            } else {
                                state = ePayPageStatu.Rebates.getValue();//部分退款
                            }
                        }
                    }
                }
            }
            //退款总金额
            data.setRefundTotalPrice(sum);
            //实收金额
            BigDecimal officialPrice = data.getPayPrice().subtract(data.getRefundTotalPrice());
            data.setOfficialPrice(officialPrice);
            //状态
            //已支付：0
            //部分退款：1
            //已退款：2
            //退款申请中：3
            //退款中：4
            data.setState(state);

            /**
             * 是否显示审批按钮
             * 不显示：0
             * 显示：1
             */
            if (apply > 0 && isSuper) {
                data.setIsApprove(1);
                data.setApproveRefunds(approves);
            }

        }

        return CommonResult.ok(result);
    }

    /**
     * 实退申请
     *
     * @param rar           实退数据
     * @param userhead      userhead请求头
     * @param bindingResult 是否为空判断
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult refundableAmount(RefundableAmountRequest rar, String userhead, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }
        //实退权限
        String userID = AesUtils.decrypt(userhead);
        RepairAdmin operateData = repairAdminService.getRepairById(userID);
        if (operateData == null) {
            return CommonResult.fail("操作人权限不足，无法使用申请功能！");
        }

        RepairPayRecord repairPayRecord = repairPayRecordService.getById(rar.getRepairPayRecordId());
        if(repairPayRecord == null){
            return CommonResult.fail("支付订单已失效，申请失败！");
        }

        RepairRecord rr = repairRecordService.getRepairById(repairPayRecord.getRecordId());
        if(rr == null){
            return CommonResult.fail("维修工单已失效，申请失败！");
        }

        //实退金额不能大于剩余金额
        LambdaQueryWrapper<RepairRefundRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RepairRefundRecord::getRecordId, repairPayRecord.getRecordId());
        wrapper.ne(RepairRefundRecord::getApprove, 2);
        List<RepairRefundRecord> refundRecordList = repairRefundRecordService.list(wrapper);
        BigDecimal refundTotal = BigDecimal.ZERO;
        for (RepairRefundRecord repairRefundRecord : refundRecordList) {
            //如果还存在审核中的退款数据就不允许提交
            if (repairRefundRecord.getApprove().intValue() == 0) {
                return CommonResult.fail("当前支付订单存在待审核退款申请，无法再次申请！");
            }
            refundTotal = refundTotal.add(repairRefundRecord.getRefundPrice());
        }
        //实收金额减总退款金额在减实退金额，不能小于0
        int i = repairPayRecord.getPayPrice().subtract(refundTotal).subtract(rar.getRefundPrice()).compareTo(new BigDecimal(0));
        if (i < 0) {
            return CommonResult.fail("实退金额有误");
        }


        try {
            RepairRefundRecord repairRefundRecord = new RepairRefundRecord();

            repairRefundRecord.setRecordId(repairPayRecord.getRecordId());
            repairRefundRecord.setUserId(repairPayRecord.getUserId());
            repairRefundRecord.setRefundPrice(rar.getRefundPrice());
            repairRefundRecord.setApprove(0);//2023-10-27 待审批
            repairRefundRecord.setIsSuccess(0);//2023-10-27 退款中
            repairRefundRecord.setApproveUser(operateData.getUsername());
            repairRefundRecord.setRemark(rar.getRemark());

            boolean save = repairRefundRecordService.save(repairRefundRecord);

            if (!save) {
                throw new Exception("实退申请失败！");
            }

            //操作人
            Integer senderId = 0;//超级管理员用ID为0
            if (!operateData.getIsSuper().equals(eIsSuper.Super.getValue())) {
                RepairUser user = repairUserService.getRepairByCardNumber(operateData.getCardNumber());
                if (user == null) {
                    throw new Exception("管理端账号未与移动端账号绑定，无法进行申请！");
                }
                senderId = user.getId();
            }
            //添加跟踪记录
            RepairTrackRecord rtr = new RepairTrackRecord();
            rtr.setRecordId(repairPayRecord.getRecordId());
            rtr.setMaintenanceState(rr.getMaintenanceState());
            rtr.setContent("申请退款-" + rar.getRemark() + "退款" + rar.getRefundPrice() + "元");
            rtr.setUserId(senderId);
            rtr.setUserZzstr("管理员");
            int insertRtr = repairTrackRecordService.insertRepairTrackRecord(rtr);
            if (insertRtr <= 0) {
                throw new Exception("实退申请失败！");
            }

        } catch (Exception e) {
            System.out.println("实退申请失败错误信息：" + e.getMessage());
            throw new Exception("实退申请失败！");
        }

        return CommonResult.ok("实退申请成功");
    }

    /**
     * 退款审核
     *
     * @param rar           实退数据
     * @param bindingResult 是否为空判断
     * @return
     */
    @Override
    @Transactional(rollbackFor = {Exception.class})
    public CommonResult refundReview(RefundReviewRequest rar, String userhead, BindingResult bindingResult) throws Exception {
        if (bindingResult.hasErrors()) {
            String st = paramUtils.getParamError(bindingResult);
            return CommonResult.fail(st);
        }

        //实退权限
        String userID = AesUtils.decrypt(userhead);
        RepairAdmin operateData = repairAdminService.getRepairById(userID);
        if (operateData == null) {
            return CommonResult.fail("操作人权限不足，无法使用审核功能！");
        }

        RepairRefundRecord data = repairRefundRecordService.getRepairById(rar.getId());
        if (data == null) {
            return CommonResult.fail("退款申请已失效，审核失败");
        }

        RepairRecord rr = repairRecordService.getRepairById(data.getRecordId());
        if(rr == null){
            return CommonResult.fail("维修工单已失效，审核失败！");
        }

        if (data.getApprove().intValue() != 0) {
            return CommonResult.fail("请勿重复审核操作");
        }

        try{
            //rar.getState() 拒绝：0；通过：1
            data.setApprove(rar.getState().intValue() == 0 ? 2 : 1);//待审批：0；通过：1；驳回：2
            data.setIsSuccess(rar.getState().intValue() == 0 ? 2 : 0);//退款失败：2；退款成功：1;退款中：0

            int num = repairRefundRecordService.updateRepairRefundRecord(data);

            if (num <= 0) {
                throw new Exception("审核失败！");
            }

            //操作人
            Integer senderId = 0;//超级管理员用ID为0
            if (!operateData.getIsSuper().equals(eIsSuper.Super.getValue())) {
                RepairUser user = repairUserService.getRepairByCardNumber(operateData.getCardNumber());
                if (user == null) {
                    throw new Exception("管理端账号未与移动端账号绑定，无法进行申请！");
                }
                senderId = user.getId();
            }
            //添加跟踪记录
            RepairTrackRecord rtr = new RepairTrackRecord();
            rtr.setRecordId(data.getRecordId());
            rtr.setMaintenanceState(rr.getMaintenanceState());
            rtr.setContent("退款审核-" + (rar.getState().intValue() == 0 ? "拒绝通过该退款申请" : "退款申请通过审核"));
            rtr.setUserId(senderId);
            rtr.setUserZzstr("超级管理员");
            int insertRtr = repairTrackRecordService.insertRepairTrackRecord(rtr);
            if (insertRtr <= 0) {
                throw new Exception("实退申请失败！");
            }

        }catch (Exception e){
            System.out.println("审核失败错误信息：" + e.getMessage());
            throw new Exception("审核失败！");
        }

        return CommonResult.ok("审核成功");
    }

    /**
     * 统计
     *
     * @return
     */
    @Override
    public CommonResult statistics() {
        LambdaQueryWrapper<RepairPayRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RepairPayRecord::getIsSuccess, eIsSuccess.Succeed.getValue());

        List<RepairPayRecord> payRecordList = repairPayRecordService.list(wrapper);
        //总金额
        BigDecimal totalPrice = new BigDecimal(0);
        for (RepairPayRecord repairPayRecord : payRecordList) {
            BigDecimal payPrice = repairPayRecord.getPayPrice();
            totalPrice = totalPrice.add(payPrice);
        }

        LambdaQueryWrapper<RepairRefundRecord> refundWrapper=new LambdaQueryWrapper<>();
        refundWrapper.eq(RepairRefundRecord::getIsSuccess, eRefundStatu.Refundsuccess.getValue());
        List<RepairRefundRecord> list = repairRefundRecordService.list(refundWrapper);
        BigDecimal refundTotalPrice = new BigDecimal(0);
        for (RepairRefundRecord repairRefundRecord : list) {
            BigDecimal refundPrice = repairRefundRecord.getRefundPrice();
            refundTotalPrice = refundTotalPrice.add(refundPrice);
        }
        StatisticsVo statisticsVo = new StatisticsVo();
        statisticsVo.setCount(payRecordList.size());
        statisticsVo.setTotalPrice(totalPrice);
        statisticsVo.setRefundTotalPrice(refundTotalPrice);
        statisticsVo.setOfficialPrice(totalPrice.subtract(refundTotalPrice));

        return CommonResult.ok(statisticsVo);
    }

    /**
     * 限制实退金额
     *
     * @param payRecordId 维修记录ID
     * @return
     * @throws Exception
     */
    @Override
    public CommonResult restrict(int payRecordId) {

        RepairPayRecord payRecord = repairPayRecordService.getById(payRecordId);

        if (ObjectUtils.isEmpty(payRecord)) {
            return CommonResult.fail("参数异常");
        }

        LambdaQueryWrapper<RepairRefundRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RepairRefundRecord::getRecordId, payRecord.getRecordId());
        wrapper.ne(RepairRefundRecord::getApprove, 2);

        List<RepairRefundRecord> refundRecordList = repairRefundRecordService.list(wrapper);
        //退款总金额
        BigDecimal refundTotalPrice = BigDecimal.ZERO;
        for (RepairRefundRecord repairRefundRecord : refundRecordList) {
            BigDecimal refundPrice = repairRefundRecord.getRefundPrice();
            refundTotalPrice = refundTotalPrice.add(refundPrice);
        }

        //实付金额
        if (payRecord.getPayPrice().compareTo(refundTotalPrice) >= 0) {
            BigDecimal subtract = payRecord.getPayPrice().subtract(refundTotalPrice);
            return CommonResult.ok(subtract);
        }

        return CommonResult.fail();
    }

    /**
     * 支付导出
     *
     * @param response  文件响应流
     * @param keyWord   关键字
     * @param startTime 开始时间
     * @param endTime   结束时间
     */
    @Override
    public void queryExport(HttpServletResponse response, String keyWord, String startTime, String endTime) {

        if (startTime != null && endTime != null) {
            try {
                startTime = TimeExchange.getStartOfDayStr(TimeExchange.StringToDate(startTime, "yyyy-MM-dd"));
                endTime = TimeExchange.getEndOfDayStr(TimeExchange.StringToDate(endTime, "yyyy-MM-dd"));
            } catch (Exception e) {
            }
        }

        List<QueryExportVo> queryExportVoList = repairPayRecordService.queryExport(keyWord, startTime, endTime);

        List<QueryExportVo> vos = new ArrayList<>();


        //        导出
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("支付成功记录表");
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("序号");
        headerRow.createCell(1).setCellValue("交易时间");
        headerRow.createCell(2).setCellValue("工单号");
        headerRow.createCell(3).setCellValue("交易流水号");
        headerRow.createCell(4).setCellValue("报修人");
        headerRow.createCell(5).setCellValue("交易金额");
        headerRow.createCell(6).setCellValue("退款金额");
        headerRow.createCell(7).setCellValue("实收金额");
        headerRow.createCell(8).setCellValue("状态");


        if (ObjectUtils.isNotEmpty(queryExportVoList) && queryExportVoList.size() > 0) {

            for (QueryExportVo queryExportVo : queryExportVoList) {
                QueryExportVo vo = new QueryExportVo();
                BeanUtils.copyProperties(queryExportVo, vo);
                //退款金额
                BigDecimal refundTotalPrice = queryExportVo.getRefundTotalPrice();
                if (ObjectUtils.isEmpty(refundTotalPrice)) {
                    refundTotalPrice = new BigDecimal(0);
                    vo.setRefundTotalPrice(refundTotalPrice);
                }
                BigDecimal payPrice = queryExportVo.getPayPrice();
                //退款金额=0
                if (refundTotalPrice.compareTo(new BigDecimal(0)) == 0) {
                    vo.setStatus("已支付");
                } else if (payPrice.compareTo(refundTotalPrice) == 0) {
                    vo.setStatus("已退款");
                } else if (payPrice.compareTo(refundTotalPrice) == 1 && refundTotalPrice.compareTo(new BigDecimal(0)) == 1) {
                    vo.setStatus("部分退款");
                }
                BigDecimal subtract = payPrice.subtract(refundTotalPrice);
                vo.setOfficialPrice(subtract);

                vos.add(vo);
            }
            for (int i = 0; i < vos.size(); i++) {
                QueryExportVo vo = vos.get(i);
                Row dataRow1 = sheet.createRow(i + 1);
                dataRow1.createCell(0).setCellValue(vo.getId());
                dataRow1.createCell(1).setCellValue(vo.getPayTime());
                dataRow1.createCell(2).setCellValue(vo.getRecordNo());
                dataRow1.createCell(3).setCellValue(vo.getPayNo());
                dataRow1.createCell(4).setCellValue(vo.getUserName());
                dataRow1.createCell(5).setCellValue(vo.getPayPrice().toString());
                dataRow1.createCell(6).setCellValue(vo.getRefundTotalPrice().toString());
                dataRow1.createCell(7).setCellValue(vo.getOfficialPrice().toString());
                dataRow1.createCell(8).setCellValue(vo.getStatus());
            }

        }

        // 将工作簿写入文件
        ExcelUtils.excelDownload(workbook, "支付成功表.xlsx", response);

    }
}

