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

/**
  * 百家学宫表
*/

@index({ roleId: 1, schoolId: 1, positionId: 1 })

export default class School extends BaseModel {

  @prop({ required: true })
  roleId: string;					// 角色 id

  @prop({ required: true })
  schoolId: number;				// 学院id
  @prop({ required: true })
  positionId: number;			// 位置id
  @prop({ required: true, default: 0 })
  hid: number;				    // 放置的武将
  @prop({ required: true, default: 0 })
  quality: number;				    // 放置的武将的品质
  @prop({ required: true, default: 0 })
  star: number;				    // 放置的武将的星级
  @prop({ required: true, default: 0 })
  colorStar: number;		  // 放置的武将的彩星
  @prop({ required: true, default: false })
  isOpen: boolean;				// 位置是否开启

  public static async findByRoleId(roleId: string) {
    let result: SchoolType[] = await SchoolModel.find({ roleId }).lean();
    return result;
  }

  public static async findBySclAndPos(roleId: string, schoolId: number, positionId: number) {
    let result: SchoolType = await SchoolModel.findOne({ roleId, schoolId, positionId }).lean();
    return result;
  }

  public static async findByHid(roleId: string, hid: number) {
    let result: SchoolType = await SchoolModel.findOne({ roleId, hid }).lean();
    return result;
  }

  public static async updateBySclAndPos(roleId: string, schoolId: number, positionId: number, update: SchoolUpdate) {

    const doc = new SchoolModel();
    const setOnInsert = doc.toJSON();
    for(let key in update) delete setOnInsert[key];
    delete setOnInsert._id;
    const result: SchoolType = await SchoolModel.findOneAndUpdate({ roleId, schoolId, positionId }, { $setOnInsert: setOnInsert, $set: update }, { new: true, upsert: true }).lean();
    return result;

  }

  public static async updateByHid(roleId: string, hid: number, update: SchoolUpdate) {
    const result: SchoolType = await SchoolModel.findOneAndUpdate({ roleId, hid }, { $set: update }, { new: true }).lean();
    return result;

  }

  public static async deleteAccount(roleId: string) {
    let result = await SchoolModel.deleteMany({ roleId });
    return result;
  }
}

export const SchoolModel = getModelForClass(School);

export interface SchoolType extends Pick<DocumentType<School>, keyof School> { };
export type SchoolUpdate = Partial<SchoolType>; // 将所有字段变成可选项
