package org.wfc.payment.pay.alipay.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeRefundModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.ijpay.alipay.AliPayApi;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.wfc.common.core.domain.R;
import org.wfc.payment.pay.alipay.service.IAliPayService;
import org.wfc.user.api.RemoteUUserService;
import org.wfc.user.api.domain.vo.UOrderVo;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.RoundingMode;
import java.util.Map;

/**
 * @description: 支付宝支付ServiceImpl
 * @author: cyc
 * @since: 2025-03-21
 */
@Service
@Slf4j
public class AliPayServiceImpl implements IAliPayService {

    @Resource
    private RemoteUUserService remoteUUserService;

    @Override
    public void pcPay(HttpServletResponse response, Long orderId, String returnUrl, String notifyUrl) {
        try {
            String totalAmount = getAmountByOrder(orderId);
            if (StrUtil.isBlank(totalAmount)) {
                return;
            }
            log.info("pc outTradeNo>" + orderId);

            AlipayTradePagePayModel model = new AlipayTradePagePayModel();

            model.setOutTradeNo(orderId.toString());
            model.setProductCode("FAST_INSTANT_TRADE_PAY");
            model.setTotalAmount(totalAmount);
            model.setSubject("WANFI PAY");
            model.setPassbackParams("passback_params");

            log.info("pc notifyUrl>" + notifyUrl);
            AliPayApi.tradePage(response, model, notifyUrl, returnUrl);
        } catch (Exception e) {
            log.error("alipay pc pay error", e);
        }
    }

    private String getAmountByOrder(Long orderId) {
        R<UOrderVo> orderRes = remoteUUserService.getOrderById(orderId);
        UOrderVo orderVo = orderRes.getData();
        if (orderVo == null) {
            return null;
        }
        return orderVo.getOrderAmount().setScale(2, RoundingMode.HALF_UP).toString();
    }

    @Override
    public void wapPay(HttpServletResponse response, Long orderId, String returnUrl, String notifyUrl) {
        String totalAmount = getAmountByOrder(orderId);
        if (StrUtil.isBlank(totalAmount)) {
            return;
        }

        String body = "WANFI WAP PAY";
        String subject = "WANFI PAY";
        String passBackParams = "1";

        AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
        model.setBody(body);
        model.setSubject(subject);
        model.setTotalAmount(totalAmount);
        model.setPassbackParams(passBackParams);
        System.out.println("wap outTradeNo>" + orderId);
        model.setOutTradeNo(orderId.toString());
        model.setProductCode("QUICK_WAP_PAY");

        log.info("wap notifyUrl>" + notifyUrl);
        try {
            AliPayApi.wapPay(response, model, returnUrl, notifyUrl);
        } catch (Exception e) {
            log.error("alipay wap pay error", e);
        }
    }

    @Override
    public String notifyUrl(HttpServletRequest request, String publicKey) {
        try {
            // 获取支付宝POST过来反馈信息
            Map<String, String> params = AliPayApi.toMap(request);

            boolean verifyResult = AlipaySignature.rsaCheckV1(params, publicKey, "UTF-8", "RSA2");

            if (verifyResult) {
                // 请在这里加上商户的业务逻辑程序代码 异步通知可能出现订单重复通知 需要做去重处理
                String outTradeNo = params.get("out_trade_no");
                remoteUUserService.paySuccess(Long.valueOf(outTradeNo), "inner");
                return "success";
            } else {
                log.error("notify_url 验证失败");
                return "failure";
            }
        } catch (AlipayApiException e) {
            log.error("alipay notifyUrl error", e);
            return "failure";
        }
    }

    @Override
    public String tradeRefund(Long orderId) {
        try {
            String totalAmount = getAmountByOrder(orderId);
            if (StrUtil.isBlank(totalAmount)) {
                return null;
            }

            AlipayTradeRefundModel model = new AlipayTradeRefundModel();
            if (ObjectUtil.isNotNull(orderId)) {
                model.setOutTradeNo(orderId.toString());
            }
            model.setRefundAmount(totalAmount);
            model.setRefundReason("normal refund");
            return AliPayApi.tradeRefundToResponse(model).getBody();
        } catch (AlipayApiException e) {
            log.error("alipay refund error", e);
        }
        return null;
    }
}
