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

class Report {
    @prop({ required: true })
    roleName: string;

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

    @prop({ required: true })
    id: number;//捐献类型id 1-铜钱 2-元宝 3-至尊捐赠
}

export default class Donation extends BaseModel {
    
    @prop({ required: true })
    guildCode: string;

    @prop({ required: true, default: 0})
    donateFund: number;
    
    @prop({ required: true, default: 0})
    hisDonateFund: number; //历史捐赠最高

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

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

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

    public static async createDonation(guildCode: string, donationLv: number, lean = true) {
        const doc = new DonationModel();
        const update = Object.assign(doc.toJSON(), {refTime: nowSeconds(), reports:[], hisDonateFund: 0, donateFund: 0, donationLv});
        const result: DonationType = await DonationModel.findOneAndUpdate({ guildCode }, {$set:update}, {upsert: true, new: true}).lean(lean);
        return result;
    }

    public static async getDonation(guildCode: string, select?: string, lean = true) {
        const result: DonationType = await DonationModel.findOne({ guildCode }).select(select).lean(lean);
        return result;
    }

    public static async donation(guildCode: string, donateFund: number, pushDate: {reports?: Report}, lean = true) {
        const result: DonationType = await DonationModel.findOneAndUpdate({ guildCode }, {$inc:{ donateFund, hisDonateFund: donateFund }, $push:pushDate}, {upsert: true, new: true}).lean(lean);
        return result;
    }

    public static async updateDonation(guildCode: string, update: DonationUpdateParam, lean = true) {
        const result: DonationType = await DonationModel.findOneAndUpdate({ guildCode }, { $set:update }, {upsert: true, new: true}).lean(lean);
        return result;
    }
}

export const DonationModel = getModelForClass(Donation);

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