//package com.greenorange.promotion.controller.wechat;
//
//import cn.binarywang.wx.miniapp.api.WxMaService;
//import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
//import com.greenorange.promotion.annotation.RequiresPermission;
//import com.greenorange.promotion.common.BaseResponse;
//import com.greenorange.promotion.common.ErrorCode;
//import com.greenorange.promotion.common.ResultUtils;
//import com.greenorange.promotion.config.WxOpenConfig;
//import com.greenorange.promotion.constant.OrderStatusConstant;
//import com.greenorange.promotion.constant.UserConstant;
//import com.greenorange.promotion.exception.BusinessException;
//import com.greenorange.promotion.exception.ThrowUtils;
//import com.greenorange.promotion.model.dto.CommonRequest;
//import com.greenorange.promotion.model.dto.wxPay.WechatPayRequest;
//import com.greenorange.promotion.model.entity.CourseOrder;
//import com.greenorange.promotion.model.entity.UserInfo;
//import com.greenorange.promotion.service.course.CourseOrderService;
//import com.greenorange.promotion.service.userInfo.UserInfoService;
//import com.greenorange.promotion.service.wechat.WechatPayService;
//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.Refund;
//import com.wechat.pay.java.service.refund.model.RefundNotification;
//import io.swagger.v3.oas.annotations.Hidden;
//import io.swagger.v3.oas.annotations.Operation;
//import io.swagger.v3.oas.annotations.tags.Tag;
//import jakarta.annotation.Resource;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.validation.Valid;
//import lombok.extern.slf4j.Slf4j;
//import me.chanjar.weixin.common.error.WxErrorException;
//import org.apache.commons.lang3.StringUtils;
//import org.springframework.transaction.annotation.Transactional;
//import org.springframework.web.bind.annotation.PostMapping;
//import org.springframework.web.bind.annotation.RequestBody;
//import org.springframework.web.bind.annotation.RequestMapping;
//import org.springframework.web.bind.annotation.RestController;
//
//import java.io.IOException;
//
//@Slf4j
//@RestController
//@Tag(name = "微信支付")
//@RequestMapping("/wxPay")
//@Transactional
//public class WechatPayController {
//
//
//    @Resource
//    private WechatPayService weChatService;
//
//    @Resource
//    private UserInfoService userInfoService;
//
//    @Resource
//    private CourseOrderService courseOrderService;
//
//    @Resource
//    private WxOpenConfig wxOpenConfig;
//
//
//
//
//    /**
//     * JSAPI 下单
//     */
//    @PostMapping("/payment/create")
//    @Operation(summary = "JSAPI 下单", description = "参数：订单id, 权限：所有人, 方法名：createPayment")
//    @RequiresPermission(mustRole = UserConstant.DEFAULT_ROLE)
//    public BaseResponse<PrepayWithRequestPaymentResponse> createPayment(@Valid @RequestBody WechatPayRequest wechatPayRequest, HttpServletRequest request) {
//
//        String code = wechatPayRequest.getCode();
//        WxMaJscode2SessionResult sessionInfo;
//        String miniOpenId;
//        try {
//            WxMaService wxMaService = wxOpenConfig.getWxMaService();
//            sessionInfo = wxMaService.jsCode2SessionInfo(code);
//            miniOpenId = sessionInfo.getOpenid();
//            if (StringUtils.isAnyBlank(miniOpenId)) {
//                throw new BusinessException(ErrorCode.SYSTEM_ERROR);
//            }
//        } catch (WxErrorException e) {
//            log.error("userLoginByWxOpen error", e);
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "登录失败，系统错误");
//        }
//        Long userId = (Long) request.getAttribute("userId");
//        UserInfo userInfo = userInfoService.getById(userId);
//
//        Long orderId = wechatPayRequest.getOrderId();
//        CourseOrder courseOrder = courseOrderService.getById(orderId);
//        ThrowUtils.throwIf(courseOrder == null, ErrorCode.NOT_FOUND_ERROR, "订单不存在");
//        ThrowUtils.throwIf(!courseOrder.getOrderStatus().equals(OrderStatusConstant.PENDING), ErrorCode.OPERATION_ERROR, "订单状态错误");
//        if (!userInfo.getId().equals(courseOrder.getUserId())) {
//            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "你不是该订单用户！");
//        }
//        PrepayWithRequestPaymentResponse response = weChatService.createPayment(String.valueOf(orderId), miniOpenId, courseOrder.getTotalAmount());
//        return ResultUtils.success(response);
//    }
//
//
//
//    /**
//     * JSAPI 下单回调
//     */
//    @Hidden
//    @PostMapping("/payment/callback")
//    @Operation(summary = "JSAPI 下单回调", description = "参数：订单id, 权限：所有人, 方法名：callbackPayment")
//    public synchronized BaseResponse<Boolean> callbackPayment(HttpServletRequest request) throws IOException {
//        // 获取下单信息
//        Transaction transaction = weChatService.getTransactionInfo(request);
//        System.out.println("下单信息:" + transaction);
//        // 支付回调
//        boolean result = weChatService.paymentCallback(transaction);
//        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "微信支付回调失败");
//        return ResultUtils.success(true);
//    }
//
//
//    /**
//     * Web管理员部分退款
//     * @param commonRequest 订单id
//     */
//    @PostMapping("/refund/part/create")
//    @Operation(summary = "Web管理员部分退款", description = "参数：订单id, 权限：web端管理员, 方法名：createPartRefund")
//    @RequiresPermission(mustRole = UserConstant.ADMIN_ROLE)
//    public BaseResponse<Refund> createPartRefund(@Valid @RequestBody CommonRequest commonRequest) {
//        Long orderId = commonRequest.getId();
//        CourseOrder courseOrder = courseOrderService.getById(orderId);
//        ThrowUtils.throwIf(courseOrder == null, ErrorCode.OPERATION_ERROR, "订单不存在");
//
//        Refund refund = weChatService.refundPartPayment(String.valueOf(orderId), courseOrder.getTotalAmount());
//        return ResultUtils.success(refund);
//    }
//
//
//    /**
//     * 部分退款回调
//     */
//    @Hidden
//    @PostMapping("/refund/part/callback")
//    @Operation(summary = "部分退款回调", description = "参数：订单id, 权限：web端管理员, 方法名：callbackRefundPart")
//    public BaseResponse<Boolean> callbackRefundPart(HttpServletRequest request) {
//        // 获取退款信息
//        RefundNotification refundNotification = weChatService.getRefundInfo(request);
//        // 退款回调
//        boolean result = weChatService.refundPartCallback(refundNotification);
//        ThrowUtils.throwIf(!result, ErrorCode.SYSTEM_ERROR, "退款回调失败");
//        return ResultUtils.success(true);
//    }
//
//
//}
