import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType, ReturnModelType, mongoose } from '@typegoose/typegoose';
import { gameData } from '../pubUtils/data';
import { SearchLogParam } from '../domain/backEndField/search';

/**
  * GM用户组接口
*/
@index({ uid: 1 })
@index({ api: 1 })

export default class GMRecord extends BaseModel {

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

  @prop({ required: true })
  env: string;

  @prop({ required: true })
  api: string;

  @prop({ required: true })
  apiName: string;

  @prop({ required: true })
  apiModule: string;

  @prop({ required: true })
  body: string;
   
  @prop({ required: true })
  result: string;

  public static async createRecord(uid: number, env: string, api: string, body: string, result: string) {
    let dicApi = gameData.apiByUrl.get(api);
    const r = await GMRecordModel.insertMany({uid, env, api, apiName: dicApi?.name, apiModule: dicApi?.module, body, result});
    return r;
  }
  
  private static getSearchObj(form: SearchLogParam) {
    let searchObj = {};
    if (form.env) searchObj['env'] = form.env;
    if (form.uid) searchObj['uid'] = form.uid;
    if (form.apiModule) searchObj['apiModule'] = form.apiModule;
    if (form.api) searchObj['api'] = form.api;
    if (form.createTimeStart && form.createTimeEnd) {
      searchObj['createdAt'] = { $lte: new Date(form.createTimeEnd * 1000), $gte: new Date(form.createTimeStart * 1000) };
    }
    return searchObj
  }

  public static async findByCondition(page: number, pageSize: number, form: SearchLogParam = {}) {
    let searchObj = GMRecordModel.getSearchObj(form);
    const result: GMRecordType[] = await GMRecordModel.find(searchObj).limit(pageSize).skip((page - 1) * pageSize).sort({ createdAt: -1 }).select('-_id').lean({ getters: true, virtuals: true });
    return result;

  }
}

export let GMRecordModel: ReturnModelType<typeof GMRecord, {}>;
export function loadGMRecordModel(connect: mongoose.Connection) {
  GMRecordModel = getModelForClass(GMRecord, {
        existingConnection: connect
    });
}

export interface GMRecordType extends Pick<DocumentType<GMRecord>, keyof GMRecord>{};