package com.ruoyi.web.modules.screen.support;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.modules.screen.domain.vo.ScreenLoginRsaPublicKeyVo;

/**
 * 大屏免密登录：校验 RSA 加密 UUID 后为专用账号签发若依 JWT。
 */
@Service
public class ScreenLoginService
{
    private static final String AUTH_FAIL_MSG = "大屏登录认证失败";

    @Autowired
    private ScreenLoginProperties properties;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private TokenService tokenService;

    public ScreenLoginRsaPublicKeyVo getRsaPublicKey()
    {
        assertLoginReady();
        return new ScreenLoginRsaPublicKeyVo(properties.getRsaPublicKey());
    }

    public String login(String encryptedToken)
    {
        assertLoginReady();
        validateEncryptedToken(encryptedToken);
        SysUser user = loadScreenUser();
        LoginUser loginUser = new LoginUser(user.getUserId(), user.getDeptId(), user, ScreenLoginPermissions.all());
        userService.updateLoginInfo(user.getUserId(), IpUtils.getIpAddr(), DateUtils.getNowDate());
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(user.getUserName(), Constants.LOGIN_SUCCESS,
                MessageUtils.message("user.login.success")));
        return tokenService.createToken(loginUser);
    }

    private void assertLoginReady()
    {
        if (!properties.isEnabled())
        {
            throw new ServiceException("大屏免密登录未启用");
        }
        if (StringUtils.isEmpty(properties.getRsaPublicKey()) || StringUtils.isEmpty(properties.getRsaPrivateKey()))
        {
            throw new ServiceException("大屏免密登录未配置 RSA 密钥");
        }
    }

    private void validateEncryptedToken(String encryptedToken)
    {
        if (StringUtils.isEmpty(encryptedToken))
        {
            recordAuthFail();
            throw new ServiceException(AUTH_FAIL_MSG);
        }
        String plain = ScreenLoginRsaSupport.decrypt(encryptedToken, properties.getRsaPrivateKey());
        if (!ScreenLoginRsaSupport.isValidUuid(plain))
        {
            recordAuthFail();
            throw new ServiceException(AUTH_FAIL_MSG);
        }
    }

    private void recordAuthFail()
    {
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(properties.getUsername(), Constants.LOGIN_FAIL,
                AUTH_FAIL_MSG));
    }

    private SysUser loadScreenUser()
    {
        String username = properties.getUsername();
        if (StringUtils.isEmpty(username))
        {
            throw new ServiceException("大屏免密登录未配置专用账号");
        }
        SysUser user = userService.selectUserByUserName(username.trim());
        if (StringUtils.isNull(user))
        {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL,
                    MessageUtils.message("user.not.exists")));
            throw new ServiceException("大屏专用账号不存在");
        }
        if (UserStatus.DELETED.getCode().equals(user.getDelFlag()))
        {
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        }
        if (UserStatus.DISABLE.getCode().equals(user.getStatus()))
        {
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }
        return user;
    }
}
