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



export class ChallengeRecord {
    @prop({ required: true })
    count: number;		//挑战次数
    @prop({ required: true })
    time: Date;				// 开始统计时间
}
/**
  * 糜家商队活动数据
*/
@index({ roleId: 1, activityId: 1 })

export default class Activity_Self_Service extends BaseModel {
    @prop({ required: true })
    serverId: number;				// 服
    @prop({ required: true })
    activityId: number;				// 活动Id
    @prop({ required: true })
    roundIndex: number;				// 活动第几周期 从1开始，根据活动开始时间计算    
    @prop({ required: true })
    roleId: string;			        // 用户Id
    @prop({ required: true })
    unitBuyCount: number;			// 购买代币次数
    @prop({ required: true })
    challengeRecords: ChallengeRecord[];	    //挑战记录


    //添加购买代币记录
    public static async addBuyRecord(serverId: number, activityId: number, roleId: string, roundIndex: number, count: number) {
        let result: ActivitySelfServiceModelType = await ActivitySelfServiceModel.findOneAndUpdate(
            { serverId, roleId, activityId, roundIndex }, { $inc: { unitBuyCount: count } }, { upsert: true, new: true }).lean(true);
        return result;
    }

    //添加挑战记录
    public static async addChallengeRecord(serverId: number, activityId: number, roleId: string, roundIndex: number, count: number, _time: Date) {
        let result: ActivitySelfServiceModelType = await ActivitySelfServiceModel.findOneAndUpdate(
            { serverId, roleId, activityId, roundIndex, },
            { $push: { challengeRecords: { count, time: new Date() } } }, { upsert: true, new: true }).lean(true);
        return result;
    }

    //查询活动数据
    public static async findData(serverId: number, activityId: number, roleId: string, roundIndex: number) {
        let result: ActivitySelfServiceModelType = await ActivitySelfServiceModel.findOne({ serverId, roleId, activityId, roundIndex }).lean(true);
        return result;
    }

    //删除活动领取记录
    public static async deleteActivity(serverId: number, activityId: number, roleId: string, roundIndex: number, index: number,) {
        await ActivitySelfServiceModel.deleteMany({ serverId, roleId, activityId, index, roundIndex });
    }
}

export const ActivitySelfServiceModel = getModelForClass(Activity_Self_Service);

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