import { Service } from 'egg';
import { STATUS, ACTIVITY_TYPE } from '@consts';
import { ActivityModel, ActivityModelType } from '@db/Activity';
import { ActivityGroupModel } from '@db/ActivityGroup';
import { SignInData } from '@domain/activityField/signInField';
import { ActivityGroupTypeModel } from '@db/ActivityGroupType';
import { ActivityTaskPointModel } from '@db/ActivityTaskPoint'; 
import { gameData } from '@pubUtils/data';
import { UpdateActivityParam } from '@domain/backEndField/params';

/**
 * Test Service
 */
export default class Activity extends Service {

    /**
     * 获得活动列表
     */
    public async getActivityList(page: number, pageSize: number, sortField: string, sortOrder: string, type: number = 0, groupId: number = 0, current: boolean = false, activityId: number = 0) {
        const { ctx } = this;
        // console.log('***', page, pageSize, type, groupId, current, activityId)
        const list = await ActivityModel.findByCondition(page, pageSize, sortField, sortOrder, type, groupId, current, activityId);
        const total = await ActivityModel.countByCondition(type, groupId, current, activityId);
        return ctx.service.utils.resResult(STATUS.SUCCESS, {
            list: list.map(cur => {
                return {
                    ...cur, beginTime: cur.beginTime?.getTime()||0, endTime: cur.endTime?.getTime()||0, 
                    multiTime: (cur.multiTime||[]).map(cur => ({ id: cur.id, beginTime: cur.beginTime?.getTime()||0, endTime: cur.endTime?.getTime()||0 })),
                    env: ctx.app.config.realEnv
                }
            }), total
        });
    }

    public async getAllActivities() {
        const { ctx } = this;
        let list = await ActivityModel.findAllActivities();
        return ctx.service.utils.resResult(STATUS.SUCCESS, { list });
    }

    public async getAllActivityGroups() {
        const { ctx } = this;
        let list = await ActivityGroupModel.findAllActivityGroups();
        return ctx.service.utils.resResult(STATUS.SUCCESS, { list });
    }

    public async getAllActivityGroupTypes() {
        const { ctx } = this;
        // console.log('***', page, pageSize, type, serverId, current, activityId)
        const list = await ActivityGroupTypeModel.findAllActivityGroupTypes();
        return ctx.service.utils.resResult(STATUS.SUCCESS, {
            list
        });
    }

    public async checkActivityEditable(activityId: number) {
        let now = new Date();
        let activity = await ActivityModel.findActivity(activityId);

        if(!activity || (activity.beginTime < now && activity.endTime > now)) {

            if(activity.type == ACTIVITY_TYPE.SIGN_IN || activity.type == ACTIVITY_TYPE.SIGN_IN_VIP) {
                // 签到活动的不显示期内也可以编辑
                let signInObj = new SignInData(activity, 0, 0);
                if(signInObj.beginTime < now.getTime() && signInObj.endTime > now.getTime() ) {
                    return this.ctx.service.utils.resResult(STATUS.GM_CAN_NOT_EDIT_ACT);
                }
            } else {
                return this.ctx.service.utils.resResult(STATUS.GM_CAN_NOT_EDIT_ACT);
            }
        }
            
        return 0
    }

    /**
     * 获得活动组列表
     */
    public async getActivityGroupList(page: number, pageSize: number, serverId: number = 0, current: boolean = false, groupId: number = 0) {
        const { ctx } = this;
        // console.log('***', page, pageSize, type, serverId, current, activityId)
        const list = await ActivityGroupModel.findByCondition(page, pageSize, serverId, current, groupId);
        const total = await ActivityGroupModel.countByCondition(serverId, current, groupId);
        return ctx.service.utils.resResult(STATUS.SUCCESS, {
            list: list.map(cur => {
                return {
                    ...cur, beginTime: cur.beginTime?.getTime(), endTime: cur.endTime?.getTime(), env: ctx.app.config.realEnv
                }
            }), total
        });
    }

    /**
     * 创建一个新组
     */
    public async createGroup() {
        const { ctx } = this;
        try {
            await ActivityGroupModel.createGroup(ctx.user?.uid);
        } catch(e) {
            return ctx.service.utils.resResult(STATUS.INTERNAL_ERR, null, (<Error>e).stack);
        }
        return ctx.service.utils.resResult(STATUS.SUCCESS)
    }

