import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType, modelOptions, Ref, mongoose } from '@typegoose/typegoose';
import GiftCode, { GiftCodeType } from './GiftCode';
import { genCode } from '../pubUtils/util';

/**
  * 举报记录
**/
@modelOptions({ schemaOptions: { id: false } })
@index({ code: 1 })
export default class GiftCodeDetail extends BaseModel {
    @prop({ required: true, default: '' })
    code: string;           // 兑换码

    @prop({ ref: 'GiftCode', type: mongoose.Schema.Types.ObjectId })
    giftCode: Ref<GiftCode>;

    @prop({ required: true, default: '' })
    usedNum: number;           // 该码使用次数


    // 根据code
    public static async findByCode(code: string) {
        let result: GiftCodeDetailType = await GiftCodeDetailModel.findOne({ code }).populate('giftCode').lean(true);
        return result;
    }

    public static async findByGiftCode(giftCode: GiftCodeType) {
        let result: GiftCodeDetailType[] = await GiftCodeDetailModel.find({ giftCode: giftCode._id }).lean();
        return result;
    }

    public static async increaseUsedNum(code: string) {
        let result: GiftCodeDetailType = await GiftCodeDetailModel.findOneAndUpdate({ code }, { $inc: { usedNum: 1 } }, { new: true }).lean();
        return result;
    }

    public static async generateOne(giftCode: GiftCodeType, code: string, uid = 1 ) {
        let result = await GiftCodeDetailModel.insertMany([{ giftCode: giftCode._id, code, usedNum: 0, createdBy: uid, updatedBy: uid }]);
        return result;
    }

    public static async generateMany(giftCode: GiftCodeType, generateNum: number, codeLen: number, uid = 1) {
        let insertArr: GiftCodeDetailParam[] = [];
        for(let i = 0; i < generateNum; i++) {
            insertArr.push({ giftCode: giftCode._id, code: genCode(codeLen), usedNum: 0, createdBy: uid, updatedBy: uid });
        }
        let result = await GiftCodeDetailModel.insertMany(insertArr);
        return result;
    }

}

export const GiftCodeDetailModel = getModelForClass(GiftCodeDetail);

export interface GiftCodeDetailType extends Pick<DocumentType<GiftCodeDetail>, keyof GiftCodeDetail> { }
export type GiftCodeDetailParam = Partial<GiftCodeDetailType>;
