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

class Goods {
  @prop({ required: true })
  gid: number; // 物品id
  @prop({ required: false })
  count: number; // 这次挂机没来得及领取的
}

export class NotReceivedGoods {
  @prop({ required: true })
  cnt: number; // 加速的次数
  @prop({ required: true, default: [], type: Goods, _id: false })
  goods: Array<Goods>; // 这次挂机没来得及领取的
}
/**
  * 挂机记录表
  */
@index({ roleId: 1, lv: 1 })

export default class HangUpSpdUpRec extends BaseModel {
  @prop({ required: true })
  roleId: string; // 角色 id
  @prop({ required: true })
  roleName: string; // 角色名

  @prop({required: true, default: 1})
  cnt: number; // 加速次数
  @prop({required: true, default: 1})
  lv: number; // 天梯层数

  @prop({ required: true, default: [], type: NotReceivedGoods, _id: false })
  notReceivedGoodsList: Array<NotReceivedGoods>

  public static async getSpdUpRec(roleId, lv, lean = true ) {
    let rec = await HangUpSpdUpRecModel.findOne({roleId, lv}).lean(lean);
    return rec;
  }

  public static async getLatestSpdUpRec(roleId, lean = true ) {
    let rec = await HangUpSpdUpRecModel.findOne({roleId}).sort({ lv: -1 }).lean(lean);
    return rec;
  }

  public static async updateRec(roleId, roleName, multi, lv, needReceiveGoods: Array<{gid:number, count: number}>, lean = true ) {
    if (multi <= 0) return null;
    let rec: HangUpSpdUpRecType = await HangUpSpdUpRecModel.findOneAndUpdate({roleId, lv, roleName}, {$inc: {cnt: multi}}, {upsert: true, new: true}).lean(lean);
    if(rec && needReceiveGoods.length > 0) {
      let {cnt} = rec;
      let goods = [{
        cnt: cnt,
        goods: needReceiveGoods
      }];
      await HangUpSpdUpRecModel.findOneAndUpdate({roleId, lv, roleName}, {$push: {notReceivedGoodsList: {$each: goods}}}, {upsert: true, new: true}).lean(lean);  
    }
    return rec;
  }

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

}

export const HangUpSpdUpRecModel = getModelForClass(HangUpSpdUpRec);

export interface HangUpSpdUpRecType extends Pick<DocumentType<HangUpSpdUpRec>, keyof HangUpSpdUpRec>{};
