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

class LoginController {

    /**
     * 登录页面
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async 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 preferenceSetting = {};
        let compilationList = [];
        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 = await userModel.markUser(sessionUser, request);

            // 获取偏好设置
            let settingModel = new SettingModel();
            preferenceSetting = await settingModel.getPreferenceSetting(request.session.sessionUser.id);

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

            let compilationModel = new CompilationModel();
            compilationList = preferenceSetting.login_ask === 1 ? await compilationModel.getList() : [];
            // 获取编办信息
            let sessionCompilation = request.session.sessionCompilation;
            if (preferenceSetting.login_ask === 0 && !sessionCompilation &&
                preferenceSetting.select_version !== '') {

                let compilationData = await compilationModel.getCompilationById(preferenceSetting.select_version);
                request.session.sessionCompilation = compilationData;
            }


        } catch (error) {
            console.log(error);
            return response.json({error: 1, msg: error});
        }
        response.json({error: 0, msg: '', login_ask: preferenceSetting.login_ask, compilation_list: JSON.stringify(compilationList)});
    }

}

export default LoginController;