    public async deleteGroup(groupId: number) {
        const { ctx } = this;
        try {
            let group = await ActivityGroupModel.findGroupData(groupId);
            if(group) {
                if(group.serverIds.length > 0 || group.activities.length > 0) {
                    return ctx.service.utils.resResult(STATUS.GM_CAN_NOT_DEL_ACT_GROUP);
                }
                await ActivityGroupModel.deleteGroup(groupId);
            }
        } catch(e) {
            return ctx.service.utils.resResult(STATUS.INTERNAL_ERR, null, (<Error>e).stack);
        }
        return ctx.service.utils.resResult(STATUS.SUCCESS)
    }

    /**
     * 获得活动组类型列表
     */
    public async getActivityGroupTypeList(page: number, pageSize: number, sortField: string, sortOrder: string, groupType: number, groupTypeName: string) {
        const { ctx } = this;
        // console.log('***', page, pageSize, type, serverId, current, activityId)
        const list = await ActivityGroupTypeModel.findByCondition(page, pageSize, sortField, sortOrder, { groupType, groupTypeName });
        const total = await ActivityGroupTypeModel.countByCondition({ groupType, groupTypeName });
        return ctx.service.utils.resResult(STATUS.SUCCESS, {
            list, total
        });
    }
    
    public async updateActivityGroupType(groupType: number|string, groupTypeName: string, activityTypes: number[] = []) {
        const { ctx } = this;
        let result;
        if(groupType == 'new') {
            result = await ActivityGroupTypeModel.createActivityGroupType(groupTypeName, activityTypes);
        } else if (typeof groupType == 'number') {
            result = await ActivityGroupTypeModel.updateActivityGroupType(groupType, groupTypeName, activityTypes);
        }
        if(!result) return ctx.service.utils.resResult(STATUS.GM_ACTIVITY_GROUP_TYPE_NOT_FOUND);
        return ctx.service.utils.resResult(STATUS.SUCCESS);
    }
    
    public async deleteActivityGroupType(groupType: number) {
        const { ctx } = this;
        await ActivityGroupTypeModel.deleteActivityGroupType(groupType);
        return ctx.service.utils.resResult(STATUS.SUCCESS);
    }

    public async createDefaultActivityGroupType() {
        const { ctx } = this;
        await ActivityGroupTypeModel.createDefaultActivityGroupType(ctx.user?.uid);
        return ctx.service.utils.resResult(STATUS.SUCCESS);
    }

    public async getActivityTaskPoint(page: number, pageSize: number, sortField: string, sortOrder: string, form: {taskType?: number, taskId?: number, activityId?: number}) {
        const { ctx } = this;
        const list = await ActivityTaskPointModel.findByCondition(page, pageSize, sortField, sortOrder, form);
        const total = await ActivityTaskPointModel.countByCondition(form);
        return ctx.service.utils.resResult(STATUS.SUCCESS, {
            list, total
        });
    }
    
    public async createTaskToActivity(type: number, activityId: number) {
        const { ctx } = this;
        let dicTask = gameData.tasks.get(type);
        if(!dicTask) return ctx.service.utils.resResult(STATUS.WRONG_PARMS);

        let activity = await ActivityModel.findActivity(activityId);
        if(!activity) return ctx.service.utils.resResult(STATUS.ACTIVITY_MISSING);

        for(let [id, dic] of dicTask) {
            await ActivityTaskPointModel.createDataIfNotExist(type, dic.taskType, id, activityId, activity.type, dic['point']||0, ctx.user?.uid);
        }
        return ctx.service.utils.resResult(STATUS.SUCCESS);
    }

    public async updateActivityTaskPoint(type: number, taskId: number, activityId: number, activityType: number, taskType: number, point: number) {
        const { ctx } = this;
        let result = await ActivityTaskPointModel.updateData(type, taskId, activityId, activityType, taskType, point, ctx.user?.uid);
        if(!result) return ctx.service.utils.resResult(STATUS.WRONG_PARMS);
        return ctx.service.utils.resResult(STATUS.SUCCESS);
    }

