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

/**
  * 30天目标活动-点数兑换奖励记录
*/
@index({ roleId: 1, activityId: 1 })

export default class Activity_Thirty_Days_Point_Reward extends BaseModel {
    @prop({ required: true })
    activityId: number;				// 活动Id
    @prop({ required: true })
    roleId: string;			        // 用户Id
    @prop({ required: true })
    cellIndex: number;			    // 第几个奖励
    @prop({ required: true })
    isReceive: boolean;				// 是否领取过奖励
    @prop({ required: true })
    isExpired: boolean;				// 是否过期奖励

    //添加过期记录
    public static async setExpired(activityId: number, roleId: string, cells: Array<number>) {
        let records = [];
        for (let cellIndex of cells) {
            let data = {
                activityId,
                roleId,
                cellIndex,
                isReceive: false,
                isExpired: true,
            }
            records.push(data)
        }
        await ActivityThirtyDaysPointRewardModel.insertMany(records);
    }

    //添加领取记录
    public static async addRecord(activityId: number, roleId: string, cellIndex: number, lean = true) {
        let result: ActivityThirtyDaysPointRewardModelType = await ActivityThirtyDaysPointRewardModel.findOneAndUpdate({ roleId, activityId, cellIndex },
            { $set: { isReceive: true } }, { upsert: true, new: true }).lean(lean);
        return result;
    }

    //根据活动id查询活动数据
    public static async findData(activityId: number, roleId: string, lean = true) {
        let result: ActivityThirtyDaysPointRewardModelType[] = await ActivityThirtyDaysPointRewardModel.find({ roleId, activityId }).lean(lean);
        return result;
    }

    //第几个活动数据
    public static async findDataByCellIndex(activityId: number, roleId: string, cellIndex: number, lean = true) {
        let result: ActivityThirtyDaysPointRewardModelType[] = await ActivityThirtyDaysPointRewardModel.find({ roleId, activityId, cellIndex }).lean(lean);
        return result;
    }

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

export const ActivityThirtyDaysPointRewardModel = getModelForClass(Activity_Thirty_Days_Point_Reward);

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