package com.bonus.canteen.core.account.utils;

import com.bonus.canteen.core.common.utils.RedisUtil;
import com.bonus.common.core.exception.ServiceException;
import com.bonus.common.houqin.constant.GlobalConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AccRedisUtils {
    private static final Logger log = LoggerFactory.getLogger(AccRedisUtils.class);

    public static void lockUpdateAccWalletBalance(Long userId) {
        String lockerKey = generateWalletLockerKey(userId);
        if (!RedisUtil.tryLock(lockerKey, 10, 15)) {
            throw new ServiceException("账户有交易正在进行中");
        }
    }

    public static void unlockUpdateAccWalletBalance(Long userId) {
        String lockerKey = generateWalletLockerKey(userId);
        try {
            RedisUtil.safeUnLock(lockerKey);
        } catch (Exception ex) {
            log.error("账户操作解锁异常", ex);
        }
    }

    public static void lockBatchUpdateAccWallet() {
        String lockerKey = generateBatchUpdateAccWalletKey();
        if (!RedisUtil.setNx(lockerKey, 1, 3600)) {
            throw new ServiceException("已有任务在执行,请稍后~");
        }
    }

    public static void unlockBatchUpdateAccWallet() {
        RedisUtil.delete(generateBatchUpdateAccWalletKey());
    }

    private static String generateWalletLockerKey(Long userId) {
        return String.format("sc:acc_lock_merchant_%s_user_%s_wallet_update",
                GlobalConstants.TENANT_ID, userId);
    }

    private static String generateBatchUpdateAccWalletKey() {
        return String.format("sc:acc_lock_merchant_%s_wallet_batch_update",
                GlobalConstants.TENANT_ID);
    }
}
