import { Application, BackendSession, HandlerService, } from 'pinus';
import { EventRecordModel } from '../../../db/EventRecord';
import { RoleModel } from '../../../db/Role';
import { EVENT_STATUS, EVENT_RECORD_STATUS, EVENT_ANSWER_STATUS, TASK_TYPE, DEBUG_MAGIC_WORD, ITEM_CHANGE_REASON, EVENT_TYPE, EVENT_QUIZ_NUM } from '../../../consts';
import { checkEventStatus, getEventSuccessStatus, getEvent, checkQuiz, startEvent, refreshEvent, getEventTime, randomPosition, randomQuestion } from '../../../services/eventSercive';
import { addItems } from '../../../services/role/rewardService';
import { STATUS } from '../../../consts/statusCode';
import { genCode, resResult } from '../../../pubUtils/util';
import { checkTask } from '../../../services/task/taskService';
import { gameData } from '../../../pubUtils/data';

export default function (app: Application) {
    new HandlerService(app, {});
    return new EventBattleHandler(app);
}

export class EventBattleHandler {
    constructor(private app: Application) {
    }

    // 主动获取奇遇事件
    async getEvents(msg: {}, session: BackendSession) {
        let roleId = session.get('roleId');
        let roleName = session.get('roleName');
        let eventStatus = session.get('eventStatus');

        let event = eventStatus == EVENT_STATUS.WAITING? await startEvent(session): await getEvent(eventStatus, roleId, roleName);

        return resResult(STATUS.SUCCESS, { list: event });
    }

    // 回答问题
    async checkAnswer(msg: { eventId: number, eventCode: string, questionId: number, answer: number }, session: BackendSession) {
        const { eventId, eventCode, questionId, answer } = msg;
        let roleId = session.get('roleId');
        // let roleName = session.get('roleName');
        // let eventStatus = session.get('eventStatus');

        let event = await EventRecordModel.getEventRecordByCode(roleId, eventCode);
        if (!event) {
            return resResult(STATUS.EVENT_RECORD_NOT_FOUND);
        }
        let { status, type, eventId: dataEventId, question } = event;

        if (status != EVENT_RECORD_STATUS.WAITING) {
            return resResult(STATUS.EVENT_STATUS_ERROR);
        }
        if (dataEventId != eventId) {
            return resResult(STATUS.EVENT_WRONG_ID);
        }
        let curQuestion = question.find(cur => cur.id == questionId);
        if (!curQuestion) return resResult(STATUS.EVENT_QUESTION_NOT_FOUND);

        let { isCorrect, answerNo } = checkQuiz(questionId, answer);
        let result = await EventRecordModel.saveEventAnswer(eventCode, questionId, isCorrect ? EVENT_ANSWER_STATUS.CORRECT : EVENT_ANSWER_STATUS.WRONG);
        if (!result) {
            return resResult(STATUS.EVENT_RECORD_NOT_FOUND);
        }
        let { question: newQuestion } = result;
        let isClear = true, allCorrect = true;
        for (let { status } of newQuestion) {
            if (status) {
                if (status == EVENT_ANSWER_STATUS.WRONG) {
                    allCorrect = false;
                }
            } else {
                isClear = false; allCorrect = false;
            }
        }
        if (isClear) {
            await EventRecordModel.setStatusByCode(roleId, eventCode, allCorrect ? EVENT_RECORD_STATUS.BATTLE_SUCCESS : EVENT_RECORD_STATUS.BATTLE_FAIL);
        }

        return resResult(STATUS.SUCCESS, { eventCode, eventId, questionId, isCorrect, answerNo });
    }

    // 获取关卡列表
    async receiveEventReward(msg: { eventId: number, eventCode: string }, session: BackendSession) {
        const { eventId, eventCode } = msg;
        let roleId = session.get('roleId');
        let roleName = session.get('roleName');
        let eventStatus = session.get('eventStatus');
        let sid = session.get('sid');
        const serverId = session.get('serverId');
        

        let event = await EventRecordModel.getEventRecordByCode(roleId, eventCode);
        if (!event) {
            return resResult(STATUS.EVENT_RECORD_NOT_FOUND);
        }
        let { status, type, eventId: dataEventId, question } = event;

        let flag = checkEventStatus(type, status);
        if (!flag) {
            return resResult(STATUS.EVENT_STATUS_ERROR);
        }

        let checkResult = getEventSuccessStatus(type, status, question);
        if (checkResult.status == -1) {
            return resResult(STATUS.EVENT_QUESTION_NO_ANSWER);
        }
        let isSuccess = checkResult.isSuccess;

        if (dataEventId != eventId) {
            return resResult(STATUS.EVENT_WRONG_ID);
        }
        let dicEvent = gameData.event.get(eventId);
        if (!dicEvent) {
            return resResult(STATUS.EVENT_INFO_NOT_FOUND);
        }

        // 保存状态
        let result = await EventRecordModel.setStatusByCode(roleId, eventCode, isSuccess ? EVENT_RECORD_STATUS.SUCCESS_RECEIVED : EVENT_RECORD_STATUS.FAIL_RECEIVED);
        // 保存奖励
        let reward = isSuccess ? dicEvent.winReward : dicEvent.loseReward;
        let goods = await addItems(roleId, roleName, sid, reward, ITEM_CHANGE_REASON.EVENT_REWARD);
        if (eventStatus == EVENT_STATUS.STARTING) { // 如果是第一次开启的挑战，保存成开启状态
            await RoleModel.setEventStatus(roleId, EVENT_STATUS.OPEN);
            // 第一场时间挑战完，开始正常刷新事件，所以刷新时间也重置起来
            session.set('eventStatus', EVENT_STATUS.OPEN);
            session.push('eventStatus', () => { });
        }
        // 推送消息刷新
        // await checkEvent(session, true);
        // 任务
        await checkTask(serverId, roleId, sid, TASK_TYPE.BATTLE_EVENT, { eventType: dicEvent.eventType });
        return resResult(STATUS.SUCCESS, {
            isSuccess,
            eventCode: result.eventCode,
            eventId: result.eventId,
            status: result.status,
            goods
        });
    }

    async debugRefEvent(msg: { magicWord: string, eventId: number }, session: BackendSession) {
        const { magicWord, eventId } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        let roleId = session.get('roleId');
        let roleName = session.get('roleName');
        let now = new Date();
        let curTime = getEventTime(now); // 这次的时间节点 0-12：前一天的18 12-18：12 18-24： 18
        await EventRecordModel.updateMany({ roleId }, { $set: {status: -1} });
        let dic = gameData.event.get(eventId);
        let point = randomPosition(dic.movePointArray, [], []);
        if(!point) return resResult(STATUS.DIC_DATA_NOT_FOUND);

        let question = dic.eventType == EVENT_TYPE.QUIZ?randomQuestion(EVENT_QUIZ_NUM): undefined;
        let eventCode = genCode(8);
        await EventRecordModel.saveEventRecord(eventCode, {
            roleId, refTime: curTime, eventId: dic.eventID,
            roleName, turn: 1, type: dic.eventType, battleId: dic.warId||0, quality: dic.quality,
            status: EVENT_RECORD_STATUS.WAITING,
            point, question
        });

        return resResult(STATUS.SUCCESS);
    }
}