package org.dromara.main.controller;

import cn.dev33.satoken.annotation.SaIgnore;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.common.web.core.BaseController;
import org.dromara.main.domain.vo.PaymentVo;
import org.dromara.main.service.IPaymentService;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/portal/payment")
public class PortalPaymentController extends BaseController {

    private final IPaymentService paymentService;

    @PostMapping("/alipay/qrcode")
    public R<PaymentVo> createAlipayQrCode(@RequestBody Map<String, Object> request) {
        Object orderIdValue = request.get("orderId");
        if (orderIdValue == null) {
            return R.fail("订单ID不能为空");
        }
        String tenantId = LoginHelper.getTenantId();
        if (tenantId == null || tenantId.isBlank()) {
            return R.fail("未登录或token已失效");
        }
        Long orderId = Long.valueOf(orderIdValue.toString());
        return R.ok(paymentService.createAlipayQrCode(orderId, tenantId));
    }

    @SaIgnore
    @PostMapping("/alipay/notify")
    public String alipayNotify(HttpServletRequest request) {
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            StringBuilder valueStr = new StringBuilder();
            for (int i = 0; i < values.length; i++) {
                valueStr.append(values[i]);
                if (i != values.length - 1) {
                    valueStr.append(",");
                }
            }
            params.put(name, valueStr.toString());
        }
        return paymentService.handleAlipayNotify(params);
    }

    @GetMapping("/status")
    public R<PaymentVo> queryPaymentStatus(@NotNull(message = "订单ID不能为空") @RequestParam Long orderId) {
        PaymentVo vo = paymentService.queryPaymentStatus(orderId);
        if (vo != null) {
            vo.setPaymentStatusText(toPaymentStatusText(vo.getPaymentStatus()));
        }
        return vo == null ? R.fail("支付记录不存在") : R.ok(vo);
    }

    @SaIgnore
    @GetMapping("/query-by-payment-no")
    public R<Map<String, Object>> queryByPaymentNo(@NotNull(message = "支付单号不能为空") @RequestParam String paymentNo) {
        PaymentVo payment = paymentService.queryByPaymentNo(paymentNo);
        if (payment == null) {
            return R.fail("支付记录不存在");
        }
        Map<String, Object> result = new HashMap<>();
        result.put("orderId", payment.getOrderId());
        result.put("orderNo", payment.getOrderNo());
        result.put("paymentStatus", payment.getPaymentStatus());
        result.put("paymentStatusText", toPaymentStatusText(payment.getPaymentStatus()));
        result.put("paymentAmount", payment.getPaymentAmount());
        return R.ok(result);
    }

    private String toPaymentStatusText(Integer status) {
        if (status == null) {
            return "未知";
        }
        return switch (status) {
            case 0 -> "待支付";
            case 1 -> "支付中";
            case 2 -> "支付成功";
            case 3 -> "支付失败";
            default -> "未知";
        };
    }
}
