'use strict';

/**
 * 用户通知相关数据模型
 *
 * @author CaiAoLin
 * @date 2017/11/22
 * @version
 */
module.exports = app => {

    class Notify extends app.BaseService {

        /**
         * 构造函数
         *
         * @param {Object} ctx - egg全局变量
         * @return {void}
         */
        constructor(ctx) {
            super(ctx);
            this.tableName = 'notify';
        }

        /**
         * 同步当前用户的通知数据
         *
         * @return {Boolean}
         */
        async syncNotifyData() {
            let result = false;
            // 获取session中的数据
            const sessionUser = this.ctx.session.sessionUser;
            if (sessionUser === null || sessionUser === undefined) {
                return result;
            }
            try {
                // 获取当前用户最后一条数据
                const condition = {
                    where: { uid: sessionUser.accountId, type: sessionUser.loginType },
                    orders: [['id', 'DESC']],
                    limit: 1,
                };

                const lastData = await this.db.select(this.tableName, condition);
                const lastMessageTime = lastData.length <= 0 ? 0 : lastData[0].create_time;

                // 获取后台设置的消息数据
                const messageData = await this.ctx.service.message.getMessage(lastMessageTime);
                // 如果已经是最新的消息则直接返回
                if (messageData.length <= 0) {
                    return true;
                }

                // 新增通知数据
                const currentTime = new Date().getTime() / 1000;
                const insertData = [];
                for (const message of messageData) {
                    const tmp = {
                        mid: message.id,
                        create_time: currentTime,
                        uid: sessionUser.accountId,
                        type: sessionUser.loginType,
                    };
                    insertData.push(tmp);
                }

                const operate = this.db.insert(this.tableName, insertData);
                result = operate.affectedRows > 0;
            } catch (error) {
                console.log(error);
                result = false;
            }

            return result;
        }
    }

    return Notify;
};
