/**
 * 登录页面控制器
 *
 * @author CaiAoLin
 * @date 2017/6/1
 * @version
 */
import BaseController from "../../common/base/base_controller";
import ManagerModel from "../models/manager_model";
import crypto from "crypto";

import Test1Model from "../../../test/models/test1_model";
import Test2Model from "../../../test/models/test2_model";
import Test3Model from "../../../test/models/test3_model";

class LoginController extends BaseController {

    /**
     * 登录页面
     *
     * @param {object} request
     * @param {object} response
     * @return {void|Mixed}
     */
    index(request, response) {
        let renderData = {
            layout: false,
        };
        let managerSessionData = request.session.managerData;
        if (managerSessionData !== undefined) {
            return response.redirect("/dashboard");
        }
        response.render('users/views/login/index', renderData);
    }

    /**
     * 登录操作
     *
     * @param {object} request
     * @param {object} response
     * @return {string}
     */
    async login(request, response) {
        let username = request.body.username;
        let password = request.body.password;
        let managerModel = new ManagerModel();

        let responseData = {
            error: 0,
            msg: ''
        };
        try {
            let managerData = await managerModel.validLogin(username, password);

            // 成功后写入session
            let currentTime = new Date().getTime();
            let sessionToken = crypto.createHmac('sha1', currentTime + '').update(managerData.username)
                .digest().toString('base64');
            let managerSession = {
                username: managerData.username,
                loginTime: currentTime,
                sessionToken: sessionToken,
                userID: managerData.id,
                permission: managerData.permission === undefined ? '' : managerData.permission,
                superAdmin: managerData.super_admin
            };
            request.session.managerData = managerSession;

            // 更新登录信息
            let ip = request.connection.remoteAddress;
            ip = ip.split(':');
            ip = ip[3] === undefined ? '' : ip[3];
            let updateData = {
                login_ip: ip,
                last_login: new Date().getTime()
            };
            let updateResult = managerModel.updateById(managerData._id, updateData);
            if (!updateResult) {
                throw {code: 44003, err: '更新登录信息失败!'};
            }
        } catch (error) {
            responseData.error = error.code;
            responseData.msg = error.err;
        }
        response.json(responseData);
    }

    /**
     * 退出操作
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    logout(request, response) {
        // 清空session
        request.session.destroy();
        response.redirect('/login');
    }

    /**
     * 压测接口
     *
     * @param {object} request
     * @param {object} response
     * @return {void}
     */
    async test(request, response) {
        let responseData = {
            error: 0,
            msg: ''
        };
        try {

            // 第一个库的操作
            let test1Model = new Test1Model();
            let test1Result = await test1Model.test();
            if (!test1Result) {
                throw 'test1出错';
            }

            // 第二个库操作
            let test2Model = new Test2Model();
            let test2Result = await test2Model.test();
            if (!test2Result) {
                throw 'test2出错';
            }

            // 第三个库操作
            let test3Model = new Test3Model();
            let test3Result = await test3Model.test();
            if (!test3Result) {
                throw 'test3出错';
            }

        } catch (error) {
            console.log(error);
            responseData.error = 1;
            responseData.msg = error;
        }

        response.json(responseData);
    }

}

export default LoginController;
