import { Application, ChannelService, BackendSession, HandlerService, pinus, } from "pinus";
import { GUILD_ACTIVITY_TYPE, STATUS, GUILD_ACTIVITY_STATUS, REDIS_KEY, TASK_TYPE, PUSH_ROUTE, DEBUG_MAGIC_WORD } from "../../../consts";
import { genCode, resResult } from "../../../pubUtils/util";
import { getGuildActivityStatus, getRaceActivityObj, getWoodenHorseList, getGAIndexInPinus, getJoinIndex, leaveRaceActivity } from "../../../services/guildActivity/guildActivityService";
import { UserGuildModel } from "../../../db/UserGuild";
import { GuildActivityRecordModel } from "../../../db/GuildActivityRec";
import { UserGuildActivityRecModel } from "../../../db/UserGuildActivityRec";
import { Rank } from "../../../services/rankService";
import { checkTask } from "../../../services/task/taskService";
import { ServerRecordModel } from "../../../db/ServerRecords";
import { sendMessageToGuildWithSuc } from "../../../services/pushService";
import { RaceActivityRankParam } from "../../../domain/battleField/guildActivity";
import { GuildRankInfo } from "../../../domain/rank";
import { ServerlistModel } from "../../../db/Serverlist";
import { dispatch } from "../../../pubUtils/dispatcher";

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

export class RaceActivityHandler {

    channelService: ChannelService;
    constructor(private app: Application) {
        this.channelService = app.get('channelService');
    }

    private aid = GUILD_ACTIVITY_TYPE.RACE_ACTIVITY; // 蛮夷入侵id

    // 进入粮草先行界面
    async getRaceActivity(msg: {}, session: BackendSession) {

        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const guildCode = session.get('guildCode');
        const sid = session.get('sid');

        if (!guildCode) return resResult(STATUS.GUILD_AUTH_NOT_ENOUGH);

        let statusResult = getGuildActivityStatus(this.aid);
        if (!statusResult) return resResult(STATUS.DIC_DATA_NOT_FOUND);

        let obj = getRaceActivityObj();
        let woodenHorse = await obj.getWoodenHorse(guildCode, serverId);
        if (!woodenHorse) return resResult(STATUS.GUILD_AUTH_NOT_ENOUGH);

        let events = obj.getEvents(guildCode, woodenHorse.distance);
        let ranks: { myGuildRank?: RaceActivityRankParam, guildRank?: RaceActivityRankParam[] } = {};
        let hasJoin = await obj.updateMemberSid(guildCode, serverId, roleId, sid);

        if(obj.status == GUILD_ACTIVITY_STATUS.START) {
            ranks = await obj.getRanks(serverId, guildCode);
        } else {
            let index = getGAIndexInPinus(this.aid);
            let r = new Rank(REDIS_KEY.RACE_ACTIVITY, { serverId, index });
            r.setGenerFieldsFun(function (param: GuildRankInfo) {
                let { rank, code, name, num, num1, num2 } = param;
                return { rank, code, name, num, time: Math.floor(num1/1000), durability: num2 };
            });
            let { ranks: guildRank, myRank: myGuildRank } = await r.getRankListWithMyRank({ guildCode });
            ranks = { guildRank, myGuildRank }
        }


        return resResult(STATUS.SUCCESS, {
            ...statusResult,
            hasJoin: !!hasJoin,
            code: hasJoin?.code||'',
            woodenHorse,
            ...ranks,
            events
        });
    }

    // 离开粮草先行界面
    async leavePage(msg: {}, session: BackendSession) {

        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const guildCode = session.get('guildCode');

        await leaveRaceActivity(serverId, guildCode, roleId);

        return resResult(STATUS.SUCCESS);
    }

    // 加入木马
    async join(msg: {}, session: BackendSession) {

        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const serverId = session.get('serverId');
        const guildCode = session.get('guildCode');
        const sid = session.get('sid');
        if (!guildCode) return resResult(STATUS.GUILD_AUTH_NOT_ENOUGH);
        let joinIndex = getJoinIndex();

        let statusResult = getGuildActivityStatus(this.aid);
        if (!statusResult) return resResult(STATUS.DIC_DATA_NOT_FOUND);

        let obj = getRaceActivityObj();

        let hasJoin = !!obj.getMember(guildCode, roleId);
        if (hasJoin) {
            return resResult(STATUS.RACE_HAS_JOIN);
        }

        let guildActivityRec = await GuildActivityRecordModel.getRecord(guildCode, serverId, this.aid, joinIndex, obj.getEvents(guildCode, 0));
        if (!guildActivityRec) return resResult(STATUS.WRONG_PARMS);

        let { code: sourceCode } = guildActivityRec;
        let myGuildActivityRec = await UserGuildActivityRecModel.getRecord(roleId, roleName, guildCode, serverId, sourceCode, this.aid);

        let myGuild = await UserGuildModel.getMyGuild(roleId, 'job');
        let woodenHorse = await obj.joinWoodenHorse(guildCode, roleId, roleName, serverId, sid, myGuild.job, myGuildActivityRec.code);
        if (!woodenHorse) return resResult(STATUS.GUILD_AUTH_NOT_ENOUGH);
        await GuildActivityRecordModel.join(guildCode, serverId, this.aid, joinIndex, { roleId, roleName, job: myGuild.job, code: myGuildActivityRec.code });

        let events = obj.getEvents(guildCode, woodenHorse.distance);
        await sendMessageToGuildWithSuc(guildCode, PUSH_ROUTE.GUILD_RACE_JOIN, { timestamp: Date.now(), woodenHorse });

        // 全服活跃统计
        await ServerRecordModel.addActiveGuild(serverId, roleId, guildCode);
        // 任务
        await checkTask(serverId, roleId, sid, TASK_TYPE.GUILD_ACTIVITY, { aid: this.aid });

        return resResult(STATUS.SUCCESS, {
            code: myGuildActivityRec.code,
            ...statusResult,
            hasJoin,
            woodenHorse,
            events
        });
    }

