import { LotRec, DividendRec } from './../domain/dbGeneral';
import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType, modelOptions } from '@typegoose/typegoose';
import { genCode } from '../pubUtils/util';
import { DIVIDEND_STATUS, ROLE_RECEIVE_STATUS } from '../consts';

/**
  * 分红记录表
**/
@modelOptions({ schemaOptions: { id: false } })
@index({ code: 1 })
@index({ begin: -1, guildCode: 1, serverId: 1 })
@index({ 'lots.code': 1 })
export default class Dividend extends BaseModel {
    @prop({ required: true, default: 0 })
    serverId: number; // 区服编号
    @prop({ required: true, default: '' })
    guildCode: string; // 军团编号
    @prop({ required: true, default: 0 })
    sourceType: number; // 0：初始值，1：演武；2：蛮夷入侵；3：诸侯混战；4：粮草先行
    @prop({ required: true, default: '' })
    sourceCode: string; // 来源的唯一标识，如活动编号
    @prop({ required: true, default: '' })
    code: string; // 分红记录唯一标识
    @prop({ required: true, type: LotRec, default: [], _id: false })
    lots: LotRec[];
    @prop({ required: true, default: 0 })
    totalPrice: number; // 分红总金额
    @prop({ required: true, type: DividendRec, default: [], _id: false })
    dividends: DividendRec[];
    @prop({ required: true, default: 0 })
    status: number; // 0：未开始；1：进行中；2：已结束；3：已发放
    @prop({ required: true })
    begin: Date;

    public static async createDividend(data: DividendParam) {
        const code = genCode(8);
        const docData = new DividendModel();
        const result: DividendType = await DividendModel.findOneAndUpdate({ code }, { ...docData.toJSON(), ...data, code }, { upsert: true, new: true }).select('-_id -__v -createdAt -updatedAt').lean();
        return result;
    }

    public static async findDividend(code: string) {
        const result = await DividendModel.findOne({ code }).select('-_id -__v').lean();
        return result;
    }

    public static async findWorldDividendsByBegin(serverId: number, begins: Date[]) {
        const results = await DividendModel.find({ serverId, begin: { $in: begins } }).select('-_id -__v').lean();
        return results;
    }

    public static async findGuildDividendsByBegin(guildCode: string, begins: Date[]) {
        const results = await DividendModel.find({ guildCode, begin: { $in: begins } }).select('-_id -__v').lean();
        return results;
    }

    public static async findDividendByRoleAndBegin(roleId: string, begins: Date[]) {
        const results = await DividendModel.find({ 'dividends.roleId': roleId, begin: { $in: begins } }).select('-_id -__v').lean();
        return results;
    }
    public static async findDividendsByBegin(begin: Date) {
        const results = await DividendModel.find({ begin }).select('-_id -__v').lean();
        return results;
    }

    public static async findDividendsByGuild(guildCode: string, count: number) {
        const results = await DividendModel.find({ guildCode }).limit(count).sort({ _id: -1 }).select('-_id -__v').lean();
        return results;
    }

    public static async updateDividend(code: string, update: DividendParam) {
        const result = await DividendModel.findOneAndUpdate({ code }, { ...update }, { new: true }).select('-_id -__v').lean();
        return result;
    }

    public static async updateLot(lotCode: string, gid: number, price: number, incPrice: number, max: boolean) {
        const result = await DividendModel.findOneAndUpdate({ 'lots.code': lotCode }, { 'lots.$.gid': gid, 'lots.$.price': price, 'lots.$.time': new Date(), 'lots.$.max': max, $inc: { totalPrice: incPrice} }, { new: true }).select('-_id -__v').lean();
        return result;
    }

    public static async findReadyDividend(code: string) {
        const result: DividendType = await DividendModel.findOne({ code, status: DIVIDEND_STATUS.END }).sort({ _id: -1 }).select('-_id -__v').lean();
        return result;
    }

    public static async updateReceiveStatus(code: string, roleId: string) {
        const result: DividendType = await DividendModel.findOneAndUpdate({ code, status: DIVIDEND_STATUS.END, 'dividends.roleId': roleId }, { 'dividends.$.status': ROLE_RECEIVE_STATUS.YES }, { new: true }).select('-_id -__v').lean();
        return result;
    }

    public static async updateDividendStatus(guildCode: string, sourceType: number, status: number) {
        const result: DividendType = await DividendModel.findOneAndUpdate({ guildCode, sourceType }, { status }, { new: true }).select('-_id -__v').lean();
        return result;
    }

    public static async updateDividendsStatus(begin: Date, status: number) {
        await DividendModel.updateMany({ begin }, { status });
        const result: DividendType[] = await DividendModel.find({ begin }).select('-_id -__v -createdAt -updatedAt').lean();
        return result
    }
}

export const DividendModel = getModelForClass(Dividend);

export interface DividendType extends Pick<DocumentType<Dividend>, keyof Dividend>{}
export type DividendParam = Partial<DividendType>;
