package cn.ezhizao.framework.security.service;

import cn.ezhizao.common.enums.TenantStatus;
import cn.ezhizao.common.enums.UserStatus;
import cn.ezhizao.common.enums.UserTypes;
import cn.ezhizao.common.exception.ServiceException;
import cn.ezhizao.common.utils.StringUtils;
import cn.ezhizao.framework.security.LoginUser;
import cn.ezhizao.project.system.domain.SysUser;
import cn.ezhizao.project.system.mapper.SysUserMapper;
import cn.ezhizao.project.system.service.ISysUserService;
import cn.ezhizao.project.tenant.domain.BizTenant;
import cn.ezhizao.project.tenant.service.IBizTenantService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * 用户验证处理
 *
 * @author ruoyi
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Resource
    private ISysUserService userService;

    @Resource
    private SysUserMapper sysUserMapper;

    @Resource
    private SysPasswordService passwordService;

    @Resource
    private SysPermissionService permissionService;

    @Resource
    private IBizTenantService tenantService;

    @Resource
    HttpServletRequest request;

    @Override
    public UserDetails loadUserByUsername(String userName) {
        final String tenantId = request.getHeader("tenantId");
        final String zero = "0";
        SysUser user;
        /* 租户登录 */
        if (StringUtils.isNotEmpty(tenantId) && !zero.equals(tenantId) ) {
            BizTenant bizTenant = new BizTenant();
            bizTenant.setId(Long.parseLong(tenantId));
            List<BizTenant> bizTenants = tenantService.getList(bizTenant);
            if (bizTenants.size() == 1) {
                bizTenant = bizTenants.get(0);
            }
            Integer status = bizTenant.getStatus();
            if (TenantStatus.STOP.getCode().equals(status)) {
                throw new ServiceException("该租户已经停用,暂时无法提供相关应用服务");
            }
            user = userService.selectUserByUserNameAndTenantId(userName, tenantId);
            // 如果是企业管理员账号登录
            if(UserTypes.TENANT_ADMIN.getCode().equals(user.getUserType())){
                passwordService.validate(user);
            }

            return createLoginUserForTenant(user);
        } else {
            /* 系统用户登录 */
            user= userService.selectUserByUserName(userName);
            if (StringUtils.isNull(user)) {
                log.info("登录用户：{} 不存在.", userName);
                throw new ServiceException("登录用户：" + userName + " 不存在");
            } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
                log.info("登录用户：{} 已被删除.", userName);
                throw new ServiceException("对不起，您的账号：" + userName + " 已被删除");
            } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
                log.info("登录用户：{} 已被停用.", userName);
                throw new ServiceException("对不起，您的账号：" + userName + " 已停用");
            }
            passwordService.validate(user);

            return createLoginUser(user);
        }
    }

    public UserDetails createLoginUser(SysUser user) {
        return new LoginUser(user.getUserId(), 0L, user, permissionService.getMenuPermission(user));
    }

    public UserDetails createLoginUserForTenant(SysUser user) {
        sysUserMapper.updateUser(user);
        return new LoginUser(user.getTenantId(), user.getTenantName(), user.getUserId(), 0L, user, permissionService.getMenuPermission(user));
    }
}
