package com.ruoyi.framework.web.service;

import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.CommonDelFlag;
import com.ruoyi.common.enums.CommonStatus;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;
import com.ruoyi.system.domain.SysTenant;
import com.ruoyi.system.service.ISysTenantService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

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

    @Autowired
    private ISysUserService userService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysTenantService tenantService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 获取租户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) AuthenticationContextHolder.getContext();

        if (ObjectUtil.isNull(authentication.getDetails())) {
            log.info("租户信息不能为空");
            throw new ServiceException("租户信息不能为空");
        }

        String tenantId = authentication.getDetails().toString();
        SysTenant sysTenant = tenantService.selectSysTenantByTenantId(tenantId);
        if (ObjectUtil.isNull(sysTenant)) {
            log.info("登录租户：{} 不存在.", sysTenant.getCompanyName());
            throw new ServiceException(MessageUtils.message("tenant.not.exists"));
        } else if (CommonDelFlag.DELETED.getCode().equals(sysTenant.getDelFlag())) {
            log.info("登录租户：{} 已被删除.", sysTenant.getCompanyName());
            throw new ServiceException(MessageUtils.message("tenant.delete"));
        } else if (CommonStatus.DISABLE.getCode().equals(sysTenant.getStatus())) {
            log.info("登录租户：{} 已被停用.", sysTenant.getCompanyName());
            throw new ServiceException(MessageUtils.message("tenant.blocked"));
        } else if (ObjectUtil.isNotNull(sysTenant.getExpireTime())) {
            if (sysTenant.getExpireTime().getTime() < System.currentTimeMillis()) {
                log.info("登录租户：{} 已过期.", sysTenant.getCompanyName());
                throw new ServiceException(MessageUtils.message("tenant.expire"));
            }
        }

        SysUser user = userService.selectUserByUserName(username, tenantId);
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }

        passwordService.validate(user);

        return createLoginUser(user);
    }

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