package com.leanwo.activiti.config;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.activiti.engine.impl.cfg.multitenant.TenantInfoHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.leanwo.activiti.util.LoginContext;
import com.leanwo.activiti.util.LoginContextUtil;


/**
 * 必须实现TenantInfoHolder，官方推荐是使用ThreadLocal来切换租户 具体可以按自己需要切换，比如消息中间件
 * 
 * @author YangZhiJie 20200721
 *
 */
public class MyTenantInfoHolder implements TenantInfoHolder {
	
	private static Logger logger = LoggerFactory.getLogger(MyTenantInfoHolder.class);

	private List<String> tenantIds = new ArrayList<String>();
	
	@Override
	public void clearCurrentTenantId() {
		LoginContextUtil.clear();
	}

	@Override
	public Collection<String> getAllTenants() {
		tenantIds.add("dataSource0");
		return tenantIds;
	}

	@Override
	public String getCurrentTenantId() {
		LoginContext loginContext = LoginContextUtil.getLoginContext();
        if (loginContext == null && tenantIds.size() > 0) {
        	return tenantIds.get(0);
        }
        Long account = loginContext.getAccountId();
        if(account == null && tenantIds.size() > 0) {
        	return tenantIds.get(0);
        }
        return "dataSource" + account;
	}

	@Override
	public void setCurrentTenantId(String tenantId) {
		if(tenantId.contains("dataSource")) {
			String accountIdStr = tenantId.replace("dataSource", "");
			Long accountId = Long.parseLong(accountIdStr);
			LoginContextUtil.setUseApplicationAccount(accountId);
		}
	}
	
	public void addTenantId(String tenantId) {
		if(tenantId != null && !tenantIds.contains(tenantId)) {
			tenantIds.add(tenantId);
		}
	}
}
