import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType } from '@typegoose/typegoose';
import { getZeroPoint, nowSeconds } from '../pubUtils/timeUtil';
import { genCode } from '../pubUtils/util';
import { GUILD_BOSS_STATUS } from '../consts';

class Rank {
    @prop({ required: true })
    roleId: string;
    @prop({ required: true })
    score: number;
    @prop({ required: true })
    time: number;
    @prop({ required: true })
    job: number;
}

@index({ code: 1 })
@index({ guildCode: 1 })
export default class BossInstance extends BaseModel {
    @prop({ required: true })
    code: string;           // 这个boss本的唯一值

    @prop({ required: true })
    guildCode: string;

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

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

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

    @prop({ required: true })
    ratio: number;    // 敌军倍率

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

    @prop({ required: true, type: Rank, default:[]})
    ranks:Array<Rank>;

    @prop({ required: true, default: nowSeconds })
    startTime: number;
    
    @prop({ required: true, default: 0 })
    killTime: number;

    @prop({ required: true, default: 0 })
    encourageCnt: number;          // 鼓舞次数

    @prop({ required: true, default: GUILD_BOSS_STATUS.OPEN })
    status: GUILD_BOSS_STATUS; // 状态 1：等待团长开启，2：今日已开启，且boss通关，3：开启中

    public static async findByCode(code: string) {
        const bossInstance: BossInstanceType = await BossInstanceModel.findOne({ code }).lean();
        return bossInstance;
    }

    public static async findBossInstance(guildCode: string) {
        const bossInstance: BossInstanceType = await BossInstanceModel.findOne({ guildCode, status: GUILD_BOSS_STATUS.OPEN }).lean();
        return bossInstance;
    }

    public static async findLastOverBossInstance(guildCode: string) {
        let today = getZeroPoint();
        const bossInstance: BossInstanceType = await BossInstanceModel.findOne({ guildCode, status: GUILD_BOSS_STATUS.CLEAR, killTime: { $gt: today } }).sort({ _id: -1 }).lean();
        return bossInstance;
    }

    public static async openBossInstance(guildCode: string, bossHp: number, ratio: number, warId: number, bossLv: number) {
        let code = genCode(10);
        let doc = new BossInstanceModel();
        let update = Object.assign(doc.toJSON(), { guildCode, bossHp, bossTotalHp: bossHp, ratio, bossLv, warId });
        const bossInstance: BossInstanceType = await BossInstanceModel.findOneAndUpdate({ code },{ $set: update }, {new: true, upsert: true}).lean();
        return bossInstance;
    }

    public static async pushRecordRanks(code: string, recordRank: Rank, lean = true) {
        const bossInstance: BossInstanceType = await BossInstanceModel.findOneAndUpdate({ code }, { $push:{ recordRanks: recordRank } }, { new: true }).lean(lean);
        return bossInstance;
    }

    public static async pushRanks(code: string, rank: Rank, lean = true) {
        const bossInstance: BossInstanceType = await BossInstanceModel.findOneAndUpdate({ code }, { $push:{ ranks: rank } }, { new: true }).lean(lean);
        return bossInstance;
    }

    public static async updateBossInstance(code: string, update:BossInstanceTypeParam, lean = true) {
        const bossInstance: BossInstanceType = await BossInstanceModel.findOneAndUpdate({ code }, { $set:update }, { new: true }).lean(lean);
        return bossInstance;
    }

    public static async updateBossHp(code: string, hp: number, roleId: string) {
        let bossInstance: BossInstanceType = await BossInstanceModel.findOneAndUpdate({ code, 'ranks.roleId': roleId, bossHp: { $gt: 0 } }, { $inc: { bossHp: - hp ,'ranks.$.score': hp}, }, { new: true }).lean();
        return bossInstance;
    }

    public static async clearBoss(code: string, bossHp: number, roleId: string) {
        let bossInstance: BossInstanceType = await BossInstanceModel.findOneAndUpdate({ code, 'ranks.roleId': roleId }, { $set: { bossHp: 0, killTime: nowSeconds(), status: GUILD_BOSS_STATUS.CLEAR }, $inc: { 'ranks.$.score': bossHp}, }, { new: true }).lean();
        return bossInstance;
    }
    public static async updateRank(code: string, roleId: string, lean = true) {
        const bossInstance: BossInstanceType = await BossInstanceModel.findOneAndUpdate({ code, 'ranks.roleId': roleId }, { $set:{ 'ranks.$.time': nowSeconds() } }, { new: true }).lean(lean);
        return bossInstance;
    }
    
    public static async removeBossRank(guildCode: string, roleId: string, lean = true) {
        const guildTrain: BossInstanceType = await BossInstanceModel.findOneAndUpdate({ guildCode },
            { $pull:{ ranks: { roleId } }}, {new: true}).lean(lean);
        return guildTrain;
    }

    public static async findBySourceCode(guildCode: string, sourceCode: string) {
        const rec: BossInstanceType = await BossInstanceModel.findOne({ guildCode, code: sourceCode }).select('ranks bossLv').lean();
        return rec;
    }

    public static async encourage(code: string, count: number, maxCount: number) {
        const rec: BossInstanceType = await BossInstanceModel.findOneAndUpdate({ code, encourageCnt: { $lte: maxCount - count } }, { $inc: { encourageCnt: count } }, { new: true }).lean();
        return rec
    }
}

export const BossInstanceModel = getModelForClass(BossInstance);

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