import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType, modelOptions } from '@typegoose/typegoose';
import { MARQUEE_TYPE } from '../consts';
import { genCode } from '../pubUtils/util';
/**
  * 跑马灯
**/
@modelOptions({ schemaOptions: { id: false } })
@index({ code: 1 })
export default class Marquee extends BaseModel {
  @prop({ required: true })
  code: string;                // 跑马灯唯一标识

  @prop({ required: true, type: Number })
  serverIds: number[];         // 推送服务器

  @prop({ required: true, enum: MARQUEE_TYPE })
  type: MARQUEE_TYPE;          // 推送类型

  @prop({ required: true })
  startTime: Date;             // 活动开始时间

  @prop({ required: true })
  endTime: Date;               // 活动结束时间

  @prop({ required: true })
  interval: number;            // 活动结束时间
  
  @prop({ required: true })
  content: string;             // 广播内容

  @prop({ required: true })
  isRunning: boolean;          // 当前正在发布

  /**
   * 创建跑马灯
   * @param params 参数 
   * @param uid 后台操作人
   */
  public static async createData(params: MarqueeParam, uid = 1) {
    const code = genCode(10);
    const doc = new MarqueeModel();
    const update = Object.assign(doc.toJSON(), params, { code, createdBy: uid, updatedBy: uid });
    const result: MarqueeType = await MarqueeModel.findOneAndUpdate({ code }, { $setOnInsert: update }, { new: true, upsert: true }).lean();
    return result;
  }

  /**
   * 更新跑马灯
   * @param code 唯一标识 
   * @param params 参数
   * @param uid 后台操作人
   */
  public static async updateData(code: string, params: MarqueeParam, uid = 1) {
    const result: MarqueeType = await MarqueeModel.findOneAndUpdate({ code }, { $set: {...params, updatedBy: uid }}, { new: true }).lean();
    return result;
  }


  /**
   * 根据唯一code查询一条数据
   * @param {String} code 唯一码
   */
  public static async findByCode(code: string) {
    const result: MarqueeType = await MarqueeModel.findOne({ code }).lean();
    return result;
  }

  /**
   * 查询所有生效中的跑马灯
   */
  public static async findEffectiveMarque() {
    const result: MarqueeType[] = await MarqueeModel.find({ type: MARQUEE_TYPE.SCHEDULE, startTime: { $lte: new Date() }, endTime: { $gte: new Date() } }).lean();
    return result;
  }


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

  public static async findByCondition(page: number, pageSize: number, sortField: string = 'updatedAt', sortOrder: string = 'descend', form: { type?: number, current?: boolean, 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: MarqueeType[] = await MarqueeModel.find(searchObj).limit(pageSize).skip((page - 1) * pageSize).sort(sort).select('+sort +showStartTime +showEndTime +serverType +isEnable').lean({ getters: true, virtuals: true });
    return result;

  }

  public static async countByCondition(form: { type?: number, current?: boolean, content?: string } = {}) {

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


export const MarqueeModel = getModelForClass(Marquee);

export interface MarqueeType extends Pick<DocumentType<Marquee>, keyof Marquee> {};
export type MarqueeParam = Partial<MarqueeType>;
