/**
 * 控制器基类
 *
 * @author CaiAoLin
 * @date 2017/6/29
 * @version
 */
const Moment = require('moment');
const Url = require('url');
const UserMessageModel = require('../../users/models/user_message_model');

class BaseController {

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

    /**
     * 初始化函数
     *
     * @param {object} request
     * @param {object} response
     * @param {function} next
     * @return {void}
     */
    async 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;
        }
        response.locals.controller = controller;
        response.locals.action = action;

        // moment工具
        response.locals.moment = Moment;

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

        // 获取当前用户数据
        let sessionUser = request.session.sessionUser;

        // 获取当前用户消息数量
        let userMessageModel = new UserMessageModel();
        // 消息处理
        await userMessageModel.initMessage(sessionUser.id);
        // 获取未读数据
        let messageUnreadCount = await userMessageModel.count({user_id: sessionUser.id, is_read: 0, is_delete: 0});
        response.locals.unreadCount = messageUnreadCount;
        next();
    }
}

module.exports = BaseController;