package com.bonus.core.pay.common.constants;

import com.bonus.constant.LeConstants;
import com.bonus.core.common.redis.RedisUtil;
import com.bonus.core.common.utils.TenantContextHolder;
import com.bonus.core.order.utils.LeNumUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class PayCacheConstants {
   private static final Logger log = LoggerFactory.getLogger(PayCacheConstants.class);
   private static final int LOCK_SECOND = 60;
   private static final String LOCK_PREFIX = "yst:trade-lock:";

   public static String tradeLockKey(Long tradeId) {
      Long var10000 = TenantContextHolder.getTenantId();
      return "yst:trade-lock:" + var10000 + ":" + tradeId;
   }

   public static boolean lockTrade(Long tradeId) {
      if (!LeNumUtil.isValidId(tradeId)) {
         log.error("[交易锁定] 交易ID不合法 {}", tradeId);
         return false;
      } else {
         String lockKey = tradeLockKey(tradeId);
         if (!RedisUtil.setNx(lockKey, LeConstants.COMMON_YES, 60)) {
            log.info("[交易锁定] 处理中 {} ", tradeId);
            return false;
         } else {
            log.info("[交易锁定] 加锁 {} {}", tradeId, 60);
            return true;
         }
      }
   }

   public static void unlockTrade(Long tradeId) {
      String lockKey = tradeLockKey(tradeId);
      RedisUtil.delete(lockKey);
      log.info("[交易锁定] 解锁 {}", lockKey);
   }
}
