import extend from "./extend";
import token from "./token";
import user from "./user";

/**
 * 登录类
 */
class Login {
    /**
     * 是否登录
     * @returns {boolean}
     */
    logined() {
        return token.has();
    }

    /**
     * 获取登录信息
     * @returns {object}
     */
    getRemember() {
        return user.getRemember();
    }

    /**
     * 登录
     * @param {object} data 登录参数
     * @param {string} data.username 用户名
     * @param {string} data.password 密码
     * @param {string} data.client_id
     * @param {string} data.client_secret
     * @param {string} data.grant_type
     * @returns {{success:boolean,message:string}}
     */
    async login(data) {
        let result = {
            success: false,
            message: ''
        };
        let res = await token.getByServer({
            url: 'oauth2/token',
            data: data
        });
        if (res.success) {
            let userRes = await user.getByServer({
                url: 'auman/user/info'
            });

            if (userRes.success) {
                result.success = true;

                // 登录成功
                user.setRemember({
                    username: this.username,
                    password: this.password
                });
            } else {
                result.message = userRes.message;
            }
        } else {
            result.message = res.message;
        }
        if (!result.success) {
            token.clear();
            user.clear();
        }
        return result;
    }
}

export default new Login();