const system = require("../../../system");
const ServiceBase = require("../../sve.base");
const moment = require("moment");

class MsgService extends ServiceBase {
    constructor() {
        super("msg", ServiceBase.getDaoName(MsgService));
        this.msguserDao = system.getObject("db.msg.msguserDao");

    }
    async create(pobj, qobj, req) {
        let {
            msgType, app_id, app_key, sender, sender_id, title,
            content, jump_address, other, target, company_id
        } = pobj;

        let msg = {
            msgType,
            app_id,
            app_key,
            sender: sender,
            sender_id: sender_id,
            title,
            content,
            jump_address,
            other,
            company_id
        }
        return this.db.transaction(async (t) => {
            const msgData = await this.dao.create(msg, t);
            if (msgType !== system.Msg.SYS && Object.prototype.toString.call(target) === '[object Object]') {
                await this.msguserDao.create({
                    user_id: target.id,
                    user: target.name,
                    msg_id: msgData.id
                }, t);
            }
            if (msgType !== system.Msg.SYS && Object.prototype.toString.call(target) === "[object Array]") {
                let msgusers = [];
                for (let val of target) {
                    msgusers.push({
                        user_id: val.id,
                        user: val.name,
                        msg_id: msgData.id
                    })
                }
                await this.msguserDao.bulkCreate(msgusers, t);
            }
            return 'SUCCESS'
        })
    }

    async findRemindMessage(pobj, qobj, req) {
        let { userid } = pobj;
        const msgData = await this.msguserDao.findAll({
            user_id: userid,
            is_remind: false
        }, [
            {
                model: this.db.models.msg,
                where: {
                    is_undo: false
                },
            }
        ]);
        const ids = msgData.map(item => item.id)
        if (ids.length > 0) {
            this.msguserDao.updateByWhere({
                is_remind: true
            }, {
                id: {
                    $in: ids
                }
            });
        }
        return msgData;
    }

    async findUnreadCount(pobj, qobj, req) {
        let { userid, is_read } = pobj;
        const msgCount = await this.msguserDao.findCount({
            where: {
                user_id: userid,
                is_read
            }, include: [
                {
                    model: this.db.models.msg,
                    where: {
                        is_undo: false
                    },
                    attributes: ["id"]
                }
            ]
        });
        return { count: msgCount };
    }

    async updateStatus(pobj, qobj, req) {
        let { id, userid, all } = pobj;
        let where = {
            is_read: false,
            user_id: userid
        };
        if (!all) {
            where.id = id
        }
        await this.msguserDao.updateByWhere({
            is_read: true
        }, where);
        return "SUCESS"
    }

    async findSystemMsgCount(pobj, qobj, req) {
        let { type, company_id } = pobj;

        let where = {
            msgType: system.Msg.SYS,
            is_undo: false,
            company_id: {
                $in: [1, company_id]
            }
        }
        if (type === "recently") {
            // 查询 三天内的
            where.created_at = {
                $between: [
                    moment().subtract('days', 3).endOf('day').format('YYYY-MM-DD HH:mm:ss'),
                    moment().endOf('day').format('YYYY-MM-DD HH:mm:ss')
                ]
            }
        }
        const msgCount = await this.dao.findCount({
            where
        });
        return { count: msgCount };
    }

    async groupCount(pobj, qobj, req) {
        let { userid } = pobj;
        let [read, unRead, system] = await Promise.all(
            [
                this.findUnreadCount({ userid, is_read: true }),
                this.findUnreadCount({ userid, is_read: false }),
                this.findSystemMsgCount({ type: "all" })
            ]
        );
        return {
            read: read.count, unRead: unRead.count, system: system.count
        }
    }

    async list(pobj, qobj, req) {
        let { userid, msgType, pageSize = 10, pageNo = 1, company_id } = pobj;
        let msgData = [];
        let other = {
            limit: pageSize,
            offset: (pageNo - 1) * pageSize,
            order: [["created_at", "DESC"]]
        };
        if (["readed", "unread"].includes(msgType)) {
            msgData = await this.msguserDao.findAll({
                user_id: userid,
                is_read: msgType === "readed"
            }, [
                {
                    model: this.db.models.msg,
                    where: {
                        is_undo: false
                    }
                }
            ], other);
        }
        if (msgType === "sys") {
            msgData = await this.dao.findAll({
                msgType: system.Msg.SYS,
                is_undo: false,
                company_id: {
                    $in: [1, company_id]
                }
            }, [], other);
            msgData = msgData.map(item => {
                return {
                    msg: item
                }
            })
        }
        return msgData;
    }
}
module.exports = MsgService;
