package org.springblade.common.constant;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.utils.SpringContextHolder;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.ldt.agent.entity.AgentRecord;
import org.springblade.ldt.agent.service.IAgentRecordService;

/**
 * @Author: Silent
 * @Description
 * @Date: Created in 14:59 2021/10/12
 * @Modified By:
 */
public interface Agent {
	//角色名称
	String roleName = "agent";

	//租户ID
	String tenantId = "000000";

	IAgentRecordService agentRecordService = SpringContextHolder.getBean(IAgentRecordService.class);

	/**
	 * 判断是否是代理
	 * @return
	 */
	static boolean isAgent() {
		return isAgent(AuthUtil.getUser());
	}

	/**
	 * 判断是否是代理
	 * @param bladeUser
	 * @return
	 */
	static boolean isAgent(BladeUser bladeUser) {
		return StringUtils.equals(bladeUser.getTenantId(), tenantId) && StringUtils.equals(bladeUser.getRoleName(), roleName);
	}

	static Long getAgentUserId() {
		return getAgentUserId(AuthUtil.getUser());
	}

	static Long getAgentUserId(BladeUser bladeUser) {
		return getAgentUserId(bladeUser.getUserId());
	}

	/**
	 * 根据BladeUser的userId去查询代理记录
	 * @param userId
	 * @return
	 */
	static Long getAgentUserId(Long userId) {
		AgentRecord agentRecord = agentRecordService.getOne(Wrappers.<AgentRecord>lambdaQuery()
			.select(AgentRecord::getAccountId) //只查询代理的id
			.eq(AgentRecord::getUserId, userId) //根据用户id去查询代理id
			.last("limit 0,1")); //如果有多个默认取第一个
		if(agentRecord!=null){
			return agentRecord.getAccountId();
		}
		return null;
	}

	static AgentRecord getAgentUserInfo(Long userId) {
		AgentRecord agentRecord = agentRecordService.getOne(Wrappers.<AgentRecord>lambdaQuery()
			.select(AgentRecord::getAccountId) //只查询代理的id
			.eq(AgentRecord::getUserId, userId) //根据用户id去查询代理id
			.last("limit 0,1")); //如果有多个默认取第一个
		if(agentRecord!=null){
			return agentRecord;
		}
		return null;
	}
}
