import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType } from '@typegoose/typegoose';
import { DicWar } from '../pubUtils/dictionary/DicWar'
@index({ roleId: 1, battleId: 1 })

export default class RScriptRecord extends BaseModel {
  @prop({ required: true, default: '' })
  roleId: string;					// 角色 id

  @prop({ required: true, default: 0 })
  battleId: number;				    // 关卡 id
  @prop({ required: true, default: 0 })
  warType: number;				    // 关卡 id

  @prop({ required: false, default: '' })
  scriptBefore: string;             // 战场前剧本

  @prop({ required: false, default: '' })
  scriptAfter: string;              // 战场后剧本


  public static async setScript(roleId: string, battleId: number, warType: number, type: number, script: string, lean = true) {
     let update = { warType };
      if(type == 1) {
        update['scriptBefore'] = script;
      } else if (type == 2) {
        update['scriptAfter'] = script;
      }
      
    const items: RScriptRecordType = await RScriptRecordModel.findOneAndUpdate({ roleId, battleId }, update, {upsert: true, new: true}).lean(lean);
    return items;
  }

  public static async findbyRoleAndBattle(roleId: string, battleId: number, lean = true) {
    const items: RScriptRecordType = await RScriptRecordModel.findOne({ roleId, battleId }).select('battleId scriptBefore scriptAfter').sort({battleId: 1}).lean(lean);
    return items;
  }

  public static async findbyRole(roleId: string, warType: number, lean = true) {
    const items: RScriptRecordType[] = await RScriptRecordModel.find({ roleId, warType }).select('battleId scriptBefore scriptAfter').lean(lean);
    return items;
  }

  public static async deleteByWarType(roleId: string, warType: number) {
    return await RScriptRecordModel.deleteMany({ roleId, warType });
  }
  public static async deleteByWarId(roleId: string, battleId: number[]) {
    return await RScriptRecordModel.deleteMany({ roleId, battleId: { $in: battleId } });
  }

  public static async insertScripts(roleId: string, dicWars: DicWar[], skipScriptAfter = []) {
    let insertParams = dicWars.map(dicWar => {
      let doc = new RScriptRecordModel();
      let param = { ...doc.toJSON(), roleId, battleId: dicWar.war_id, warType: dicWar.warType }
      if(dicWar.scriptBefore) param.scriptBefore = dicWar.scriptBefore;
      if(dicWar.scriptAfter && skipScriptAfter.indexOf(dicWar.war_id) == -1) param.scriptAfter = dicWar.scriptAfter;
      return param;
    });
    // console.log('&&&&', insertParams
    return await RScriptRecordModel.insertMany(insertParams);
  }
}

export const RScriptRecordModel = getModelForClass(RScriptRecord);

export interface RScriptRecordType extends Pick<DocumentType<RScriptRecord>, keyof RScriptRecord>{};