package com.njzscloud.common.security.module.wechat.mini;

import com.njzscloud.common.core.ex.ExceptionMsg;
import com.njzscloud.common.core.ex.SysThrowable;
import com.njzscloud.common.security.contant.AuthWay;
import com.njzscloud.common.security.ex.UserLoginException;
import com.njzscloud.common.security.module.password.PasswordLoginForm;
import com.njzscloud.common.security.support.*;
import lombok.RequiredArgsConstructor;

import java.util.Set;

/**
 * 验证码登录认证器
 */
@RequiredArgsConstructor
public class WechatMiniAuthenticationProvider extends AbstractAuthenticationProvider {
    private final IUserService iUserService;
    private final IRoleService iRoleService;

    /**
     * 读取用户信息
     *
     * @param loginForm 登录表单
     * @return 用户信息
     */
    @Override
    protected UserDetail retrieveUser(LoginForm loginForm) throws UserLoginException {
        WechatMiniLoginForm wechatMiniLoginForm = (WechatMiniLoginForm) loginForm;
        UserDetail userDetail;
        try {
            userDetail = iUserService.selectUser(wechatMiniLoginForm);
        } catch (SysThrowable e) {
            throw new UserLoginException(e.msg, e.message.toString());
        }
        if (userDetail == null) throw new UserLoginException(ExceptionMsg.CLI_ERR_MSG, "微信登录失败");
        Long userId = userDetail.getUserId();
        Set<String> roles = iRoleService.selectRoleByUserId(userId);
        return userDetail
                .setAuthWay(AuthWay.WECHAT_MINI)
                .setRoles(roles)
                ;
    }

    /**
     * 获取登录表单类型
     *
     * @return 登录表单类型
     * @see PasswordLoginForm
     */
    @Override
    protected Class<?> getLoginFormClazz() {
        return WechatMiniLoginForm.class;
    }
}
