/**
 * 邮件的模板，在GM后台能看到的邮件列表
 */
import BaseModel from './BaseModel';
import { getModelForClass, prop, DocumentType } from '@typegoose/typegoose';
import { nowSeconds } from '../pubUtils/timeUtil';

class Reward {
    @prop({ required: true })
    id: number;
    @prop({ required: true })
    count: number;
}

export default class GMMail extends BaseModel {

    @prop({ required: true, type: Reward, default: [], _id: false })
    goods: Reward[];

    @prop({ required: true, default: true })
    useTempTime: boolean;          // 生成邮件是否按照模板时间

    @prop({ required: false})
    continueHour: number;           // 如果不按模板时间，sendTime为生成单独邮件的时候，endTime为sendTime+continueHour，单位小时

    @prop({ required: true })
    sendTime: number;               // 如果按照模板时间，发送时间，10位时间戳

    @prop({ required: true })
    endTime: number;                // 如果按照模板时间，过期时间，10位时间戳

    @prop({ required: true })
    content: string;
    
    @prop({ required: true })
    sendName: string;

    public static async addMail(params: GMMailTypeParam, uid = 1) {
        const doc = new GMMailModel();
        let mail = Object.assign(doc.toJSON(), params);
        let result: GMMailType = await GMMailModel.findOneAndUpdate({ _id: mail._id }, { $set: {...mail, updatedBy: uid}, $setOnInsert: { createdBy: uid } }, {upsert: true, new: true}).lean();
        return result;
    }

    public static async updateMailById(_id: string, params: GMMailTypeParam, uid: number = 1) {
        let mail: GMMailType = await GMMailModel.findByIdAndUpdate(_id, { $set: {...params, updatedBy: uid}}, {new: true}).lean();
        return mail;
    }

    public static async getGmMailById(_id: string, lean = true) {
        const result: GMMailType = await GMMailModel.findOne({ _id }).lean(lean);
        return result;
    }

    public static async getMail(updatedMailAt: number, lean = true) {
        const result: GMMailType[] = await GMMailModel.find({ $or: [{updatedAt: { $gte: new Date(updatedMailAt) }}, {sendTime: { $lte: nowSeconds() }}], endTime: { $gte: nowSeconds()} }).lean(lean);
        return result;   
    }
    
    public static async getMails( lean = true) {
        const result: GMMailType[] = await GMMailModel.find({ endTime: { $gte: nowSeconds() }}).lean(lean);
        return result;
    }


    private static getSearchObj(form: {_id?: string, content?: string}) {
        let searchObj = {};
        if(form['_id']) searchObj['_id'] = form._id;
        if(form['content']) searchObj['context'] = { $regex: new RegExp(form.content.toString(), 'i') }
        return searchObj
      }

    public static async findByCondition(page: number, pageSize: number, sortField: string, sortOrder: string, form: {_id?: string, content?: string} = {}) {

        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: GMMailType[] = await GMMailModel.find(searchObj).limit(pageSize).skip((page - 1) * pageSize).sort(sort).lean({ getters: true, virtuals: true });
        return result;

    }

    public static async countByCondition(form: {_id?: string, content?: string} = {}) {

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


}

export const GMMailModel = getModelForClass(GMMail);

export interface GMMailType extends Pick<DocumentType<GMMail>, keyof GMMail> { };

export type GMMailTypeParam = Partial<GMMailType>; // 将所有字段变成可选项