import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType } from '@typegoose/typegoose';
import { nowSeconds } from '../pubUtils/timeUtil';
import { RewardInter } from '../pubUtils/interface';

@index({ leagueCode: 1, roleId: 1, configId: 1, status: 1 })
export default class GVGUserItem extends BaseModel {

    @prop({ required: true })
    roleId: string;          // 玩家

    @prop({ required: true })
    leagueCode: string;        // 联军id

    @prop({ required: true })
    configId: number;          // 赛期

    @prop({ required: true })
    id: number;              // 道具： 包括 种子、铲子、斧子

    @prop({ required: true, default: 0 })
    count: number;           // 数量

    @prop({ required: true, default: 0 })
    expireTime: number;  

    public static async findByRole(configId: number, leagueCode: string, roleId: string) {
        const result: GVGUserItemType[] = await GVGUserItemModel.find({ configId, leagueCode, roleId, expireTime: { $gte: nowSeconds() }, count: { $gt: 0 } }, { _id: 0, id: 1, count: 1 }).lean();
        return result;
    }

    public static async increaseItem(configId: number, leagueCode: string, roleId: string, id: number, inc: number, expireTime: number) {
        const result: GVGUserItemType = await GVGUserItemModel.findOneAndUpdate({ configId, leagueCode, roleId, id, expireTime }, { $inc: { count: inc } }, { new: true, upsert: true }).lean();
        return result;
    }

    public static async findByRoleAndIds(configId: number, leagueCode: string, roleId: string, ids: number[]) {
        const result: GVGUserItemType[] = await GVGUserItemModel.find({ configId, leagueCode, roleId, expireTime: { $gte: nowSeconds() }, id: { $in: ids } }).select('id count').lean();
        return result;
    }

    public static async decreaseItem(configId: number, leagueCode: string, roleId: string, items: RewardInter[]) {
        const result: GVGUserItemType[] = [];
        for(let { id, count } of items) {
            let item: GVGUserItemType = await GVGUserItemModel.findOneAndUpdate({ configId, leagueCode, roleId, id, count: { $gte: count }, expireTime: { $gte: nowSeconds() } }, { $inc: { count: -1 * count } }, { new: true }).lean();
            if(item) result.push(item);
        }
        return result;
    }

    public static async checkItemCnt(configId: number, leagueCode: string, roleId: string, id: number, count: number) {
        return await GVGUserItemModel.exists({ configId, leagueCode, roleId, id, count: { $gte: count }, expireTime: { $gte: nowSeconds() } });
    }
}

export const GVGUserItemModel = getModelForClass(GVGUserItem);

export interface GVGUserItemType extends Pick<DocumentType<GVGUserItem>, keyof GVGUserItem> {
    id: number;
};
export type GVGUserItemUpdate = Partial<GVGUserItemType>; // 将所有字段变成可选项
