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

class Reward {
  @prop({ required: true })
  point: number;
  @prop({ required: true, type: ItemReward, default: [] })
  reward: ItemReward[];
  @prop({ required: true })
  received: boolean;
  @prop({ required: true })
  recTime: Date;
}
/**
  * 远征记录
  */
@index({ roleId: 1 })

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

    @prop({ required: true, default: 0 })
    pointCost: number;					 // 消耗点数
    @prop({ required: true, default: false })
    completed: boolean;					 // 本轮奖励是否完成
    @prop({ required: true, type: Reward, default: [] })
    rewards: Reward[];                     // 领取记录

    public static async getExpeditionPoint(roleId: string, lean = true) {
        const result: ExpeditionPointType = await ExpeditionPointModel.findOne({ roleId, completed: false }).lean(lean);
        return result;
    }

    public static async updatePointStatus(roleId: string, point: number, reward: ItemReward[], lean = true) {
      const result: ExpeditionPointType = await ExpeditionPointModel.findOneAndUpdate(
        { roleId, completed: false },
        { $set: { pointCost: point }, $push: {rewards:{point, reward, received: true, recTime: new Date()}}},
        { new: true, upsert: true }
      ).lean(lean);
      return result;
    }

    public static async completeStatus(roleId: string, lean = true) {
      const result: ExpeditionPointType = await ExpeditionPointModel.findOneAndUpdate(
        { roleId, completed: false },
        { $set: {completed: true } }
      ).lean(lean);
      return result;
    }

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

export const ExpeditionPointModel = getModelForClass(ExpeditionPoint);

export interface ExpeditionPointType extends Pick<DocumentType<ExpeditionPoint>, keyof ExpeditionPoint>{};