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

/**
  * 派遣任务记录表
  */
@index({ rid: 1 })
@index({ code: 1 })

export default class ScriptBarrage extends BaseModel {
  @prop({ required: true })
  code: string;					  // 弹幕唯一标识
  @prop({ required: true })
  roleId: string;					// 角色 id
  @prop({ required: true })
  warId: number;          // 关卡id
  @prop({ required: true })
  rid: string;            // 剧本id
  @prop({ required: true })
  index: string;          // 对话索引
  @prop({ required: true })
  content: string;        // 弹幕内容


  public static async createBarrage(roleId: string, warId: number, rid: string, index: string, content: string) {
    const code = genCode(10);
    let result: ScriptBarrageType = await ScriptBarrageModel.findOneAndUpdate({ code }, { $setOnInsert: { roleId, warId, rid, index, content } }, { new: true, upsert: true }).lean();
    return result;
  }

  public static async getBarrageList(rid: string, limit: number) {
    let result: ScriptBarrageType[] = await ScriptBarrageModel.find({ rid }, { _id: 0 }).limit(limit).sort({ index: 1, createdAt: -1 }).lean();
    return result;
  }
  
}

export const ScriptBarrageModel = getModelForClass(ScriptBarrage);

export interface ScriptBarrageType extends Pick<DocumentType<ScriptBarrage>, keyof ScriptBarrage>{};