/**
 * 登录页面控制器
 *
 * @author CaiAoLin
 * @date 2017/6/1
 * @version
 */
import BaseController from "../../common/base/base_controller";
import ManagerModel from "../models/manager_model";
import PermissionModel from "../models/permission_model";
import PermissionGroupModel from "../models/permission_group_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 permissionModel = new PermissionModel();
        let permissionGroupModel = new PermissionGroupModel();

        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 menuData = {
                'dashboard': {
                    title: '首页',
                    url: '/dashboard',
                    name: 'dashboard',
                    iconClass: 'glyphicon glyphicon-home'
                }
            };
            let toolMenuData = [];
            let toolPermissionController = [];
            if (managerData.super_admin !== 1) {
                let permissionGroup = managerData.permission !== undefined && managerData.permission !== '' ?
                    await permissionGroupModel.findDataByCondition({_id: managerData.permission}) : '';
                // let otherPermission = [];
                if (permissionGroup !== undefined && permissionGroup !== '' && permissionGroup.permission !== undefined && permissionGroup.permission !== '') {
                    let permissionIdList = JSON.parse(permissionGroup.permission);
                    for (let top of permissionIdList.top) {
                        let permissionInfo = await permissionModel.findDataByCondition({_id:top});
                        menuData[permissionInfo.controller] = {
                            title: permissionInfo.name,
                            url: permissionInfo.url,
                            name: permissionInfo.controller,
                            iconClass: 'glyphicon ' + permissionInfo.iconClass,
                            children: {},
                        }
                    }
                    for (let per in permissionIdList) {
                        if (per !== 'top' && per !== 'tool') {
                            let permissionArray = permissionIdList[per];
                            for (let pa of permissionArray) {
                                let permissionInfo = await permissionModel.findDataByCondition({_id:pa});
                                if (permissionInfo !== undefined && permissionInfo !== '') {
                                    if (permissionInfo.isMenu) {
                                        // 属于二级菜单
                                        let action = {
                                            title: permissionInfo.name,
                                            url: permissionInfo.url,
                                            name: permissionInfo.action,
                                        };
                                        console.log(Object.keys(menuData[permissionInfo.controller].children).length);
                                        if (Object.keys(menuData[permissionInfo.controller].children).length === 0) {
                                            menuData[permissionInfo.controller].url = action.url;
                                        }
                                        menuData[permissionInfo.controller].children[permissionInfo.action] = action;
                                    } else {
                                        // 其它权限
                                        // otherPermission.push({
                                        //     title: permissionInfo.name,
                                        //     url: permissionInfo.url,
                                        //     name: permissionInfo.action,
                                        // });
                                    }
                                }
                            }
                        } else if (per === 'tool') {
                            // 工具里的页面权限
                            let permissionArray = permissionIdList[per];
                            for (let pa of permissionArray) {
                                let permissionInfo = await permissionModel.findDataByCondition({_id:pa});
                                if (!permissionInfo) {
                                    console.log(`pa`);
                                    console.log(pa);
                                }
                                if (permissionInfo.isMenu) {
                                    toolMenuData.push({
                                        title: permissionInfo.name,
                                        controller: permissionInfo.controller,
                                        url: permissionInfo.url,
                                        sort: permissionInfo.ID  // 用来排序
                                    });
                                }
                                toolPermissionController.push(permissionInfo.controller);
                                // 对于工具里的多个控制层进行优化处理
                                if (permissionInfo.otherController !== undefined && permissionInfo.otherController !== '') {
                                    for (let other of permissionInfo.otherController.split(',')) {
                                        toolPermissionController.push(other);
                                    }
                                }
                            }
                        }
                    }
                }
            } else {
                // 获取数据库菜单列表
                let menuPermissionList = await permissionModel.getList({isMenu:true});
                let subList = [];
                for (let menu of menuPermissionList) {
                    if (menu.pid === 0) {
                        menuData[menu.controller] = {
                            title: menu.name,
                            url: menu.url,
                            name: menu.controller,
                            iconClass: 'glyphicon ' + menu.iconClass,
                            children: {},
                        }
                    } else if (menu.pid !== 4) {
                        subList.push(menu);//防止子节点ID比父节点ID小的问题
                    }
                }
                for(let s of subList){
                    let action = {
                     title: s.name,
                     url: s.url,
                     name: s.action,
                     };
                     menuData[s.controller].children[s.action] = action;
                }

                // 超级管理员二级菜单添加
                menuData['manager'].children['admin'] = {
                    title: '超级管理员',
                    url: '/manager/admin',
                    name: 'admin',
                }
            }
            // 获取所有工具里的权限控制器名称
            let toolAllPermission = [];
            let toolAllPermissionList = await permissionModel.getList({pid:4});
            console.log(`toolAllPermissionList`);
            console.log(toolAllPermissionList);
            for (let tool of toolAllPermissionList) {
                toolAllPermission.push(tool.controller);
                if (managerData.super_admin === 1) {
                    toolMenuData.push({
                        title: tool.name,
                        controller: tool.controller,
                        url: tool.url,
                        sort: tool.ID  // 用来排序
                    });
                }
                if (tool.otherController !== undefined && tool.otherController !== '') {
                    for (let other of tool.otherController.split(',')) {
                        toolAllPermission.push(other);
                    }
                }
            }

            let managerSession = {
                username: managerData.username,
                real_name:managerData.real_name,
                loginTime: currentTime,
                sessionToken: sessionToken,
                userID: managerData.id,
                toolPermission: toolPermissionController.join(','),
                toolMenuData: toolMenuData,
                toolAllPermission: toolAllPermission.join(','),
                menuData: menuData,
                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) {
            console.log(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;
