/**
 * 控制器基类
 *
 * @author CaiAoLin
 * @date 2017/6/29
 * @version
 */
import crypto from "crypto";
import Url from "url";
import Moment from 'moment-timezone';
// import menuData from "../../../config/menu";

class BaseController {

    /**
     * 页面title
     *
     * @var string
     */
    title = '';

    /**
     * 构造函数
     *
     * @return {void}
     */
    constructor() {
        /**
         * 使BaseController可以实例化，可作为中间件使用
         */
        /*if (new.target === BaseController) {
            throw new Error('BaseController不能实例化,只能继承使用。');
        }*/
    }

    /**
     * 初始化函数
     *
     * @param {object} request
     * @param {object} response
     * @param {function} next
     * @return {void}
     */
    init(request, response, next) {
        // 获取当前控制器和动作名称
        let urlInfo = Url.parse(request.originalUrl, true);
        let url = urlInfo.pathname.substr(1);
        let actionInfo = url.split('/');
        let controller = 'index';
        let action = 'index';
        switch (actionInfo.length) {
            case 1:
                controller = actionInfo[0];
                break;
            case 2:
                controller = actionInfo[0];
                action = actionInfo[1];
                break;
            default:
                controller = actionInfo[0];
                break;
        }

        try {
            console.log('enterINit');
            // 如果不适超级管理员则判断权限
            let sessionManager = request.session.managerData;
            let MenuPermission = sessionManager.menuData;
            if (sessionManager.superAdmin !== 1) {
                let currentPermission = sessionManager.toolPermission;
                // MenuPermission = sessionManager.menuData;
                // 校验权限 暂时只检测能否使用该controller名称的总权限，不细分
                currentPermission = currentPermission.split(',');
                let withoutPermission = ['login', 'dashboard'];

                // 工具
                let toolAllPermission = sessionManager.toolAllPermission;
                toolAllPermission = toolAllPermission.split(',');
                // let toolAllPermission = ['stdBillsmain', 'rationRepository', 'rpt_tpl', 'stdGljRepository',
                //     'billsGuidance', 'clearJunk', 'billsTemplate', 'mainTreeCol',
                //     'materialReplace', 'projectFeature', 'feeRate', 'calcProgram'];
                let hasToolPermission = true;
                if (toolAllPermission.indexOf(controller) >= 0 && currentPermission.indexOf(controller) < 0) {
                    hasToolPermission = false;
                }

                let currentControllerPermission = '';
                // let currentActionPermission = true;

                if(withoutPermission.indexOf(controller) < 0) {
                    if (MenuPermission.hasOwnProperty(controller)) {
                        currentControllerPermission = MenuPermission[controller];

                    }

                    // if (currentControllerPermission !== '' && action !== 'index') {
                    //     if (currentControllerPermission.children.hasOwnProperty(action)) {
                    //         currentActionPermission = true;
                    //     }
                    // } else if (action === 'index') {
                    //     currentActionPermission = true
                    // }
                }

                if (withoutPermission.indexOf(controller) < 0 &&
                    !(hasToolPermission || currentControllerPermission !== '')) {

                    throw '没有权限';
                }
            }

            // 菜单数据
            response.locals.menu = MenuPermission;
            // 二级菜单数据
            response.locals.secondMenu = MenuPermission[controller] !== undefined && MenuPermission[controller].children !== undefined ?
                MenuPermission[controller].children : {};

            // url相关数据
            response.locals.urlQuery = JSON.stringify(urlInfo.query);
            response.locals.controller = controller;
            response.locals.action = action;

            // 用户session数据
            response.locals.manager = sessionManager;

            // moment工具
            response.locals.moment = Moment;
        } catch (error) {
            console.log('enterAURE');
            console.log(error);
            response.redirect('/dashboard');
            return;
        }

        next();
    }

    /**
     * 验证方法
     *
     * @param {object} request
     * @param {object} response
     * @param {function} next
     * @return {void}
     */
    auth(request, response, next) {
        // 判断session
        let mangerData = request.session.managerData;
        try {
            console.log('enterAuth');
            if (typeof mangerData !== 'object' || Object.keys(mangerData).length < 0) {
                throw 'err data';
            }

            if (mangerData.username === undefined || mangerData.loginTime === undefined) {
                throw 'username empty';
            }
            // 校验session
            let sessionToken = crypto.createHmac('sha1', mangerData.loginTime + '')
                .update(mangerData.username).digest().toString('base64');
            if (sessionToken !== mangerData.sessionToken) {
                throw 'session error';
            }

        } catch (error) {
            console.log('enterAURE');
            response.redirect('/login');
            return;
        }

        next();
    }

}

export default BaseController;