package com.ruoyi.applet.contoller;

import com.alibaba.fastjson.JSONObject;
import com.cyl.manager.oms.domain.WechatPaymentHistory;
import com.cyl.manager.oms.mapper.WechatPaymentHistoryMapper;
import com.cyl.wechat.WechatPayData;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.refund.model.RefundNotification;
import com.wechat.pay.java.service.refund.model.Status;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * 微信退款回调控制器
 */
@Slf4j
@RestController
@RequestMapping("/no-auth/wechat")
public class WechatRefundNotifyController {

    @Autowired
    private WechatPaymentHistoryMapper wechatPaymentHistoryMapper;

    /**
     * 微信退款回调
     * @param request HTTP请求
     * @return 处理结果
     */
    @PostMapping("/refund")
    public String refundNotify(HttpServletRequest request) {
        log.info("收到微信退款回调");
        
        try {
            // 从请求头中获取信息
            String timestamp = request.getHeader("Wechatpay-Timestamp");
            String nonce = request.getHeader("Wechatpay-Nonce");
            String signature = request.getHeader("Wechatpay-Signature");
            String wechatPayCertificateSerialNumber = request.getHeader("Wechatpay-Serial");
            
            // 获取请求体
            StringBuilder requestBody = new StringBuilder();
            String line;
            BufferedReader reader = request.getReader();
            while ((line = reader.readLine()) != null) {
                requestBody.append(line);
            }
            
            log.info("退款回调请求体: {}", requestBody.toString());
            
            // 构造请求参数
            RequestParam requestParam = new RequestParam.Builder()
                    .serialNumber(wechatPayCertificateSerialNumber)
                    .nonce(nonce)
                    .signature(signature)
                    .timestamp(timestamp)
                    .body(requestBody.toString())
                    .build();
            
            // 验证签名并解析通知
            Config config = com.cyl.wechat.WechatPayConfig.getInstance();
            NotificationParser parser = new NotificationParser((NotificationConfig) config);
            RefundNotification refundNotification = parser.parse(requestParam, RefundNotification.class);
            
            // 处理退款通知
            handleRefundNotification(refundNotification);
            
            return "SUCCESS";
        } catch (Exception e) {
            log.error("处理微信退款回调失败", e);
            return "FAIL";
        }
    }
    
    /**
     * 处理退款通知
     * @param refundNotification 退款通知
     */
    private void handleRefundNotification(RefundNotification refundNotification) {
        try {
            log.info("处理退款通知: {}", JSONObject.toJSONString(refundNotification));
            
            // 更新退款历史记录
            updateRefundHistory(refundNotification);
            
            // 根据退款状态进行相应处理
            if (Status.SUCCESS.equals(refundNotification.getRefundStatus())) {
                log.info("退款成功，退款单号: {}", refundNotification.getOutRefundNo());
                // 可以在这里添加其他业务逻辑，比如发送通知等
            } else if (Status.CLOSED.equals(refundNotification.getRefundStatus())) {
                log.info("退款关闭，退款单号: {}", refundNotification.getOutRefundNo());
            } else if (Status.ABNORMAL.equals(refundNotification.getRefundStatus())) {
                log.warn("退款异常，退款单号: {}", refundNotification.getOutRefundNo());
            }
            
        } catch (Exception e) {
            log.error("处理退款通知失败", e);
        }
    }
    
    /**
     * 更新退款历史记录
     * @param refundNotification 退款通知
     */
    private void updateRefundHistory(RefundNotification refundNotification) {
        try {
            // 根据退款单号查询退款历史记录
            // 这里需要根据实际情况实现查询逻辑
            // WechatPaymentHistory refundHistory = wechatPaymentHistoryMapper.selectByRefundNo(refundNotification.getResult().getOutRefundNo());
            
            // 更新退款状态
            // if (refundHistory != null) {
            //     refundHistory.setPaymentStatus(Constants.PaymentStatus.COMPLETE);
            //     refundHistory.setUpdateTime(LocalDateTime.now());
            //     wechatPaymentHistoryMapper.updateById(refundHistory);
            // }
            
            log.info("退款历史记录已更新，退款单号: {}", refundNotification.getOutRefundNo());
        } catch (Exception e) {
            log.error("更新退款历史记录失败", e);
        }
    }
} 