import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType, modelOptions } from '@typegoose/typegoose';
import { GachaResultIndb } from '../domain/activityField/gachaField';
import { genCode } from '../pubUtils/util';
import { SearchGachaLogParam } from '../domain/backEndField/search';

/**
  * 玩家抽卡表
**/
@modelOptions({ schemaOptions: { id: false } })
@index({ code: 1 })

export default class UserGachaRec extends BaseModel {

    @prop({ required: true })
    code: string;					// 玩家id

    @prop({ required: true })
    roleId: string;					// 玩家id

    @prop({ required: true })
    gachaId: number;			    // 抽卡id 1-元宝 2-友情 3-指定 4-限时

    @prop({ required: true, default: 0 })
    activityId: number;			        // 限时抽卡对应活动id

    @prop({ required: true, default: 0 })
    count: number;			      // 抽卡次数

    @prop({ required: true, type: GachaResultIndb, default: [], _id: false })
    result: GachaResultIndb[];             // 结果

    public static async createRec(roleId: string, gachaId: number, activityId: number, count: number, result: GachaResultIndb[]) {
        let code = genCode(8);
        const rec = await UserGachaRecModel.findOneAndUpdate({ code }, { $set: { roleId, gachaId, activityId, count, result } }, { new: true, upsert: true });
        return rec;
    }

    private static getSearchObj(form: SearchGachaLogParam) {
      let searchObj = {};
      if (form.roleId) searchObj['roleId'] = form.roleId;
      if (form.gachaId) searchObj['gachaId'] = form.gachaId;
      if (form.count) searchObj['count'] = form.count;
      if (form.hid) searchObj['result.hid'] = form.hid;
      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: SearchGachaLogParam = {}) {
      let searchObj = UserGachaRecModel.getSearchObj(form);
      const result: UserGachaRecType[] = await UserGachaRecModel.find(searchObj).limit(pageSize).skip((page - 1) * pageSize).sort({ createdAt: -1 }).select('-_id').lean({ getters: true, virtuals: true });
      return result;
    }
}

export const UserGachaRecModel = getModelForClass(UserGachaRec);

export interface UserGachaRecType extends Pick<DocumentType<UserGachaRec>, keyof UserGachaRec> { }
export type UserGachaRecParam = Partial<UserGachaRecType>;