//package com.greenorange.promotion.service.wechat.impl;
//
//import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
//import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
//import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
//import com.greenorange.promotion.common.ErrorCode;
//import com.greenorange.promotion.constant.OrderStatusConstant;
//import com.greenorange.promotion.constant.SystemConstant;
//import com.greenorange.promotion.exception.ThrowUtils;
//import com.greenorange.promotion.model.entity.*;
//import com.greenorange.promotion.model.enums.CommissionStatusEnum;
//import com.greenorange.promotion.service.common.CommonService;
//import com.greenorange.promotion.service.course.CourseOrderService;
//import com.greenorange.promotion.service.course.CoursePromotionCommissionPendingService;
//import com.greenorange.promotion.service.course.CourseService;
//import com.greenorange.promotion.service.refund.RefundRecordService;
//import com.greenorange.promotion.service.userInfo.UserInfoService;
//import com.greenorange.promotion.service.userInfo.UserPerformanceSummaryService;
//import com.greenorange.promotion.service.wechat.WechatPayService;
//import com.greenorange.promotion.utils.RefundUtils;
//import com.wechat.pay.java.core.notification.NotificationParser;
//import com.wechat.pay.java.core.notification.RequestParam;
//import com.wechat.pay.java.service.payments.jsapi.model.Amount;
//import com.wechat.pay.java.service.payments.jsapi.model.Payer;
//import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
//import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
//import com.wechat.pay.java.service.payments.model.Transaction;
//import com.wechat.pay.java.service.refund.model.AmountReq;
//import com.wechat.pay.java.service.refund.model.CreateRequest;
//import com.wechat.pay.java.service.refund.model.Refund;
//import com.wechat.pay.java.service.refund.model.RefundNotification;
//import jakarta.annotation.Resource;
//import jakarta.servlet.http.HttpServletRequest;
//import lombok.SneakyThrows;
//import org.springframework.stereotype.Service;
//
//import java.io.BufferedReader;
//import java.io.IOException;
//import java.math.BigDecimal;
//import java.util.List;
//import java.util.Map;
//import java.util.function.Function;
//
///**
// * @author 陈新知
// */
//@Service
//public class WechatPayServiceImpl implements WechatPayService {
//
//
//    @Resource
//    private WxPayConfig wxPayConfig;
//
//
//    @Resource
//    private CourseOrderService courseOrderService;
//
//
//    @Resource
//    private CourseService courseService;
//
//
//    @Resource
//    private CommonService commonService;
//
//
//    @Resource
//    private RefundRecordService refundRecordService;
//
//
//    @Resource
//    private UserInfoService userInfoService;
//
//
//    @Resource
//    private UserPerformanceSummaryService userPerformanceSummaryService;
//
//
//    @Resource
//    private CoursePromotionCommissionPendingService coursePromotionCommissionPendingService;
//
//
//    /**
//     * 请求参数
//     */
//    public static RequestParam requestParam = null;
//
//
//    /**
//     * 微信支付
//     */
//    @Override
//    public PrepayWithRequestPaymentResponse createPayment(String orderId, String miniOpenId, BigDecimal amount) {
//        // request.setXxx(val)设置所需参数，具体参数可见Request定义
//        PrepayRequest request = new PrepayRequest();
//        // 金额
//        Amount WxAmount = new Amount();
//        WxAmount.setTotal(amount.movePointRight(2).intValue());
//        WxAmount.setCurrency("CNY");
//        request.setAmount(WxAmount);
//        // 公众号id
//        request.setAppid(wxPayConfig.getAppId());
//        // 商户号
//        request.setMchid(wxPayConfig.getMerchantId());
//        // 支付者信息
//        Payer payer = new Payer();
//        payer.setOpenid(miniOpenId);
//        request.setPayer(payer);
//        // 获取订单号
//        CourseOrder courseOrder = courseOrderService.getById(orderId);
//        String orderNumber = courseOrder.getOrderNumber();
//        // 描述
//        request.setDescription("订单号：" + orderNumber);
//        // 微信回调地址
//        request.setNotifyUrl(wxPayConfig.getNotifyUrl() + "/wxPay/payment/callback");
//        // 商户订单号
//        request.setOutTradeNo(orderNumber);
//        //返回数据，前端调起支付
//        return wxPayConfig.getJsapiServiceExtension().prepayWithRequestPayment(request);
//    }
//
//
//    /**
//     * 支付回调
//     */
//    @Override
//    public boolean paymentCallback(Transaction transaction) throws IOException {
//        System.out.println("---------------------------微信支付回调（开始）-------------------------------");
//        // 获取订单信息
//        String orderNumber = transaction.getOutTradeNo();
//        LambdaQueryWrapper<CourseOrder> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(CourseOrder::getOrderNumber, orderNumber);
//        CourseOrder courseOrder = courseOrderService.getOne(queryWrapper);
//
//        // 修改订单状态
//        LambdaUpdateWrapper<CourseOrder> updateWrapper = new LambdaUpdateWrapper<>();
//        updateWrapper.eq(CourseOrder::getId, courseOrder.getId())
//                .set(CourseOrder::getOrderStatus, OrderStatusConstant.SUCCESS);
//        courseOrderService.update(updateWrapper);
//
//        // 修改当前课程下单人数
//        Long courseId = courseOrder.getCourseId();
//        Course course = courseService.getById(courseId);
//        if (course != null) {
//            course.setOrderCount(course.getOrderCount() + 1);
//            courseService.updateById(course);
//        }
//
//        // 更新主管和员工的绩效记录
//        Long userId = courseOrder.getUserId();
//        List<Long> pathToRoot = userInfoService.findPathToRoot(userId);
//        List<Long> superUserIdList = pathToRoot.subList(1, 3);
//        List<UserPerformanceSummary> userPerformanceSummaryList = commonService.findByFieldInTargetField(superUserIdList, userPerformanceSummaryService, Function.identity(), UserPerformanceSummary::getUserId);
//        BigDecimal rate;
//        Map<String, BigDecimal> rateMap = userPerformanceSummaryService.queryRakeRewardsRate();
//        for (int i = 0; i < userPerformanceSummaryList.size(); i ++ ) {
//            if (i == 0) rate = rateMap.get("first");
//            else rate = rateMap.get("second");
//            // 计算理论上获得的最大提成奖励
//            BigDecimal rakeRewards = courseOrder.getTotalAmount().multiply(rate);
//            UserPerformanceSummary userPerformanceSummary = userPerformanceSummaryList.get(i);
//
//            userPerformanceSummary.setTotalAmount(userPerformanceSummary.getTotalAmount().add(courseOrder.getTotalAmount()));
//            userPerformanceSummary.setNetAmount(userPerformanceSummary.getNetAmount().add(courseOrder.getTotalAmount().multiply(SystemConstant.FEE_RATE)));
//            userPerformanceSummary.setOrderCount(userPerformanceSummary.getOrderCount() + 1);
//            userPerformanceSummary.setToRelease(userPerformanceSummary.getToRelease().add(rakeRewards.multiply(SystemConstant.REFUND_RATE)));
//            userPerformanceSummary.setToSettle(userPerformanceSummary.getToSettle().add(rakeRewards.multiply(SystemConstant.FEE_RATE)));
//        }
//        userPerformanceSummaryService.updateBatchById(userPerformanceSummaryList);
//
//
//        // 添加课程推广待提成记录
//        Long firstUserId = pathToRoot.get(0);
//        Long secondUserId = pathToRoot.get(1);
//        CoursePromotionCommissionPending coursePromotionCommissionPending = CoursePromotionCommissionPending.builder()
//                .firstUserId(firstUserId)
//                .secondUserId(secondUserId)
//                .courseId(courseId)
//                .name(courseOrder.getName())
//                .type(courseOrder.getType())
//                .image(courseOrder.getImage())
//                .orderId(courseOrder.getId())
//                .userId(userId)
//                .firstRate(rateMap.get("first"))
//                .secondRate(rateMap.get("second"))
//                .firstReward(courseOrder.getTotalAmount().multiply(rateMap.get("first")))
//                .secondReward(courseOrder.getTotalAmount().multiply(rateMap.get("second")))
//                .totalAmount(courseOrder.getTotalAmount())
//                .commissionStatus(CommissionStatusEnum.PENDING.getValue())
//                .orderCreateTime(courseOrder.getCreateTime())
//                .build();
//        coursePromotionCommissionPendingService.save(coursePromotionCommissionPending);
//
//
//        System.out.println("---------------------------微信支付回调（结束）-------------------------------");
//        return true;
//    }
//
//
//    /**
//     * 部分退款申请
//     */
//    @Override
//    public Refund refundPartPayment(String orderId, BigDecimal refundAmount) {
//        // 获取订单
//        CourseOrder courseOrder = courseOrderService.getById(orderId);
//        ThrowUtils.throwIf(courseOrder == null, ErrorCode.OPERATION_ERROR, "订单不存在");
//        // 判断该订单是否已经退款
//        ThrowUtils.throwIf(courseOrder.getOrderStatus().equals(OrderStatusConstant.REFUNDED), ErrorCode.OPERATION_ERROR, "订单已退款");
//
//        String orderNumber = courseOrder.getOrderNumber();
//        // 退款请求
//        CreateRequest createRequest = new CreateRequest();
//        // 商户订单号
//        createRequest.setOutTradeNo(orderNumber);
//        // 商户退款单号
//        String outRefundNo = RefundUtils.generateRefundNo();
//        createRequest.setOutRefundNo(outRefundNo);
//        // 退款结果回调
//        createRequest.setNotifyUrl(wxPayConfig.getNotifyUrl() + "/wxPay/refund/part/callback");
//        // 退款金额
//        AmountReq amountReq = new AmountReq();
//
//        amountReq.setRefund(refundAmount.movePointRight(2).longValue());
//        amountReq.setTotal(courseOrder.getTotalAmount().movePointRight(2).longValue());
//        amountReq.setCurrency("CNY");
//        createRequest.setAmount(amountReq);
//
////        // 生成退款记录
////        Course course = courseService.getById(courseOrder.getCourseId());
////        RefundRecord refundRecord = commonService.copyProperties(course, RefundRecord.class);
////        refundRecord.setId(null);
////        refundRecord.setOutTradeNo(orderNumber);
////        refundRecord.setOutRefundNo(outRefundNo);
////        refundRecord.setTotalAmount(courseOrder.getTotalAmount().movePointRight(2));
////        refundRecord.setRefundAmount(refundAmount.movePointRight(2));
////        refundRecord.setUserId(courseOrder.getUserId());
////        refundRecord.setCreateTime(null);
////        refundRecord.setUpdateTime(null);
////        refundRecordService.save(refundRecord);
//
//        // 申请退款
//        System.out.println("退款请求：" + createRequest);
//        Refund refund = wxPayConfig.getRefundService().create(createRequest);
//        System.out.println("退款申请结果：" + refund);
//
//        return refund;
//    }
//
//
//    /**
//     * 部分退款回调
//     */
//    @Override
//    public boolean refundPartCallback(RefundNotification refundNotification) {
//        System.out.println("---------------------------微信退款回调（开始）-------------------------------");
//        // 获取订单信息
//        String orderNumber = refundNotification.getOutTradeNo();
//        LambdaQueryWrapper<CourseOrder> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.eq(CourseOrder::getOrderNumber, orderNumber);
//        CourseOrder courseOrder = courseOrderService.getOne(queryWrapper);
//
//        // 修改订单状态
//        LambdaUpdateWrapper<CourseOrder> updateWrapper = new LambdaUpdateWrapper<>();
//        updateWrapper.eq(CourseOrder::getId, courseOrder.getId())
//                .set(CourseOrder::getOrderStatus, OrderStatusConstant.REFUNDED);
//        courseOrderService.update(updateWrapper);
//
//        // 修改课程下单人数
//        Long courseId = courseOrder.getCourseId();
//        Course course = courseService.getById(courseId);
//        if (course != null) {
//            course.setOrderCount(course.getOrderCount() - 1);
//            courseService.updateById(course);
//        }
//
//        // 更新主管和员工的绩效记录
//        Long userId = courseOrder.getUserId();
//        List<Long> pathToRoot = userInfoService.findPathToRoot(userId);
//        List<Long> superUserIdList = pathToRoot.subList(1, 3);
//        List<UserPerformanceSummary> userPerformanceSummaryList = commonService.findByFieldInTargetField(superUserIdList, userPerformanceSummaryService, Function.identity(), UserPerformanceSummary::getUserId);
//        BigDecimal rate;
//        LambdaQueryWrapper<CoursePromotionCommissionPending> coursePromotionQueryWrapper = new LambdaQueryWrapper<>();
//        coursePromotionQueryWrapper.eq(CoursePromotionCommissionPending::getOrderId, courseOrder.getId());
//        CoursePromotionCommissionPending coursePromotionCommissionPending = coursePromotionCommissionPendingService.getOne(coursePromotionQueryWrapper);
//        for (int i = 0; i < userPerformanceSummaryList.size(); i ++ ) {
//            if (i == 0) rate = coursePromotionCommissionPending.getFirstRate();
//            else rate = coursePromotionCommissionPending.getSecondRate();
//            // 计算理论上获得的最大提成奖励
//            BigDecimal rakeRewards = courseOrder.getTotalAmount().multiply(rate);
//            UserPerformanceSummary userPerformanceSummary = userPerformanceSummaryList.get(i);
//
//            userPerformanceSummary.setTotalAmount(userPerformanceSummary.getTotalAmount().subtract(courseOrder.getTotalAmount()));
//            userPerformanceSummary.setNetAmount(userPerformanceSummary.getNetAmount().subtract(courseOrder.getTotalAmount().multiply(SystemConstant.FEE_RATE)));
//            userPerformanceSummary.setToRelease(userPerformanceSummary.getToRelease().subtract(rakeRewards.multiply(SystemConstant.REFUND_RATE)));
//            userPerformanceSummary.setRefunded(userPerformanceSummary.getRefunded().add(courseOrder.getTotalAmount().multiply(SystemConstant.REFUND_RATE)));
//        }
//        userPerformanceSummaryService.updateBatchById(userPerformanceSummaryList);
//
//        // 修改课程推广待提成状态为"已失效"
//        LambdaUpdateWrapper<CoursePromotionCommissionPending> coursePromotionUpdateWrapper = new LambdaUpdateWrapper<>();
//        coursePromotionUpdateWrapper.eq(CoursePromotionCommissionPending::getOrderId, courseOrder.getId())
//                        .set(CoursePromotionCommissionPending::getCommissionStatus, CommissionStatusEnum.EXPIRED.getValue());
//        coursePromotionCommissionPendingService.update(coursePromotionUpdateWrapper);
//
//        System.out.println("---------------------------微信退款回调（结束）-------------------------------");
//        return true;
//    }
//
//
//    /**
//     * 获取支付回调信息
//     */
//    @Override
//    public Transaction getTransactionInfo(HttpServletRequest request) {
//        NotificationParser notificationParser = getNotificationParser(request);
//        return notificationParser.parse(requestParam, Transaction.class);
//    }
//
//
//    /**
//     * 获取退款回调信息
//     */
//    @Override
//    public RefundNotification getRefundInfo(HttpServletRequest request) {
//        NotificationParser notificationParser = getNotificationParser(request);
//        return notificationParser.parse(requestParam, RefundNotification.class);
//    }
//
//
//    /**
//     * 根据微信官方发送的请求获取信息
//     */
//    @SneakyThrows
//    public NotificationParser getNotificationParser(HttpServletRequest request) {
//        System.out.println("---------------------------获取信息-------------------------------");
//        // 获取RSA配置
//        NotificationParser notificationParser = new NotificationParser(wxPayConfig.getRSAConfig());
//        // 构建请求
//        StringBuilder bodyBuilder = new StringBuilder();
//        BufferedReader reader = request.getReader();
//        String line;
//        while ((line = reader.readLine()) != null) {
//            bodyBuilder.append(line);
//        }
//        String body = bodyBuilder.toString();
//        String timestamp = request.getHeader("Wechatpay-Timestamp");
//        String nonce = request.getHeader("Wechatpay-Nonce");
//        String signature = request.getHeader("Wechatpay-Signature");
//        String singType = request.getHeader("Wechatpay-Signature-Type");
//        String wechatPayCertificateSerialNumber = request.getHeader("Wechatpay-Serial");
//        requestParam = new RequestParam.Builder()
//                .serialNumber(wechatPayCertificateSerialNumber)
//                .nonce(nonce)
//                .signature(signature)
//                .timestamp(timestamp)
//                .signType(singType)
//                .body(body)
//                .build();
//        System.out.println(requestParam.toString());
//        System.out.println("---------------------------信息获取完毕-------------------------------");
//        return notificationParser;
//    }
//
//
//}
