package com.red.circle.other.app.common.account;


import com.red.circle.component.redis.service.RedisService;
import com.red.circle.other.infra.database.rds.service.family.FamilyBaseInfoService;
import com.red.circle.tool.core.num.account.PrettyAccount;
import com.red.circle.tool.core.num.account.PrettyAccountEnum;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 用户短账号生产.
 *
 * @author pengliang on 2020/10/2 19:18
 */
@Service
@RequiredArgsConstructor
public class FamilyAccountShortProduction {

  /**
   * 起步 account.
   */
  private final RedisService redisService;
  private static final Long INIT_ACCOUNT = 1000L;
  private final FamilyBaseInfoService familyBaseInfoService;
  private static final String FAMILY_ACCOUNT_SHORT = "FAMILY_ACCOUNT_SHORT";
  private static final String FAMILY_ACCOUNT_SHORT_DEV = "FAMILY_ACCOUNT_SHORT_DEV";


  public Long getFamilyAccount() {
    Long account = generateFamilyAccount();
    PrettyAccountEnum prettyAccountEnum = PrettyAccount.getPrettyAccountType(account);
    if (!Objects.equals(prettyAccountEnum, PrettyAccountEnum.NONE)) {
      return getFamilyAccount();
    }
    return account;
  }

  private Long generateFamilyAccount() {
    Long account = incrFamilyAccount();
    if (account < 1000) {
      Long maxAccount = familyBaseInfoService.maxAccount();
      account = incrFamilyAccount(
          Objects.isNull(maxAccount) || maxAccount <= 0 ? INIT_ACCOUNT : maxAccount
      );
    }
    return account;
  }

  private Long incrFamilyAccount() {
    return redisService.increment(FAMILY_ACCOUNT_SHORT);
  }

  private Long incrFamilyAccount(Long account) {
    return redisService.increment(FAMILY_ACCOUNT_SHORT_DEV, account);
  }

}
