package com.example.demo.controller;

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

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.domain.AlipayTradeQueryModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.ijpay.alipay.AliPayApi;

/**
 * 支付宝支付控制器
 * 基于IJPay实现
 */
@RestController
@RequestMapping("/api/payments/alipay")
public class AlipayController {

    private static final Logger logger = LoggerFactory.getLogger(AlipayController.class);

    @Autowired
    private com.example.demo.config.PaymentConfig.AliPayConfig aliPayConfig;


    /**
     * PC网页支付
     */
    @PostMapping("/pc-pay")
    public void pcPay(@RequestParam String outTradeNo,
                      @RequestParam String totalAmount,
                      @RequestParam String subject,
                      @RequestParam String body,
                      HttpServletResponse response) {
        try {
            String returnUrl = aliPayConfig.getDomain() + "/api/payments/alipay/return";
            String notifyUrl = aliPayConfig.getDomain() + "/api/payments/alipay/notify";

            AlipayTradePagePayModel model = new AlipayTradePagePayModel();
            model.setOutTradeNo(outTradeNo);
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            model.setTotalAmount(totalAmount);
            model.setSubject(subject);
            model.setBody(body);

            AliPayApi.tradePage(response, model, notifyUrl, returnUrl);
            logger.info("PC支付页面跳转成功: {}", outTradeNo);
        } catch (Exception e) {
            logger.error("PC支付失败", e);
        }
    }

    /**
     * 手机网页支付
     */
    @PostMapping("/wap-pay")
    public void wapPay(@RequestParam String outTradeNo,
                       @RequestParam String totalAmount,
                       @RequestParam String subject,
                       @RequestParam String body,
                       HttpServletResponse response) {
        try {
            String returnUrl = aliPayConfig.getDomain() + "/api/payments/alipay/return";
            String notifyUrl = aliPayConfig.getDomain() + "/api/payments/alipay/notify";

            AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
            model.setOutTradeNo(outTradeNo);
            model.setProductCode("QUICK_WAP_PAY");
            model.setTotalAmount(totalAmount);
            model.setSubject(subject);
            model.setBody(body);

            AliPayApi.wapPay(response, model, returnUrl, notifyUrl);
            logger.info("手机支付页面跳转成功: {}", outTradeNo);
        } catch (Exception e) {
            logger.error("手机支付失败", e);
        }
    }

    /**
     * APP支付
     */
    @PostMapping("/app-pay")
    public ResponseEntity<Map<String, Object>> appPay(@RequestParam String outTradeNo,
                                                      @RequestParam String totalAmount,
                                                      @RequestParam String subject,
                                                      @RequestParam String body) {
        Map<String, Object> response = new HashMap<>();
        try {
            String notifyUrl = aliPayConfig.getDomain() + "/api/payments/alipay/notify";

            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setOutTradeNo(outTradeNo);
            model.setProductCode("QUICK_MSECURITY_PAY");
            model.setTotalAmount(totalAmount);
            model.setSubject(subject);
            model.setBody(body);
            model.setTimeoutExpress("30m");

            String orderInfo = AliPayApi.appPayToResponse(model, notifyUrl).getBody();
            response.put("success", true);
            response.put("orderInfo", orderInfo);
            logger.info("APP支付订单创建成功: {}", outTradeNo);
        } catch (Exception e) {
            logger.error("APP支付失败", e);
            response.put("success", false);
            response.put("message", "支付失败: " + e.getMessage());
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 扫码支付
     */
    @PostMapping("/qr-pay")
    public ResponseEntity<Map<String, Object>> qrPay(@RequestParam String outTradeNo,
                                                    @RequestParam String totalAmount,
                                                    @RequestParam String subject,
                                                    @RequestParam String body) {
        Map<String, Object> response = new HashMap<>();
        try {
            String notifyUrl = aliPayConfig.getDomain() + "/api/payments/alipay/notify";

            AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
            model.setOutTradeNo(outTradeNo);
            model.setTotalAmount(totalAmount);
            model.setSubject(subject);
            model.setBody(body);
            model.setTimeoutExpress("5m");

            String qrCode = AliPayApi.tradePrecreatePayToResponse(model, notifyUrl).getBody();
            response.put("success", true);
            response.put("qrCode", qrCode);
            logger.info("扫码支付订单创建成功: {}", outTradeNo);
        } catch (Exception e) {
            logger.error("扫码支付失败", e);
            response.put("success", false);
            response.put("message", "支付失败: " + e.getMessage());
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 查询订单
     */
    @GetMapping("/query")
    public ResponseEntity<Map<String, Object>> queryOrder(@RequestParam(required = false) String outTradeNo,
                                                          @RequestParam(required = false) String tradeNo) {
        Map<String, Object> response = new HashMap<>();
        try {
            AlipayTradeQueryModel model = new AlipayTradeQueryModel();
            if (outTradeNo != null) {
                model.setOutTradeNo(outTradeNo);
            }
            if (tradeNo != null) {
                model.setTradeNo(tradeNo);
            }

            String result = AliPayApi.tradeQueryToResponse(model).getBody();
            response.put("success", true);
            response.put("data", result);
            logger.info("订单查询成功: outTradeNo={}, tradeNo={}", outTradeNo, tradeNo);
        } catch (Exception e) {
            logger.error("订单查询失败", e);
            response.put("success", false);
            response.put("message", "查询失败: " + e.getMessage());
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 退款
     */
    @PostMapping("/refund")
    public ResponseEntity<Map<String, Object>> refund(@RequestParam(required = false) String outTradeNo,
                                                     @RequestParam(required = false) String tradeNo,
                                                     @RequestParam String refundAmount,
                                                     @RequestParam String refundReason) {
        Map<String, Object> response = new HashMap<>();
        try {
            AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            if (outTradeNo != null) {
                model.setOutTradeNo(outTradeNo);
            }
            if (tradeNo != null) {
                model.setTradeNo(tradeNo);
            }
            model.setRefundAmount(refundAmount);
            model.setRefundReason(refundReason);

            String result = AliPayApi.tradeRefundToResponse(model).getBody();
            response.put("success", true);
            response.put("data", result);
            logger.info("退款申请成功: outTradeNo={}, tradeNo={}, amount={}", outTradeNo, tradeNo, refundAmount);
        } catch (Exception e) {
            logger.error("退款失败", e);
            response.put("success", false);
            response.put("message", "退款失败: " + e.getMessage());
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 支付同步回调和异步回调已移至 AlipayCallbackController
     * 请使用 /api/payments/alipay/return 和 /api/payments/alipay/notify
     * 
     * @deprecated 此方法已移除，请使用 AlipayCallbackController
     */
}
