package cn.ezhizao.framework.security.service;

import cn.ezhizao.common.enums.UserStatus;
import cn.ezhizao.common.exception.ServiceException;
import cn.ezhizao.common.utils.SecurityUtils;
import cn.ezhizao.common.utils.StringUtils;
import cn.ezhizao.framework.qrCode.QrCodeService;
import cn.ezhizao.framework.security.LoginUser;
import cn.ezhizao.framework.security.context.AuthenticationContextHolder;
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.Tenant;
import cn.ezhizao.project.tenant.service.ITenantService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
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 ITenantService tenantService;

    @Resource
    private QrCodeService qrCodeService;

    @Resource
    HttpServletRequest request;


    @Override
    public UserDetails loadUserByUsername(String userName) {
        String tenantId = request.getHeader("tenantId");
        SysUser user = null;
        /** 租户登录 */
        if (StringUtils.isNotEmpty(tenantId)) {
            Tenant tenant = new Tenant();
            tenant.setId(Long.parseLong(tenantId));
            List<Tenant> tenants = tenantService.getList(tenant);
            if (tenants.size() == 1) {
                tenant = tenants.get(0);
            }
            // 每次登录更新下企业信息
            tenantService.setTenantInfo(tenant);
            tenantService.updateById(tenant);
            if (tenant.getStatus() == 1) {
                throw new ServiceException("企业信息审核中,暂时无法提供相关应用服务。");
            } else if (tenant.getStatus() == 3) {
                throw new ServiceException("企业信息审核未通过,请登录标识解析二级节点业务管理系统修改相关信息。并重新提交");
            }
            user = userService.selectUserByUserNameAndTenantId(userName, tenantId);
            String token = "";
            // 如果是企业管理员账号登录
            if ("01".equals(user.getUserType())) {
                Authentication usernamePasswordAuthenticationToken = AuthenticationContextHolder.getContext();
                String username = usernamePasswordAuthenticationToken.getName();
                String password = usernamePasswordAuthenticationToken.getCredentials().toString();
                if (token.isEmpty()) {
                    passwordService.validate(user);
                } else {
                    tenant.setIdentity(tenant.getEntPrefix() + "/" + tenant.getId());
                    qrCodeService.generateIdentityQrCode(tenant);
                    tenant.setSnmsUserName(username);
                    tenant.setSnmsPassword(password);
                    tenantService.updateById(tenant);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    sysUserMapper.updateUser(user);
                    user.setSnmsToken(token);
                    try {
                        register(tenant, token);
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
                // 如果是企业下属员工登录
            } else {
                String username = tenant.getSnmsUserName();
                String password = tenant.getSnmsPassword();
                if (token.isEmpty()) {
                    passwordService.validate(user);
                } else {
                    user.setSnmsToken(token);
                }
            }
            /** 系统用户登录 */
        } 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);
        }
        if (StringUtils.isNotEmpty(tenantId)) {
            return createLoginUserForTenant(user);
        }
        return createLoginUser(user);
    }

    public String register(Tenant tenant, String token) throws NoSuchFieldException, IllegalAccessException {
        return "";
    }

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

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

}
