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

@index({ day: 1, groupKey: 1, score: 1 })
@index({ roleId: 1 })
export default class GVGVestigeSumRank extends BaseModel {

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

    @prop({ required: true })
    day: number;           // 每天5点

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

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

    @prop({ required: true })
    groupKey: string;       // 战区id

    @prop({ required: true })
    score: number;          // 得分

    @prop({ required: true })
    rank: number;          // 最后的排名，每天22点定格

    @prop({ required: true })
    isReceived: boolean;   // 是否领取过

    public static async incScore(roleId: string, leagueCode: string, configId: number, groupKey: string, inc: number) {
        let today = getZeroPoint();
        let result: GVGVestigeSumRankType = await GVGVestigeSumRankModel.findOneAndUpdate({ 
            configId, day: today, groupKey, roleId, leagueCode
         }, { $inc: { score: inc } , $setOnInsert: { rank: 0, isReceived: false } }, { new: true, upsert: true }).lean();
        return result;
    }

    // 排行榜
    public static async findRankByGroupId(): Promise<{ _id: string, arr: { roleId: string, score: number, updatedAt: Date }[], roleIds: string[] }[]> {
        let today = getZeroPoint();
        let ranks = await GVGVestigeSumRankModel.aggregate([
            { $match: { day: today } },
            { $group: { 
                _id:  "$groupKey", 
                arr: { $push: { roleId: "$roleId", score: "$score", updatedAt: "$updatedAt", leagueCode: "$leagueCode" } }, roleIds: { $addToSet: "$roleId" }
            }},
        ]);
        return ranks;
    }

    // 用于快照玩家的得分
    public static async findAllScores() {
        let today = getZeroPoint();
        let ranks: GVGVestigeSumRankType[] = await GVGVestigeSumRankModel.aggregate([
            { $match: { day: today } },
            { $project: { roleId: 1, score: 1, leagueCode: 1 } }
        ]);
        return ranks;
    }

    public static async saveRank(groupKey: string, ranks: { rank: number, field: string }[]) {
        let today = getZeroPoint();
        await GVGVestigeSumRankModel.bulkWrite(ranks.map(({ field, rank }) => {
            return { updateOne: { filter: { day: today, groupKey, roleId: field }, update: { $set: { rank } }} }
        }));
    }

    public static async getCanReceiveRanks(configId: number, roleId: string) {
        console.log(configId, roleId)
        let result: GVGVestigeSumRankType[] = await GVGVestigeSumRankModel.find({ configId, roleId, rank: { $gt: 0 }, isReceived: false }).lean();
        return result;
    }

    public static async receiveRanks(_ids: string[]) {
        await GVGVestigeSumRankModel.updateMany({ _id: { $in: _ids } }, { $set: { isReceived: true } });
    }

    public static async getAllCanReceiveRanks(configId: number) {
        let result: GVGVestigeSumRankType[] = await GVGVestigeSumRankModel.find({ configId: { $lte: configId }, rank: { $gt: 0 }, isReceived: false }).lean();
        return result;
    }
}

export const GVGVestigeSumRankModel = getModelForClass(GVGVestigeSumRank);

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