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; // 这次挂机没来得及领取的
}
/**
  * 挂机记录表
  */
@index({ roleId: 1, startLv: 1 })

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

  @prop({ required: true, default: 0 })
  speedUpTime: number; // 加速时长

  @prop({ required: true, default: 1 })
  startLv: number; // 开始挂机时的天梯层数，收益使用当前层数 -1 计算，即用户已经通过的最高层
  @prop({ required: true })
  startTime: Date; // 开始挂机的时间

  @prop({ required: false })
  endLv: number; // 结束挂机时的层数
  @prop({ required: false })
  endTime: Date; // 结束挂机的时间

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

  @prop({ required: true, default: false })
  received: boolean; // 是否已经领取，true-领取，false-未领取

  public static async initRecord(roleId: string, roleName: string, towerLv: number) {
    // console.log('****** initRecord before')
    const curTime = new Date();
    const recDoc = new HangUpRecordModel();
    const update = Object.assign(recDoc.toJSON(), {roleId, roleName, startTime: curTime, towerLv});
    const rec: HangUpRecordType = await HangUpRecordModel.findOneAndUpdate({roleId, startLv: towerLv}, { $setOnInsert: update }, {upsert: true, new: true}).lean();
    
    // console.log('****** initRecord after')
    return rec;
  }

  public static async getCurRec(roleId: string, lean = true) {
      const rec: HangUpRecordType = await HangUpRecordModel.findOne({roleId, received: false}).lean(lean);
      return rec;
  }

  public static async getLastRec(roleId: string, lean = true) {
    const rec: HangUpRecordType = await HangUpRecordModel.findOne({roleId, received: true}).sort({endTime: -1}).lean(lean);
    return rec;
}

  public static async updateRec(roleId: string, roleName: string, endLv: number, endTime: Date, needReceiveGoods: Array<{gid:number, count: number}>, lean = true) {
    await HangUpRecordModel.updateMany({roleId, received: false}, {endLv, endTime, received: true, notReceivedGoods: needReceiveGoods});
    const recDoc = new HangUpRecordModel();
    const update = Object.assign(recDoc.toJSON(), {roleId, roleName, startTime: endTime, startLv: endLv});
    delete update._id;
    const newRec: HangUpRecordType = await HangUpRecordModel.findOneAndUpdate({roleId, startLv: endLv, received: false}, update, {upsert: true, new: true}).lean(lean);
    return newRec;
  }

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

export const HangUpRecordModel = getModelForClass(HangUpRecord);

export interface HangUpRecordType extends Pick<DocumentType<HangUpRecord>, keyof HangUpRecord>{};
