import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType, modelOptions } from '@typegoose/typegoose';
import { MSG_STATUS } from '../consts';

/**
  * 私聊信息
**/
@modelOptions({ schemaOptions: { id: false } })
@index({ roomId: 1, seqId: -1 })
@index({ msgId: 1 })
export default class PrivateMessage extends BaseModel {
    @prop({ required: true, default: '' })
    roomId: string; // 频道唯一 Id，由 roleId 和 targetRoleId 排序后拼接
    @prop({ required: true, default: 0 })
    type: number; // 消息类型：0，纯文本；1，富文本；2，表情
    @prop({ required: true, default: 0 })
    source: number; // 消息来源：0，玩家；1，玩家送礼；2，武将升品...

    @prop({ required: true, default: '' })
    roleId: string; // 消息发送者 roleId
    @prop({ required: true, default: '' })
    roleName: string; // 消息发送者名称
    @prop({ required: true, default: '' })
    targetRoleId: string; // 接收者 roleId
    @prop({ required: true, default: '' })
    targetRoleName: string; // 接收者名称

    @prop({ required: true, default: '' })
    msgCode: string; // 消息唯一 Id
    @prop({ required: true, default: 0 })
    seqId: number; // 消息在本聊天室的递增 Id
    @prop({ required: true, default: '' })
    targetMsgCode: string; // 回复消息的唯一 Id

    @prop({ required: true, default: 0 })
    status: number; // 消息状态：0，正常；1，屏蔽

    @prop({ required: true, default: '' })
    content: string; // 消息内容

    public static async createMsg(data: PrivateMessageParam) {
      const result = await PrivateMessageModel.findOneAndUpdate({ msgCode: data.msgCode }, {...data}, {upsert: true, new: true}).lean();
      return result;
    }

    public static async findOneMsg(query: PrivateMessageParam) {
      const result = await PrivateMessageModel.findOne(query).lean();
      return result;
    }

    public static async getMsgs(roomId: string, fromSeqId: number, count: number) {
      const result = await PrivateMessageModel.find({ roomId, seqId: { $lt: fromSeqId }, status: MSG_STATUS.NORMAL }).sort({ seqId: -1 }).limit(count).lean();
      return result;
    }

    public static async getMsgsByTime(roomId: string, time: Date, count: number) {
      const result = await PrivateMessageModel.find({ roomId, createdAt: { $gt: time }, status: MSG_STATUS.NORMAL }).sort({ seqId: -1 }).limit(count).lean();
      return result;
    }

    public static async getMsgByRooms(roomIds: string[], count: number) {
      const result = await PrivateMessageModel.find({ roomId: { $in: roomIds }, status: MSG_STATUS.NORMAL }).sort({ seqId: -1 }).limit(count).lean();
      return result;
    }

    public static async blockMsg(roomId: string) {
      await PrivateMessageModel.updateMany({ roomId }, { $set: { status: MSG_STATUS.BLOCKED } });
    }
}


export const PrivateMessageModel = getModelForClass(PrivateMessage);

export interface PrivateMessageType extends Pick<DocumentType<PrivateMessage>, keyof PrivateMessage> {};
export type PrivateMessageParam = Partial<PrivateMessageType>;
