import { Service } from 'egg';
import { STATUS, ACTIVITY_TYPE } from '@consts';
import { ActivityModel } 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';

/**
 * 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(), endTime: cur.endTime.getTime(), 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);
                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(taskType: number, activityId: number) {
        const { ctx } = this;
        let dicTask = gameData.tasks.get(taskType);
        if(!dicTask) return ctx.service.utils.resResult(STATUS.WRONG_PARMS);

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

    public async updateActivityTaskPoint(taskType: number, taskId: number, activityId: number, point: number) {
        const { ctx } = this;
        let result = await ActivityTaskPointModel.updateData(taskType, taskId, activityId, 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);
    }
}
