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

export class Floor {
  @prop({ required: true })
  id: number;            // 保底类型，对应 DicGiftPackageFloor 的 floorId
  @prop({ required: true })
  count: number;         // 抽卡次数
  @prop({ required: true })
  quality: number;       // 品质
}

/**
  * 宝箱保底
  */
@index({ roleId: 1, giftPackageId: 1, floorPlanId: 1 })

export default class GiftPackageFloor extends BaseModel {
  @prop({ required: true })
  roleId: string;					// 角色 id
  @prop({ required: true })
  giftPackageId: number;            // 礼包 id
  @prop({ required: true })
  floorPlanId: number;						// 礼包内容 id，唯一 id
  
  @prop({ required: true, default: 0 })
  getNum: number;						// 获取次数，当allNum超过配置次数重置
  @prop({ required: true, default: 0 })
  allNum: number;						// 全部次数，当超过配置次数重置
  @prop({ required: true, type: Floor, default: [], _id: false })
  floors: Floor[];           // 已抽卡次数
  @prop({ required: true, default: 0 })
  getSum: number;						// 获取道具的全部次数
  @prop({ required: true, default: 0 })
  allSum: number;						// 全部全部次数，不重置


  public static async findByPlanId(roleId: string, giftPackageId: number, floorPlanId: number, lean = true) {
    const result: GiftPackageFloorType = await GiftPackageFloorModel.findOneAndUpdate({ roleId,  giftPackageId, floorPlanId}, {}, {new: true, upsert: true}).lean(lean);
    return result;
  }

  // 根据礼包 id 查找
  public static async findByGiftPackageId(roleId: string, giftPackageId: number, select = '', lean = true) {
    const result: GiftPackageFloorType = await await GiftPackageFloorModel.findOneAndUpdate({ roleId,  giftPackageId}, {}, {new: true, upsert: true}).select(select).lean(lean);
    return result;
  }

  // 根据礼包 id 更新
  public static async updateByGiftPackageId(roleId: string, giftPackageId: number, params: {floors: Floor[], getSum: number, allSum: number}, lean = true) {
    const result: GiftPackageFloorType = await GiftPackageFloorModel.findOneAndUpdate({roleId, giftPackageId}, {$set: params}, {new: true}).lean(lean);
    return result;
  }

  public static async updateByPlanId(roleId: string, giftPackageId: number, floorPlanId: number, params: {getNum: number, allNum: number, getSum: number, allSum: number}, lean = true) {
    const result: GiftPackageFloorType = await GiftPackageFloorModel.findOneAndUpdate({roleId, giftPackageId, floorPlanId}, {$set: params}).lean(lean);
    return result;
  }

  public static async deleteAccount(roleId: string) {
    let result = await GiftPackageFloorModel.deleteMany({roleId});
    return result;
  }
}

export const GiftPackageFloorModel = getModelForClass(GiftPackageFloor);

export interface GiftPackageFloorType extends Pick<DocumentType<GiftPackageFloor>, keyof GiftPackageFloor>{}