package com.kxs.common.pay.service;

import cn.hutool.extra.spring.SpringUtil;
import com.kxs.common.core.exception.GlobalCustomerException;
import com.kxs.common.pay.enums.PayPlatformEnum;
import com.kxs.common.pay.handlers.PayMessageHandler;
import com.kxs.common.pay.model.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.core.Ordered;

import java.util.Comparator;
import java.util.Map;
import java.util.Optional;

/**
 * 支付公共接口服务
 *
 * @author 没秃顶的码农
 * @date 2024-04-24
 */
public interface PayService {

    /**
     * 支付
     */
    PayResponse appPay(PayRequest payReq);

    /**
     * 查询
     */
    QueryResponse query(QueryRequest queryReq);

    /**
     * 退款
     */
    RefundResponse refund(RefundRequest queryReq);


    /**
     * 回调
     */
    String payBack(HttpServletRequest request);

    /**
     * 获取支付回调handler
     */
    default PayMessageHandler getPayMessageHandler(PayPlatformEnum payPlatformEnum){
        Map<String, PayMessageHandler> payMessageHandlerMap = SpringUtil
                .getBeansOfType(PayMessageHandler.class);
        Optional<PayMessageHandler> optional = payMessageHandlerMap.values()
                .stream()
                .filter(service -> service.support(payPlatformEnum))
                .max(Comparator.comparingInt(Ordered::getOrder));

        if (optional.isEmpty()) {
            throw new GlobalCustomerException("DefaultPayMessageHandler error , not register");
        }
        return optional.get();
    }
}
