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

export class TurntableRecord {
  @prop({ required: true })
  roleName: string;

  @prop({ required: true })
  gid: number;

  @prop({ required: true })
  count: number;
}

/**
  * 幸运转盘活动 
*/
@index({ roleId: 1, activityId: 1 })

export default class Activity_Turntable_Rec extends BaseModel {

    @prop({ required: true })
    activityId: number;		    // 活动id

    @prop({ required: true })
    serverId: number;		    // 区id

    @prop({ required: true })
    roleId: string;				// 用户id

    @prop({ required: true })
    roundIndex: number;				// 循环次数

    @prop({ required: true })
    count: number;			   // 抽卡次数

    @prop({ required: true })
    greatRewardCount: number;	// 中头奖次数

    @prop({ required: true })
    todayCount: number;		  // 本日抽卡

    @prop({ required: true })
    refTodayCount: Date;		  // 本日抽卡刷新时间

    @prop({ required: true, type: TurntableRecord, _id: false })
    records: TurntableRecord[];		  // 本日抽卡刷新时间

    @prop({ required: true, type: Number })
    box: number[];		  // 宝箱已领取次数

    public static async findByActivityId(serverId: number, activityId: number, roleId: string, roundIndex: number) {
      let rec: ActivityTurntableModelType = await ActivityTurntableModel.findOne({ roleId, activityId, serverId, roundIndex }).lean();
      return rec;
    }

    public static async updateData(serverId: number, activityId: number, roleId: string, roundIndex: number, update: ActivityTurntableModelTypeParam) {
      let rec: ActivityTurntableModelType = await ActivityTurntableModel.findOneAndUpdate({ roleId, activityId, serverId, roundIndex }, { $set: update }, { upsert: true, new: true }).lean();
      return rec;
    }

    public static async refreshTodayCount(serverId: number, activityId: number, roleId: string, roundIndex: number) {
      let rec: ActivityTurntableModelType = await ActivityTurntableModel.findOneAndUpdate({ roleId, activityId, serverId, roundIndex }, {$set: { todayCount: 0, refTodayCount: new Date() }}).lean();
      return rec;
    }

    public static async receiveBox(serverId: number, activityId: number, roleId: string, roundIndex: number, boxCount: number) {
      let rec: ActivityTurntableModelType = await ActivityTurntableModel.findOneAndUpdate({ roleId, activityId, serverId, roundIndex }, {$addToSet: { box: boxCount }}, { new: true }).lean();
      return rec;
    }
}

export const ActivityTurntableModel = getModelForClass(Activity_Turntable_Rec);

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