package com.jeesharp.business.modules.pay.util;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.pay.exception.ErrorCode;
import com.jeesharp.business.modules.pay.exception.PayException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 支付通用工具：单号生成与统一异常抛出。
 *
 * @author jeesharp
 * @since 2023-08-08
 */
@Component
@Transactional
public class PayCommonUtil {

    private static final ConcurrentMap<Integer, String> MESSAGES = new ConcurrentHashMap<>();

    public static String getOrderNumber(String prefix) {
        return StrUtil.isBlank(prefix) ? "ORD" : prefix + IdWorker.getIdStr();
    }

    public static String getOrderNumber() {
        return IdWorker.getIdStr();
    }

    /**
     * 获取订单 id（28 位）：应用(3) + 终端(1) + 终端类型(1) + 交易类型(1) + 时间(17) + 随机数(5)。
     */
    public static String getOrderNumberByApp(int app, int terminal, int terminalType, int trade) {
        return String.format("%s%s%s%s%s%s", app, terminal, terminalType, trade,
                DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_MS_FORMAT), RandomUtil.randomNumbers(5));
    }

    public static String getFangShiOrder() {
        return getOrderNumberByApp(500, 2, 3, 1);
    }

    public static void wrapPayAndThrow(String message) {
        throw new PayException(message);
    }

    public static PayException wrapPayExceptionAndThrow(ErrorCode errorCode) {
        String messagePattern = MESSAGES.getOrDefault(errorCode.getCode(), errorCode.getMsg());
        throw new PayException(errorCode.getCode(), messagePattern);
    }

    public static PayException wrapPayExceptionAndThrow(Integer code, String message) {
        throw new PayException(code, message);
    }
}
