import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType } from '@typegoose/typegoose';
import { CounterModel } from './Counter';
import { COUNTER } from '../consts';

/**
  * 开服策略
*/
@index({ id: 1 })

export default class ServerStategy extends BaseModel {
    @prop({ required: true })
    id: number;				         // 策略唯一id
    @prop({ required: true })
    name: string;				     // 策略名

    @prop({ required: true, default: false })
    isDefault: boolean;				  // 是否是自动开服默认使用的策略
    @prop({ required: true, default: 0 })
    maxPlayerCnt: number;			  // 人数上限

    @prop({ required: true, type: Number })
    activityGroupId: number[];		   // 选择活动组
    @prop({ required: true, type: Number })
    mails: number[];                   // 选择邮件模板
    @prop({ required: true, type: Number })
    marquees: number[];	               // 选择跑马灯
    @prop({ required: true, type: Number })
    notices: number[];	               // 选择公告

    public static async findBySId(id: number) {
        const result: ServerStategyType = await ServerStategyModel.findOne({ id }, { _id: 0 }).lean({ getters: true, virtuals: true });
        return result;

    }

    private static getSearchObj(form: { id?: number, name?: string, isDefault?: boolean }) {
        let searchObj = {};
        if (form.id != undefined) searchObj['id'] = form.id;
        if (form.name != undefined) searchObj['name'] = { $regex: new RegExp(form.name.toString(), 'i') };
        if (form.isDefault != undefined) searchObj['isDefault'] = form.isDefault;
        return searchObj
    }

    public static async findByCondition(page: number, pageSize: number, sortField: string, sortOrder: string, form: { id?: number, name?: string, isDefault?: boolean } = {}) {

        let searchObj = this.getSearchObj(form);
        let sort = {};
        if (sortField && sortOrder) {
            if (sortOrder == 'ascend') {
                sort[sortField] = 1;
            } else if (sortOrder == 'descend') {
                sort[sortField] = -1;
            }
        }
        const result: ServerStategyType[] = await ServerStategyModel.find(searchObj, { _id: 0 }).limit(pageSize).skip((page - 1) * pageSize).sort(sort).lean({ getters: true, virtuals: true });
        return result;

    }

    public static async countByCondition(form: { id?: number, name?: string, isDefault?: boolean } = {}) {

        let searchObj = this.getSearchObj(form);
        const result = await ServerStategyModel.count(searchObj);
        return result;
    }

    private static async unsetDefault() {
        const rec = await ServerStategyModel.updateMany({ isDefault: true }, { $set: { isDefault: false } });
        return rec;
    }

    public static async updateServerStategy(values: ServerStategyTypeParam & {id: string|number}, uid = 1) {
        let id = values.id;
        if(id == 'new') {
            id = await CounterModel.getNewCounter(COUNTER.SERVER_STATEGY);
        }
        if(values.isDefault) {
            await this.unsetDefault();
        }
        delete values.id;
        let rec: ServerStategyType = await ServerStategyModel.findOneAndUpdate({ id }, { $set: {...values, updatedBy: uid}, $setOnInsert: { createdBy: uid } },
            { new: true, upsert: true }).lean(true);
        return rec;
    }
}

export const ServerStategyModel = getModelForClass(ServerStategy);

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