    public async delActivityTaskPoint(taskType: number, taskId: number, activityId: number) {
        const { ctx } = this;

        await ActivityTaskPointModel.deleteData(taskType, taskId, activityId);
        return ctx.service.utils.resResult(STATUS.SUCCESS);
    }

    public async updateActivity(data: UpdateActivityParam) {
        const { ctx } = this;

        if(!data.checkParams()) return ctx.service.utils.resResult(STATUS.WRONG_PARMS);
        if(!data.checkTime()) return ctx.service.utils.resResult(STATUS.GM_ACTIVITY_TIME_ERR);

        let activities = await ActivityModel.findActivityByIds(data.activityIds);
        // let checkTimeResult = await checkActivityEditable(activities);
        // if(!checkTimeResult) return resResult(STATUS.GM_CAN_NOT_EDIT_ACT);
        if(data.groupId) {
            let checkGroup = await this.checkActivityGroupTypeWithId(data.groupId, activities);
            if(!checkGroup) return ctx.service.utils.resResult(STATUS.GM_ACTIVITY_NOT_FIT_GROUP_TYPE);
        }

        activities = await ActivityModel.updateActivity(data.activityIds, data, ctx.user?.uid);
        return ctx.service.utils.resResult(STATUS.SUCCESS, { aids: activities.map(cur => cur.activityId) });
    }

    public async switchActivity(aid: number, isEnable: boolean) {
        const { ctx } = this;

        let activity = await ActivityModel.findActivity(aid);
        if(!activity) return ctx.service.utils.resResult(STATUS.WRONG_PARMS);

        activity = await ActivityModel.setEnable(aid, isEnable, ctx.user?.uid);
        return ctx.service.utils.resResult(STATUS.SUCCESS, { aids: [activity.activityId]});
    }
     
    public async deleteActivity(aid: number) {
        const { ctx } = this;

        const result = await ActivityModel.deleteActivity(aid, ctx.user?.uid);
        if (!result) {
            return ctx.service.utils.resResult(STATUS.ACTIVITY_MISSING);
        }
        await ActivityGroupModel.pullByActivityIds([aid]);

        return ctx.service.utils.resResult(STATUS.SUCCESS);
    }

    public async updateActivityGroup(groupId: number, groupName: string, serverIds: number[], activityIds: number[], groupType: number) {
        const { ctx } = this;

        let groupTypeObj = await ActivityGroupTypeModel.findByGroupType(groupType);
        if(!groupTypeObj) return ctx.service.utils.resResult(STATUS.GM_ACTIVITY_GROUP_TYPE_NOT_FOUND);

        let activities = await ActivityModel.findActivityByIds(activityIds);
        let checkResult = await this.checkActivityGroupType(groupType, activities);
        if(!checkResult) return ctx.service.utils.resResult(STATUS.GM_ACTIVITY_NOT_FIT_GROUP_TYPE);

        await ActivityGroupModel.setActivitiesToGroupData(groupId, activityIds, ctx.user?.uid);
        await ActivityGroupModel.updateServerData(groupId, serverIds, ctx.user?.uid); 
        await ActivityGroupModel.updateGroup(groupId, {groupName, type: groupType}, ctx.user?.uid);
        return ctx.service.utils.resResult(STATUS.SUCCESS);
    }

    private async checkActivityGroupTypeWithId(groupId: number, activities: ActivityModelType[]) {
    
        let activityGroup = await ActivityGroupModel.findGroupData(groupId);
        if(!activityGroup) return false;
        if(activityGroup.type != 0) {
            return await this.checkActivityGroupType(activityGroup.type, activities);
        }
    
        return true
    }

    private async checkActivityGroupType(groupType: number, activities: ActivityModelType[]) {
        if(groupType != 0) {
            let activityGroupType = await ActivityGroupTypeModel.findByGroupType(groupType);
            if(!activityGroupType) return false;
            let dic = activityGroupType.activityTypes;
            for(let { type } of activities) {
                let index = dic.findIndex(cur => cur.activityType == type);
                if(index == -1) {
                    return false;
                }
            }
        }

        return true
    }
}
