package com.ghy.common.adapay.callback.mapping;

import com.alibaba.fastjson.JSON;
import com.ghy.common.adapay.callback.Event;
import com.ghy.common.adapay.callback.PayCallback;
import com.ghy.common.adapay.model.PayReply;
import org.springframework.util.Assert;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 支付结果匹配
 *
 * @author HH 2022/3/25
 */
public class PayReplyMapping {

    /**
     * 临时保存支付结果
     * key: orderNo
     * value: 处理支付结果的回调接口
     */
    private final static ConcurrentHashMap<String, PayCallback> PAY_RESULT_CALLBACK_MAP = new ConcurrentHashMap<>(1024);

    public static void putReply(Event event) {
        String data = event.getData();
        PayReply payment = JSON.parseObject(data, PayReply.class);
        Assert.hasText(payment.getOrderNo(), "orderNo is blank !!!");
        PayCallback callback = PAY_RESULT_CALLBACK_MAP.remove(payment.getOrderNo());
        if (callback != null) {
            callback.onReply(payment);
        }
    }

    public static void putCallback(String orderNo, PayCallback callback) {
        Assert.hasText(orderNo, "orderNo is blank !!!");
        Assert.notNull(callback, "PayCallback is null !!!");
        PAY_RESULT_CALLBACK_MAP.put(orderNo, callback);
    }
}
