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


/**
  * 购买记录
*/

export class BuyRecord {
    @prop({ required: true })
    pageIndex: number; //第几页
    @prop({ required: true })
    id: number; //物品id标识
    @prop({ required: true })
    time: Date; //购买时间
}


/**
  * 可购买商品
*/

export class GoodsInfo {
    @prop({ required: true })
    pageIndex: number; //第几页
    @prop({ required: true })
    id: number; //物品id标识
}

/**
  * 活动系统 - 新手限定、每日限购、每周限购
*/
@index({ roleId: 1, activityId: 1 })

export default class Activity_Refresh_Shop extends BaseModel {
    @prop({ required: true })
    activityId: number;				// 活动Id
    @prop({ required: true })
    roleId: string;			        // 用户Id
    @prop({ required: true })
    roundIndex: number;				// 第几个周期，从1开始
    @prop({ required: true })
    records: BuyRecord[];		    // 购买记录
    @prop({ required: true })
    goods: GoodsInfo[];		       // 可购买商品

    //购买领取奖励的记录
    public static async addRecord(activityId: number, roleId: string, roundIndex: number, pageIndex: number, id: number, count: number) {
        let records = [];
        for(let i = 0; i < count; i++) {
          records.push({ id, pageIndex, time: new Date() });
        }    
        let result: ActivityRefreshShopModelType = await ActivityRefreshShopModel.findOneAndUpdate({ roleId, activityId, roundIndex },
            { $push: { records: { $each: records } } }, { upsert: true, new: true }).lean(true);
        return result;
    }

    //购买领取奖励的记录
    public static async createShop(activityId: number, roleId: string, roundIndex: number, goods: GoodsInfo[]) {
        let result: ActivityRefreshShopModelType = await ActivityRefreshShopModel.findOneAndUpdate({ roleId, activityId, roundIndex },
            { $push: { goods: { $each: goods } } }, { upsert: true, new: true }).lean(true);
        return result;
    }

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

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

export const ActivityRefreshShopModel = getModelForClass(Activity_Refresh_Shop);

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