import BaseModel from './BaseModel';
import { index, getModelForClass, prop, DocumentType, ReturnModelType, mongoose } from '@typegoose/typegoose';
import { CounterAllModal } from './CounterAll';
import { COUNTER, ACTIVITY_TYPE } from '../consts';

/**
  * 活动合集
*/

class ActivityType {
    @prop({ required: true })
    index: number;                  // 活动集合内部id，防止activityType有重复的情况
    
    @prop({ required: true, enum: ACTIVITY_TYPE })
    activityType: ACTIVITY_TYPE;     // 活动类型
}

@index({ groupType: 1 })
export default class Activity_GroupType extends BaseModel {
    @prop({ required: true })
    groupType: number;				// 类型id，创建时自增

    @prop({ required: true })
    groupTypeName: string;          // 类型名

    @prop({ required: true, type: ActivityType, _id: false })
    activityTypes: ActivityType[];   // 活动类型集合

    public static async findByGroupType(groupType: number) {
        let result: ActivityGroupTypeInter = await ActivityGroupTypeModel.findOne({ groupType }).lean();
        return result;
    }

    public static async createDefaultActivityGroupType(uid = 1) {
        let result: ActivityGroupTypeInter = await ActivityGroupTypeModel.findOneAndUpdate({ groupType: 0 }, {
            $setOnInsert: { groupTypeName: "常规类型", activityTypes: [], createdBy: uid }, $set: { updatedBy: uid }
        }, { new: true, upsert: true }).lean();
        return result;
    }

    public static async createActivityGroupType(groupTypeName: string, types: number[], uid = 1) {
        let activityTypes = types.map((value, index) => {
            return { index: index + 1, activityType: value };
        });
        let groupType = await CounterAllModal.getNewCounter(COUNTER.ACTIVITY_GROUP_TYPE);

        let result: ActivityGroupTypeInter = await ActivityGroupTypeModel.findOneAndUpdate({ groupType }, {
            $setOnInsert: { groupTypeName, activityTypes, createdBy: uid }, $set: { updatedBy: uid }
        }, { new: true, upsert: true }).lean();
        return result;
    }

    public static async updateActivityGroupType(groupType: number, groupTypeName: string, types: number[], uid = 1) {
        let activityTypes = types.map((value, index) => {
            return { index: index + 1, activityType: value };
        });

        let result: ActivityGroupTypeInter = await ActivityGroupTypeModel.findOneAndUpdate({ groupType }, {
            $set: { groupTypeName, activityTypes, updatedBy: uid }
        }, { new: true }).lean();
        return result;
    }

    public static async deleteActivityGroupType(groupType: number) {
        let result = await ActivityGroupTypeModel.deleteMany({ groupType });
        return result;
    }

    private static getSearchObj(form: { groupType?: number, groupTypeName?: string }) {
        let searchObj = {};
        if(form.groupType != undefined) searchObj['groupType'] = form.groupType;
        if(form.groupTypeName != undefined) searchObj['groupTypeName'] = form.groupTypeName;
        return searchObj;
    }

    //查询
    public static async findByCondition(page: number, pageSize: number, sortField: string, sortOrder: string, form: { groupType?: number, groupTypeName?: string } = {}) {
        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: ActivityGroupTypeInter[] = await ActivityGroupTypeModel.find(searchObj, { _id: 0 }).limit(pageSize).skip((page - 1) * pageSize).sort(sort).lean({ getters: true, virtuals: true });
        return result;
      }
    

    // 获得活动数量
    public static async countByCondition(form: { groupType?: number, groupTypeName?: string } = {}) {
        let searchObj = this.getSearchObj(form);
        const result = await ActivityGroupTypeModel.count(searchObj);
        return result;
    }

    public static async findAllActivityGroupTypes() {
        let all: ActivityGroupTypeInter[] = [];
        let createdAt;
        for(let i = 0; i < 9999; i++) { // 防死循环
            let condition = {};
            if(createdAt) condition['createdAt'] = { $gt: createdAt }
            let cur: ActivityGroupTypeInter[] = await ActivityGroupTypeModel.find(condition).limit(1000).sort({ createdAt: 1 }).lean();
            if(cur.length == 0) break;
            createdAt = cur[cur.length - 1].createdAt;
            all.push(...cur);
        }
        return all;
    }
}

export let ActivityGroupTypeModel: ReturnModelType<typeof Activity_GroupType, {}>;
export function loadActivityGroupType(connect: mongoose.Connection) {
    ActivityGroupTypeModel = getModelForClass(Activity_GroupType, {
        existingConnection: connect
    });
}

export interface ActivityGroupTypeInter extends Pick<DocumentType<Activity_GroupType>, keyof Activity_GroupType> {
  id: number;
};
export type ActivityGroupTypeUpdate = Partial<ActivityGroupTypeInter>; // 将所有字段变成可选项
