/**
 * 登录相关控制器
 *
 * @author CaiAoLin
 * @date 2017/6/8
 * @version
 */
import UserModel from "../models/user_model";

class LoginController {

    /**
     * 登录页面
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    index(request, response) {
        let sessionUser = request.session.sessionUser;
        if (sessionUser !== undefined && sessionUser.ssoId >= 0) {
            return response.redirect("/pm");
        }
        response.render('users/html/login', {});
    }

    /**
     * 登录操作
     *
     * @param {object} request
     * @param {object} response
     * @return {string}
     */
    async login(request, response) {
        let account = request.body.account;
        let password = request.body.pw;
        let userExist = true;

        try {
            // 调用接口验证登录信息
            let userModel = new UserModel();
            let responseData = await userModel.getInfoFromSSO(account, password);
            responseData = JSON.parse(responseData);
            if (typeof responseData !== 'object') {
                throw '邮箱/手机 或 密码错误';
            }

            if (responseData.length <= 0) {
                throw '接口返回数据错误';
            }

            // 正确登录后 存入session
            let userData = responseData[0];
            let sessionUser = {
                ssoId: userData.id,
                username: userData.username,
                email: userData.useremail,
                mobile: userData.mobile
            };
            request.session.sessionUser = sessionUser;
            // 记录用户数据到数据库
            let [result, exist] = await userModel.markUser(sessionUser);
            userExist = exist;

            if (!result) {
                throw '标记用户信息失败!';
            }

        } catch (error) {
            return response.json({error: 1, msg: error});
        }

        response.json({error: 0, msg: '', exist: userExist ? 1 : 0});
    }

}

export default LoginController;