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

export class ReceivedReward {
    @prop({ required: true })
    pageIndex: number;

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

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

/**
  * 30天目标活动
*/
@index({ roleId: 1, activityId: 1 })

export default class Activity_Task_Pass extends BaseModel {
    @prop({ required: true })
    serverId: number;				// 服Id

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

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

    @prop({ required: true })
    roundIndex: number;			        // 第几轮

    @prop({ required: true, type: String })
    productIDs: string[];			    // 购买记录

    @prop({ required: true, type: ReceivedReward, _id: false })
    receivedReward: ReceivedReward[];		// 领取了的奖励

    @prop({ required: true })
    spdUpCnt: number;				// 加速次数

    @prop({ required: true })
    totalPoint: number;			    // 获得总点数

    // 寻找记录
    public static async findData(serverId: number, activityId: number, roleId: string, roundIndex: number) {
        let result: ActivityTaskPassModelType = await ActivityTaskPassModel.findOne({ serverId, activityId, roleId, roundIndex }).lean();
        return result;
    }

    // 增加点数
    public static async addPoint(serverId: number, activityId: number, roleId: string, roundIndex: number, addPoint: number, spdUpCnt = 0) {
        let result: ActivityTaskPassModelType = await ActivityTaskPassModel.findOneAndUpdate({ serverId, roleId, activityId, roundIndex },
            { $inc: { totalPoint: addPoint, spdUpCnt } }, { upsert: true, new: true }).lean(true);
        return result;
    }

    //添加购买记录
    public static async buy(serverId: number, activityId: number, roleId: string, roundIndex: number, productID: string) {
        let result: ActivityTaskPassModelType = await ActivityTaskPassModel.findOneAndUpdate({ serverId, roleId, activityId, roundIndex },
            { $addToSet: { productIDs: productID } }, { upsert: true, new: true }).lean(true);
        return result;
    }

    public static async receiveItems(serverId: number, activityId: number, roleId: string, roundIndex: number, receivedReward: ReceivedReward[]) {
        // console.log(receivedReward)
        let result: ActivityTaskPassModelType = await ActivityTaskPassModel.findOneAndUpdate({ serverId, roleId, activityId, roundIndex},
            { $push: { receivedReward: { $each: receivedReward } }}, { upsert: true, new: true }).lean(true);
        return result;
    }
}

export const ActivityTaskPassModel = getModelForClass(Activity_Task_Pass);

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