package com.example.demo.controller;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.example.demo.service.LuluPayService;
import com.example.demo.service.PaymentService;

/**
 * 噜噜支付（彩虹易支付）回调控制器
 */
@RestController
@RequestMapping("/api/payments/lulupay")
public class LuluPayCallbackController {
    
    private static final Logger logger = LoggerFactory.getLogger(LuluPayCallbackController.class);
    
    @Autowired
    private LuluPayService luluPayService;
    
    @Autowired
    private PaymentService paymentService;
    
    @Value("${app.frontend-url:}")
    private String frontendUrl;
    
    /**
     * 异步通知接口
     * 支付平台会通过GET方式调用此接口通知支付结果
     */
    @GetMapping(value = "/notify", produces = MediaType.TEXT_PLAIN_VALUE)
    public String notifyGet(@RequestParam Map<String, String> params) {
        return handleNotify(params);
    }
    
    /**
     * 异步通知接口（POST方式）
     */
    @PostMapping(value = "/notify", produces = MediaType.TEXT_PLAIN_VALUE)
    public String notifyPost(@RequestParam Map<String, String> params) {
        return handleNotify(params);
    }
    
    /**
     * 处理异步通知
     */
    private String handleNotify(Map<String, String> params) {
        logger.info("========== 收到噜噜支付异步通知 ==========");
        logger.info("参数: {}", params);
        
        try {
            boolean success = luluPayService.handleNotify(params);
            
            if (success) {
                String tradeStatus = params.get("trade_status");
                String outTradeNo = params.get("out_trade_no");
                String tradeNo = params.get("trade_no");
                
                logger.info("噜噜支付验签成功: tradeStatus={}, outTradeNo={}, tradeNo={}", tradeStatus, outTradeNo, tradeNo);
                
                // 如果支付成功，调用统一的支付确认方法
                if ("TRADE_SUCCESS".equals(tradeStatus)) {
                    try {
                        // 查找支付记录并确认
                        logger.info("开始查找支付记录: outTradeNo={}", outTradeNo);
                        var paymentOpt = paymentService.findByOrderId(outTradeNo);
                        if (paymentOpt.isPresent()) {
                            var payment = paymentOpt.get();
                            logger.info("找到支付记录: paymentId={}, status={}, orderId={}", 
                                payment.getId(), payment.getStatus(), payment.getOrderId());
                            
                            // 调用确认方法（内部会检查是否已处理，避免重复增加积分）
                            // 即使状态已经是SUCCESS，也要确保会员信息已更新
                            logger.info("开始调用confirmPaymentSuccess: paymentId={}", payment.getId());
                            paymentService.confirmPaymentSuccess(payment.getId(), tradeNo);
                            logger.info("✅ 支付确认处理完成: 订单号={}", outTradeNo);
                        } else {
                            logger.error("❌ 未找到支付记录: outTradeNo={}", outTradeNo);
                        }
                    } catch (Exception e) {
                        logger.error("❌ 支付确认失败: outTradeNo={}, error={}", outTradeNo, e.getMessage(), e);
                    }
                } else {
                    logger.info("交易状态不是TRADE_SUCCESS，不处理积分: tradeStatus={}", tradeStatus);
                }
                
                logger.info("========== 噜噜支付异步通知处理成功 ==========");
                return "success";
            } else {
                logger.warn("========== 噜噜支付异步通知处理失败（验签失败） ==========");
                return "fail";
            }
        } catch (Exception e) {
            logger.error("处理噜噜支付异步通知异常: ", e);
            return "fail";
        }
    }
    
    /**
     * 同步返回接口
     * 用户支付完成后跳转到会员订阅页面
     */
    @GetMapping("/return")
    public ResponseEntity<Void> returnUrl(@RequestParam Map<String, String> params) {
        logger.info("========== 收到噜噜支付同步返回 ==========");
        logger.info("参数: {}", params);
        
        try {
            boolean success = luluPayService.handleReturn(params);
            String tradeStatus = params.get("trade_status");
            String orderId = params.get("out_trade_no");
            
            logger.info("支付同步返回处理结果: success={}, tradeStatus={}, orderId={}", success, tradeStatus, orderId);
            
            // 构建重定向URL，跳转到会员订阅页面
            String redirectUrl = (frontendUrl != null && !frontendUrl.isEmpty() ? frontendUrl : "") 
                + "/subscription?paymentStatus=" + (success && "TRADE_SUCCESS".equals(tradeStatus) ? "success" : "pending")
                + "&orderId=" + (orderId != null ? orderId : "");
            
            logger.info("重定向到: {}", redirectUrl);
            
            return ResponseEntity.status(HttpStatus.FOUND)
                .header("Location", redirectUrl)
                .build();
                
        } catch (Exception e) {
            logger.error("处理噜噜支付同步返回异常: ", e);
            
            // 出错也跳转到订阅页面
            String redirectUrl = (frontendUrl != null && !frontendUrl.isEmpty() ? frontendUrl : "") 
                + "/subscription?paymentStatus=error";
            
            return ResponseEntity.status(HttpStatus.FOUND)
                .header("Location", redirectUrl)
                .build();
        }
    }
}
