import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType } from '@typegoose/typegoose';
import { ItemReward } from '../domain/dbGeneral';
import { genCode } from '../pubUtils/util';
import { Member, WoodenHorse, Event, JoinMember } from '../domain/battleField/guildActivity'


@index({ code: 1 })
@index({ guildCode: 1, aid: 1, index: 1, status: 1 })
export default class GuildActivityRecord extends BaseModel {

    @prop({ required: true })
    code: string;            // 本次记录唯一值

    @prop({ required: true })
    guildCode: string;       // 军团code

    @prop({ required: true })
    serverId: number;       // 分服

    @prop({ required: true, default: 1 })
    status: number;       // 分服

    @prop({ required: true })
    aid: number;             // 军团活动id

    @prop({ required: true })
    index: number;            // 第几次这个类型的军团活动

    @prop({ required: true })
    auctionType: number;             // 转为拍卖行的类型

    @prop({ required: true, default: false })
    isSuccess: boolean;      // 是否胜利

    @prop({ required: true, default: false })
    isCompleted: boolean;      // 是否胜利

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

    @prop({ required: true, type: Member, default: [], _id: false })
    members: Member[];        // 参与活动的团员的roleId列表
    
    @prop({ required: true, type: JoinMember, default: [], _id: false })
    joinMember: JoinMember[];        // 参与活动的团员的roleId列表

    @prop({ required: true, default: 0 })
    memberCnt: number;        // 参加的团员的数量

    @prop({ required: true, type: ()=> ItemReward, default: [], _id: false })
    rewards: ItemReward[];        // 转到拍卖行的道具

    @prop({ required: true })
    score: number;            // 蛮夷入侵总军功

    @prop({ required: true })
    remainGateHp: number;           // 城门剩余血量

    @prop({ required: true })
    challengeCityId: number;           // 诸侯混战占领了的城池

    @prop({ required: true })
    cityId: number;           // 诸侯混战占领了的城池

    @prop({ required: true })
    damage: number;           // 诸侯混战

    @prop({ required: true, _id: false })
    woodenHorse: WoodenHorse;   // 粮草先行木马

    @prop({ required: true, type: () => Event,  _id: false })
    events: Event[];   // 粮草先行木马

    // 每天一条记录
    public static async getRecord(guildCode: string, serverId: number, aid: number, index: number, events?: Event[], cityId?: number) {
        let docs = new GuildActivityRecordModel();
        let code = genCode(10);
        let insert = Object.assign(docs, { code, guildCode, serverId, aid, createdAt: new Date(), auctionType: aid + 1 });
        if(events) insert = Object.assign(insert, { events });
        let update: GuildActivityRecordUpdateParam = {};
        if(cityId) update = Object.assign(update, { challengeCityId: cityId });
        let rec: GuildActivityRecordType = await GuildActivityRecordModel.findOneAndUpdate(
            { aid, guildCode, index, status: 1}, 
            { $setOnInsert: insert, $set: update }, 
            {new: true, upsert: true}).lean();
        return rec;
    }
    
    public static async updateInfo(guildCode: string, aid: number, index: number, update: GuildActivityRecordUpdateParam) {
        let rec: GuildActivityRecordType = await GuildActivityRecordModel.findOneAndUpdate(
            { guildCode, aid, index, status: 1 }, 
            { $set: update, $setOnInsert: { code: genCode(10) } }, { new: true, upsert: true }).lean();
        return rec;
    }

    public static async pushEvent(guildCode: string, aid: number, index: number, event: Event) {
        let rec: GuildActivityRecordType = await GuildActivityRecordModel.findOneAndUpdate(
            { guildCode, index, aid, status: 1 }, 
            { $push: { events: event }, $setOnInsert: { code: genCode(10) } }, { new: true, upsert: true }).lean();
        return rec;
    }

    public static async findBySourceCode(guildCode: string, sourceType: number, sourceCode: string) {
        const rec = await GuildActivityRecordModel.findOne({ guildCode, auctionType: sourceType, code: sourceCode }).select('members aid rank challengeCityId').lean();
        return rec;
    }

    public static async join(guildCode: string, serverId: number, aid: number, index: number, member: JoinMember) {
        let rec: GuildActivityRecordType = await GuildActivityRecordModel.findOneAndUpdate(
            { guildCode, serverId, index, aid, status: 1 }, 
            { $push: { joinMember: member }, $setOnInsert: { code: genCode(10) } }, { new: true, upsert: true }).lean();
        return rec;
    }

    public static async removeMember(guildCode: string, serverId: number, aid: number, index: number, roleId: string) {
        console.log(guildCode, serverId, aid, index, roleId)
        let rec: GuildActivityRecordType = await GuildActivityRecordModel.findOneAndUpdate(
            { guildCode, serverId, index, aid }, 
            { $pull: { joinMember: { roleId } } }, { new: true }).lean();
        return rec;
    }

    public static async dismiss(guildCode: string, serverId: number, aid: number, index: number) {
        let rec: GuildActivityRecordType = await GuildActivityRecordModel.findOneAndUpdate({ guildCode, serverId, index, aid }, { $set: { status: 0 }}, { new: true }).lean();
        return rec;
    }

    public static async findRecs(aid: number, index: number) {
        let rec: GuildActivityRecordType[] = await GuildActivityRecordModel.find({  index, aid, status: 1 }).lean();
        return rec;
    }
}

export const GuildActivityRecordModel = getModelForClass(GuildActivityRecord);

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