import BaseModel from './BaseModel';
import { getModelForClass, prop, DocumentType, modelOptions } from '@typegoose/typegoose';
import { CounterModel } from './Counter';
import { COUNTER, GIFT_GENERATE_TYPE } from '../consts';
import { SearchGiftCodeParam } from '../domain/backEndField/search';

class Rewards {
    @prop({ required: true })
    id: number;
    @prop({ required: true })
    count: number;
}

/**
  * 举报记录
**/
@modelOptions({ schemaOptions: { id: false } })
export default class GiftCode extends BaseModel {
    @prop({ required: true })
    id: number;           // 唯一id

    @prop({ required: true, default: '' })
    name: string;           // 礼包码名

    @prop({ required: true, type: Rewards, _id: false })
    goods: Rewards[];         // 奖励

    @prop({ required: true })
    beginTime: number;         // 开始时间

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

    @prop({ required: true, default: 0 })
    codeLen: number;           // 礼包码位数

    @prop({ required: false, default: '' })
    code: string;           // 指定礼包码

    @prop({ required: true, default: '' })
    remark: string;           // 备注

    @prop({ required: true, default: 0, enum: GIFT_GENERATE_TYPE })
    generateType: GIFT_GENERATE_TYPE;         // 生成类型

    @prop({ required: true, default: ['all'], type: String })
    channel: string[];           // 可使用渠道

    @prop({ required: true, default: 0 })
    generateCnt: number;         // 生成条数，giftCodeDetail的数量
    
    @prop({ required: true, default: 0 })
    usedNum: number;         // 使用次数

    @prop({ required: true, default: true })
    isEnable: boolean;         // 是否可以使用


    public static async findByGiftId(id: number) {
        let rec: GiftCodeType = await GiftCodeModel.findOne({ id }).lean();
        return rec;
    }

    public static async createData(values: GiftCodeParam, uid = 1) {
        let id = await CounterModel.getNewCounter(COUNTER.GIFT_CODE);
        let doc = new GiftCodeModel();
        let obj = doc.toJSON();
        let update = Object.assign(obj, values, { id });

        let rec: GiftCodeType = await GiftCodeModel.findOneAndUpdate({ id }, { $set: { updatedBy: uid}, $setOnInsert: { ...update, createdBy: uid } },
            { new: true, upsert: true }).lean(true);
        return rec;
    }

    public static async updateData(id: number, values: GiftCodeParam, uid = 1) {

        let rec: GiftCodeType = await GiftCodeModel.findOneAndUpdate({ id }, { $set: {...values, updatedBy: uid} },
            { new: true }).lean(true);
        return rec;
    }

    public static async increaseUsedNum(id: number) {
        let result: GiftCodeType = await GiftCodeModel.findOneAndUpdate({ id }, { $inc: { usedNum: 1 } }, { new: true }).lean();
        return result;
    }

    public static async increateGenerateNum(id: number, count: number) {
        let result: GiftCodeType = await GiftCodeModel.findOneAndUpdate({ id }, { $inc: { generateCnt: count } }, { new: true }).lean();
        return result;
    }

    private static getSearchObj(form: SearchGiftCodeParam) {
        let searchObj = {};
        if(form.id) searchObj['id'] = form.id;
        if (form.name != undefined) searchObj['name'] = { $regex: new RegExp(form.name.toString(), 'i') };
        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, sortField: string, sortOrder: string, form:SearchGiftCodeParam = {}) {

        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: GiftCodeType[] = await GiftCodeModel.find(searchObj, { _id: 0 }).limit(pageSize).skip((page - 1) * pageSize).sort(sort).lean({ getters: true, virtuals: true });
        return result;

    }

    public static async countByCondition(form: SearchGiftCodeParam = {}) {

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

export let GiftCodeModel = getModelForClass(GiftCode);
export interface GiftCodeType extends Pick<DocumentType<GiftCode>, keyof GiftCode> { }
export type GiftCodeParam = Partial<GiftCodeType>;
