package org.sky.system.rule.tenant;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.sky.core.literule.annotation.LiteRuleComponent;
import org.sky.core.literule.core.RuleComponent;
import org.sky.core.tenant.TenantId;
import org.sky.core.tool.constant.KdConstant;
import org.sky.core.tool.utils.Func;
import org.sky.system.cache.ParamCache;
import org.sky.system.pojo.entity.Tenant;
import org.sky.system.rule.context.TenantContext;
import org.sky.system.service.ITenantService;

import java.util.List;
import java.util.stream.Collectors;

import static org.sky.common.constant.TenantConstant.ACCOUNT_NUMBER_KEY;
import static org.sky.common.constant.TenantConstant.DEFAULT_ACCOUNT_NUMBER;
import static org.sky.system.rule.constant.TenantRuleConstant.TENANT_RULE;


/**
 * 租户构建
 *
 */
@LiteRuleComponent(id = TENANT_RULE, name = "租户构建")
public class TenantRule extends RuleComponent {
	@Override
	public void process() {
		// 获取上下文
		TenantContext contextBean = this.getContextBean(TenantContext.class);
		Tenant tenant = contextBean.getTenant();
		TenantId tenantIdGenerator = contextBean.getTenantIdGenerator();
		ITenantService tenantService = contextBean.getTenantService();

		// 获取租户ID
		List<Tenant> tenants = tenantService.list(Wrappers.<Tenant>query().lambda().eq(Tenant::getIsDeleted, KdConstant.DB_NOT_DELETED));
		List<String> codes = tenants.stream().map(Tenant::getTenantId).collect(Collectors.toList());
		String tenantId = getTenantId(tenantIdGenerator, codes);
		tenant.setTenantId(tenantId);
		// 获取参数配置的账号额度
		int accountNumber = Func.toInt(ParamCache.getValue(ACCOUNT_NUMBER_KEY), DEFAULT_ACCOUNT_NUMBER);
		tenant.setAccountNumber(accountNumber);

		// 设置上下文
		contextBean.setTenant(tenant);

	}

	private String getTenantId(TenantId tenantIdGenerator, List<String> codes) {
		String code = tenantIdGenerator.generate();
		if (codes.contains(code)) {
			return getTenantId(tenantIdGenerator, codes);
		}
		return code;
	}
}