    // 打开竞赛页面
    async getRace(msg: {}, session: BackendSession) {

        const roleId = session.get('roleId');
        const roleName = session.get('roleName');
        const serverId = session.get('serverId');
        const guildCode = session.get('guildCode');
        if (!guildCode) return resResult(STATUS.GUILD_AUTH_NOT_ENOUGH);

        let statusResult = getGuildActivityStatus(this.aid);
        if (!statusResult) return resResult(STATUS.DIC_DATA_NOT_FOUND);
        // if (statusResult.status != GUILD_ACTIVITY_STATUS.START) {
        //     return resResult(STATUS.GUILD_ACTIVITY_NOT_OPEN);
        // }

        let obj = getRaceActivityObj();
        let woodenHorse = await obj.getWoodenHorse(guildCode, serverId);
        if (!woodenHorse) return resResult(STATUS.GUILD_AUTH_NOT_ENOUGH);

        let events = obj.getEvents(guildCode, woodenHorse.distance);
        let hasJoin = !!obj.getMember(guildCode, roleId);
        let items = obj.getItem(roleId);

        let woodenHorseList = await getWoodenHorseList(guildCode, serverId);

        return resResult(STATUS.SUCCESS, {
            ...statusResult,
            hasJoin,
            woodenHorseList,
            events,
            items
        });
    }


    // 使用道具
    async useItem(msg: { id: number, count: number, toGuild: string }, session: BackendSession) {
        let roleId = session.get('roleId');
        let serverId = session.get('serverId');
        let guildCode = session.get('guildCode');
        let sid = session.get('sid');
        let joinIndex = getJoinIndex();

        let { id, count, toGuild } = msg;
        let obj = getRaceActivityObj();
        let woodenHorse = obj.getWoodenHorse(toGuild, serverId);
        if (!woodenHorse) return resResult(STATUS.WRONG_PARMS);

        let event = await obj.useItem(serverId, roleId, sid, guildCode, toGuild, id, count);
        if (!event) return resResult(STATUS.BATTLE_CONSUMES_NOT_ENOUGH);

        await GuildActivityRecordModel.pushEvent(guildCode, this.aid, joinIndex, event);

        return resResult(STATUS.SUCCESS, {
            timestamp: Date.now(),
            events: obj.getEvents(guildCode, 0)
        });
    }

    // 结束挑战
    async battleEnd(msg: { code: string, isSuccess: boolean }, session: BackendSession) {
        let guildCode = session.get('guildCode');
        let serverId = session.get('serverId');
        
        let { code, isSuccess } = msg;
        let joinIndex = getJoinIndex();

        let statusResult = getGuildActivityStatus(this.aid);
        if (!statusResult) return resResult(STATUS.DIC_DATA_NOT_FOUND);

        // 更新userGuildActivityRecord
        let guildActivityRec = await GuildActivityRecordModel.getRecord(guildCode, serverId, this.aid, joinIndex);
        let myGuildActivityRec = await UserGuildActivityRecModel.updateInfo(code, { isSuccess, isCompleted: true });
        if (!guildActivityRec || !myGuildActivityRec) return resResult(STATUS.WRONG_PARMS);

        let hasShow = !!myGuildActivityRec.hasShow;
        if(!hasShow) {
            await UserGuildActivityRecModel.updateInfo(code, { hasShow: true });
        }

        // 返回当前军团总军功
        let obj = getRaceActivityObj();
        let myGuildRank = 0;
        let woodenHorse = await obj.getWoodenHorse(guildCode, serverId);
        if(obj.status == GUILD_ACTIVITY_STATUS.START) {
            let { myGuildRank: rank, guildRank } = await obj.getRanks(serverId, guildCode);
            // console.log('#', JSON.stringify(guildRank))
            myGuildRank = rank?.rank||0;
            if(woodenHorse) {
                // console.log('########', woodenHorse.time - woodenHorse.allStartTime, rank.sortTime);
                woodenHorse = woodenHorse.getTreatTime();
            }
        } else {
            woodenHorse = guildActivityRec.woodenHorse;
            myGuildRank = guildActivityRec.rank;
        }


        return resResult(STATUS.SUCCESS, {
            timestamp: Date.now(),
            hasShow,
            woodenHorse,
            myGuildRank
        })
    }

    // 加入木马
    async debugAddHorse(msg: { magicWord: string, isMyGuild: number, memberCnt: number, itemInterval: number }, session: BackendSession) {
        const { magicWord, isMyGuild, memberCnt, itemInterval } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }

        const serverId = session.get('serverId');
        let guildCode = session.get('guildCode');
        if(!isMyGuild) {
            guildCode = genCode(8);
        }

        let statusResult = getGuildActivityStatus(this.aid);
        if (!statusResult) return resResult(STATUS.DIC_DATA_NOT_FOUND);
        if(!statusResult.isOpen) return resResult(STATUS.GUILD_ACTIVITY_NOT_OPEN);
        if(statusResult.status != GUILD_ACTIVITY_STATUS.START) return resResult(STATUS.GUILD_ACTIVITY_NOT_OPEN);

        let guild = pinus.app.getServersByType('guild');
        let sid = dispatch(`${serverId}`, guild);
        pinus.app.rpc.guild.guildActivityRemote.debugAddHorse.toServer(sid.id, serverId, guildCode, memberCnt, itemInterval)

        return resResult(STATUS.SUCCESS);
    }
}