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


/**
  * 战斗记录接口
  */
@index({ roleId: 1, type: 1 })

export default class DailyRecord extends BaseModel {
  @prop({ required: true })
  roleId: string;					// 角色 id
  @prop({ required: true })
  type: number;						// 每日类型
  @prop({ required: true, default: 0 })
  count: number;          // 挑战次数
  @prop({ required: true, default: 0 })
  buyCount: number;       // 购买次数次数
  @prop({ required: true, default: 0 })
  refTime: number;				// 刷新时间

  public static async getDailyRecordById(roleId: string, type: number, lean = true) {
    const result: DailyRecordType = await DailyRecordModel.findOneAndUpdate({ roleId, type }, {}, {new: true, upsert: true}).lean(lean);
    return result;
  }

  public static async refreshRecord(roleId: string, type: number, lean = true) {
    const dailyRecord: DailyRecordType = await DailyRecordModel.findOne({ roleId, type }).lean(lean);
    let {count = 0, refTime = 0, buyCount = 0} = dailyRecord||{};
    let today = getZeroPoint();

    if(today > refTime) {
        refTime = today; count = 0; buyCount = 0;
    }
    let result: DailyRecordType = await DailyRecordModel.findOneAndUpdate({roleId, type}, {$set: {refTime, count, buyCount}}, {new: true, upsert: true}).lean(lean);
    return result;
  }

  public static async increseDailyCount(roleId: string, type: number, count: number, lean = true) {
    const result: DailyRecordType = await DailyRecordModel.findOneAndUpdate({ roleId, type }, {$inc: { count } }, {new: true, upsert: true}).lean(lean);
    return result;
  }

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

  public static async increseBuyCount(roleId: string, type: number, count: number, lean = true) {
    const result: DailyRecordType = await DailyRecordModel.findOneAndUpdate({ roleId, type }, {$inc: { buyCount:count } }, {new: true, upsert: true}).lean(lean);
    return result;
  }
}

export const DailyRecordModel = getModelForClass(DailyRecord);

export interface DailyRecordType extends Pick<DocumentType<DailyRecord>, keyof DailyRecord>{};
