// 征战中原对手锁
import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType } from '@typegoose/typegoose';
import { getZeroPoint } from '../pubUtils/timeUtil';
import { GVG } from '../pubUtils/dicParam';

@index({ day: 1, groupId: 1, vestigeId: 1, rank: 1 })
export default class GVGVestigeLock extends BaseModel {

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

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

    @prop({ required: true })
    groupKey: string;         // 1-单服 2-跨服

    @prop({ required: true })
    vestigeId: number;     // 遗迹id

    @prop({ required: true })
    rank: number;     // 排名

    @prop({ required: true })
    unlockTime: number;     // 锁定到什么时候,13位时间戳

    @prop({ required: true })
    attackRoleId: string;     // 挑战玩家

    @prop({ required: true })
    defenseRoleId: string;     // 防守玩家

    public static async chooseOppLock(groupKey: string, vestigeId: number, rank: number, configId: number, attackRoleId: string, defenseRoleId: string ) {
        let day = getZeroPoint();
        await GVGVestigeLockModel.findOneAndUpdate({ day, groupKey, vestigeId, rank }, { $setOnInsert: { configId, unlockTime: 0 } }, { upsert: true });
        let result: GVGVestigeLockType = await GVGVestigeLockModel.findOneAndUpdate({ 
            day, groupKey, vestigeId, rank, unlockTime: { $lt: Date.now() } 
        }, { $set: { unlockTime: Date.now() + GVG.GVG_VESTIGE_PREPARE_COUNTDOWN * 1000, attackRoleId, defenseRoleId } }, { new: true }).lean();
        return result;
    }

    public static async checkBattleLock(groupKey: string, vestigeId: number, rank: number, attackRoleId: string) {
        let day = getZeroPoint();
        let result: GVGVestigeLockType = await GVGVestigeLockModel.findOneAndUpdate({ 
            day, groupKey, vestigeId, rank, attackRoleId, unlockTime: { $gt: Date.now() }
        }, { $set: { unlockTime: Date.now() + GVG.GVG_VESTIGE_BATTLE_COUNTDOWN * 1000 } }, { new: true }).lean();
        return result;
    }

    public static async releaseLock(groupKey: string, vestigeId: number, rank: number) {
        let day = getZeroPoint();
        let result: GVGVestigeLockType = await GVGVestigeLockModel.findOneAndUpdate({ day, groupKey, vestigeId, rank }, { $set: { unlockTime: 0 } }, { new: true }).lean();
        return result;
    }
}

export const GVGVestigeLockModel = getModelForClass(GVGVestigeLock);

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