package com.yunzhupaas.granter;

import com.yunzhupaas.base.ActionResult;
import com.yunzhupaas.base.UserInfo;
import com.yunzhupaas.consts.AuthConsts;
import com.yunzhupaas.database.util.TenantDataSourceUtil;
import com.yunzhupaas.exception.LoginException;
import com.yunzhupaas.model.BaseSystemInfo;
import com.yunzhupaas.model.LoginForm;
import com.yunzhupaas.model.LoginVO;
import com.yunzhupaas.permission.entity.UserEntity;
import com.yunzhupaas.util.JsonUtil;
import com.yunzhupaas.util.LoginHolder;
import com.yunzhupaas.util.UserProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

import static com.yunzhupaas.granter.YunzhupaasOfficialTokenGranter.GRANT_TYPE;

/**
 * YUNZHUPAAS官网专用短信认证
 *
 * @author 云筑产品开发平台组
 * @user N
 * @copyright 深圳市乐程软件有限公司
 * @date 2024/9/17 22:13
 */
@Slf4j
@Component(GRANT_TYPE)
public class YunzhupaasOfficialTokenGranter extends PasswordTokenGranter {

    public static final String GRANT_TYPE = "official";

    @Autowired
    private UserDetailsServiceBuilder userDetailsServiceBuilder;

    @Override
    public ActionResult granter(Map<String, String> loginParameters) throws LoginException {
        LoginForm loginForm = JsonUtil.getJsonToBean(loginParameters, LoginForm.class);
        // 校验短信验证码
        TenantDataSourceUtil.checkOfficialSmsCode(loginForm.getAccount(), loginForm.getCode(), 1);

        UserInfo userInfo = UserProvider.getUser();
        // 切换租户
        switchTenant(userInfo);
        // 获取系统配置
        BaseSystemInfo baseSystemInfo = getSysconfig(userInfo);
        // 预检信息
        preAuthenticate(loginForm, userInfo, baseSystemInfo);
        // 登录账号
        super.loginAccount(userInfo, baseSystemInfo);
        // 返回登录信息
        LoginVO loginResult = getLoginVo(userInfo);
        return ActionResult.success(loginResult);
    }

    /**
     * 可重写实现邮箱、短信、TOTP验证
     *
     * @param loginForm
     * @param sysConfigInfo
     * @throws LoginException
     */
    protected void preAuthenticate(LoginForm loginForm, UserInfo userInfo, BaseSystemInfo sysConfigInfo)
            throws LoginException {
        // 验证密码
        UserEntity userEntity = userDetailsServiceBuilder.getUserDetailService(AuthConsts.USERDETAIL_ACCOUNT)
                .loadUserEntity(userInfo);
        try {
            authenticateLock(userEntity, sysConfigInfo);
        } catch (Exception e) {
            authenticateFailure(userEntity, sysConfigInfo);
            throw e;
        }
        LoginHolder.setUserEntity(userEntity);
    }

    @Override
    protected String getGrantType() {
        return GRANT_TYPE;
    }
}
