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

/**
  * 购买记录
*/

export class Record {
    @prop({ required: true })
    point: number; //消耗点数
    @prop({ required: true })
    time: Date; //兑换时间
}


/**
  * 活动系统 - 通用的刷新任务（分页，可刷新，限制领取次数），点数兑换奖品记录
*/
@index({ roleId: 1, activityId: 1 })

export default class Activity_Refresh_Task_Point extends BaseModel {
    @prop({ required: true })
    serverId: number;				// 服id
    @prop({ required: true })
    activityId: number;				// 活动Id
    @prop({ required: true })
    roleId: string;			        // 用户Id
    @prop({ required: true })
    totalPoint: number;		        // 获得的总点数
    @prop({ required: true })
    records: Record[];		        // 兑换红包消耗点数记录


    //获得点数
    public static async addPoint(serverId: number, activityId: number, roleId: string, point: number) {
        let result: ActivityRefreshTaskPointModelType = await ActivityRefreshTaskPointModel.findOneAndUpdate({ serverId, roleId, activityId, },
            { $inc: { totalPoint: point } }, { upsert: true, new: true }).lean(true);
        return result;
    }

    //兑换记录
    public static async addReceiveRecord(serverId: number, activityId: number, roleId: string, point: number) {
        let result: ActivityRefreshTaskPointModelType = await ActivityRefreshTaskPointModel.findOneAndUpdate({ serverId, roleId, activityId, },
            { $push: { records: { point, time: new Date() } } }, { upsert: true, new: true }).lean(true);
        return result;
    }

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

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

export const ActivityRefreshTaskPointModel = getModelForClass(Activity_Refresh_Task_Point);

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