import { Application, ChannelService, BackendSession, HandlerService, } from "pinus";
import { GUILD_ACTIVITY_TYPE, STATUS, GUILD_ACTIVITY_STATUS, GUILD_POINT_WAYS, REDIS_KEY, TASK_TYPE } from "../../../consts";
import { resResult } from "../../../pubUtils/util";
import { getGuildActivityStatus, getRaceActivityObj, getRaceActivityRank, getWoodenHorseList, calWoodenHorseAndSend, raceActivitySettleReward } from "../../../services/guildActivityService";
import { UserGuildModel } from "../../../db/UserGuild";
import { GuildActivityRecordModel } from "../../../db/GuildActivityRec";
import { UserGuildActivityRecModel } from "../../../db/UserGuildActivityRec";
import { addActive } from "../../../services/guildService";
import { Rank } from "../../../services/rankService";
import { checkActivityTask, checkTask } from "../../../services/taskService";
import { guildInter } from "../../../pubUtils/interface";
import { RaceActivityObject } from "../../../services/guildActivityObjService";

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');
        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 = await getRaceActivityRank(guildCode, serverId);
        let hasJoin = obj.hasJoin(guildCode, roleId);

        return resResult(STATUS.SUCCESS, {
            ...statusResult,
            hasJoin,
            woodenHorse,
            ...ranks,
            events
        });
    }

    // 加入木马
    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 statusResult = getGuildActivityStatus(this.aid);
        if (!statusResult) return resResult(STATUS.DIC_DATA_NOT_FOUND);

        let obj = getRaceActivityObj();

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


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

        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);
        if (!woodenHorse) return resResult(STATUS.GUILD_AUTH_NOT_ENOUGH);

        let events = obj.getEvents(guildCode, woodenHorse.distance);

        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.hasJoin(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 { id, count, toGuild } = msg;
        if (!count || count < 0) return resResult(STATUS.WRONG_PARMS);
        let obj = getRaceActivityObj();
        let woodenHorse = obj.getWoodenHorse(toGuild, serverId);
        if (!woodenHorse) return resResult(STATUS.WRONG_PARMS);

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

        await GuildActivityRecordModel.pushEvent(guildCode, 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 statusResult = getGuildActivityStatus(this.aid);
        if (!statusResult) return resResult(STATUS.DIC_DATA_NOT_FOUND);

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

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

        // 返回当前军团总军功
        let r = new Rank(REDIS_KEY.RACE_ACTIVITY, { serverId });
        let myGuildRank = await r.getMyRank({ guildCode });

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

    async test(msg: { serverId: number }, session: BackendSession) {
        let guildCode = session.get('guildCode');
        let serverId = session.get('serverId');
        let obj = getRaceActivityObj();
        let woodenHorse = await obj.getWoodenHorse(guildCode, serverId);
        if (woodenHorse) {
            await raceActivitySettleReward(guildCode, woodenHorse)
        }
    }
}