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

/**
  * 群聊信息
**/
@modelOptions({ schemaOptions: { id: false } })
@index({ roomId: 1, seqId: 1 })
@index({ msgId: 1 })
export default class GroupMessage extends BaseModel {

    @prop({ required: true, default: '' })
    channel: string; // 频道类型：1，系统；2，世界；3，军团；4，组队
    @prop({ required: true, default: '' })
    channelId: string; // 具体频道标识
    @prop({ required: true, default: '' })
    roomId: string; // 频道唯一 Id，由 channel 和 channelId 拼接：world_serverId，guild_guildId
    @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; // 消息内容

    @prop({ required: true, default: '' })
    otherInfo: string; // 其他信息

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

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

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


export const GroupMessageModel = getModelForClass(GroupMessage);

export interface GroupMessageType extends Pick<DocumentType<GroupMessage>, keyof GroupMessage> {};
export type GroupMessageParam = Partial<GroupMessageType>;
