package com.platform.modules.sys.controller;

import com.platform.common.utils.Constant;
import com.platform.common.utils.RedisUtils;
import com.platform.modules.sys.entity.SysTenantEntity;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.modules.sys.service.SysTenantService;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * Controller公共组件
 */
public abstract class AbstractController {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private SysTenantService tenantService;

    protected Logger logger = LoggerFactory.getLogger(getClass());

    protected SysUserEntity getUser() {

        SysUserEntity sysUserEntity = (SysUserEntity) SecurityUtils.getSubject().getPrincipal();

        if (null == sysUserEntity.getTenantId())
            return sysUserEntity;

        if (redisUtils.hexists(Constant.REDIS_SYS_TENANT_ENTITY, sysUserEntity.getTenantId().toString())) {
            sysUserEntity.setTenantName(redisUtils.hget(Constant.REDIS_SYS_TENANT_ENTITY, sysUserEntity.getTenantId().toString(), SysTenantEntity.class).getTenantName());
        } else {
            SysTenantEntity tenantEntity = tenantService.selectById(sysUserEntity.getTenantId());
            if (tenantEntity != null) {
            	redisUtils.hset(Constant.REDIS_SYS_TENANT_ENTITY, tenantEntity.getId().toString(), tenantEntity);
                sysUserEntity.setTenantName(tenantEntity.getTenantName());
            }
        }

        return sysUserEntity;
    }

    protected Long getUserId() {
        if (getUser() == null) {
            return null;
        }
        return getUser().getUserId();
    }
}
