import { Application, BackendSession, HandlerService, } from "pinus";
import { STATUS, CONSUME_TYPE, DEBUG_MAGIC_WORD, GIFT_GENERATE_TYPE, ITEM_CHANGE_REASON } from "../../../consts";
import { RewardInter } from "../../../pubUtils/interface";

import { resResult } from "../../../pubUtils/util";
import { addItems, handleCost } from "../../../services/role/rewardService";
import { RoleModel } from "../../../db/Role";
import { gameData } from "../../../pubUtils/data";
import { ITID } from "../../../consts/constModules/itemConst";
import { useGiftPackage } from "../../../services/activity/giftPackageService";
import { getAp, setAp, setApBuyTimes } from "../../../services/actionPointService";
import { ActionPointModel } from "../../../db/ActionPoint";
import { GiftCodeDetailModel } from "../../../db/GiftCodeDetail";
import { GiftCodeType, GiftCodeModel } from "../../../db/GiftCode";
import { nowSeconds } from "../../../pubUtils/timeUtil";
import { AP } from "../../../pubUtils/dicParam";
import { GiftPackageFloorModel } from "../../../db/GiftPackageFloor";

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

export class ItemHandler {

    constructor(private app: Application) {
    }


    // 道具的使用
    public async useItem(msg: { id: number, selected: Array<number>, count: number }, session: BackendSession) {
        let { id, selected, count } = msg;
        const roleId = session.get('roleId');
        const serverId = session.get('serverId');
        const sid = session.get('sid');
        const roleName = session.get('roleName');
        const guildCode = session.get('guildCode');
        
            let consumeResult = await handleCost(roleId, sid, [{ id: id, count: count }], ITEM_CHANGE_REASON.USE_GIFT_PACKAGE);
            if (!consumeResult) return resResult(STATUS.ACTIVITY_RES_NOT_ENOUGH);

            let dicGoods = gameData.goods.get(id);
            if (!dicGoods) {
                return resResult(STATUS.ACTIVITY_DATA_ERROR);
            }
            let dicItid = ITID.get(dicGoods.itid);
            if (!dicItid) return resResult(STATUS.DIC_DATA_NOT_FOUND);
            if (dicItid.type != CONSUME_TYPE.GIFT_PACKAGE) {
                return resResult(STATUS.NOT_CONSUME_GOODS);
            }
            let giftID = dicGoods.gift;
            if (!giftID) {
                return resResult(STATUS.NOT_GIFTPACKAGE);
            }
            let result = await useGiftPackage(roleId, roleName, sid, serverId, guildCode, giftID, selected, count);
            return result;

    }

    // 获取礼包保底情况
    public async getGiftPackageFloor(msg: { id: number }, session: BackendSession) {
        let { id } = msg;
        const roleId = session.get('roleId');
        let dicGoods = gameData.goods.get(id);
        if (!dicGoods) {
            return resResult(STATUS.ACTIVITY_DATA_ERROR);
        }
        let dicItid = ITID.get(dicGoods.itid);
        if (!dicItid) return resResult(STATUS.DIC_DATA_NOT_FOUND);
        if (dicItid.type != CONSUME_TYPE.GIFT_PACKAGE) {
            return resResult(STATUS.NOT_CONSUME_GOODS);
        }
        let giftID = dicGoods.gift;
        if (!giftID) {
            return resResult(STATUS.NOT_GIFTPACKAGE);
        }
        let giftPackageData = gameData.giftPackage.get(giftID);
        if (!giftPackageData) {
            return resResult(STATUS.NOT_GIFTPACKAGE);
        }
        let result = await GiftPackageFloorModel.findByGiftPackageId(roleId, giftPackageData.id, 'floors giftPackageId');
        return resResult(STATUS.SUCCESS, result);
    }

    // 使用体力道具
    public async useApItem(msg: { id: number, count: number }, session: BackendSession) {
        let { id, count } = msg;
        const roleId = session.get('roleId');
        const sid = session.get('sid');
        const ip = session.get('ip');
        const serverId = session.get('serverId');

            let dicGoods = gameData.goods.get(id);
            if (!dicGoods) {
                return resResult(STATUS.DIC_DATA_NOT_FOUND);
            }
            let dicItid = ITID.get(dicGoods.itid);
            if (!dicItid) return resResult(STATUS.DIC_DATA_NOT_FOUND);
            if (dicItid.type != CONSUME_TYPE.AP) {
                return resResult(STATUS.ROLE_METERIAL_ERROR);
            }

            let role = await RoleModel.findByRoleId(roleId, 'lv');
            let { ap, isOver } = await getAp(roleId, ip, role.lv);
            if (isOver) return resResult(STATUS.AP_IS_FULL);

            if(ap + dicGoods.value * count > AP.AP_SAVE_MAX) {
                return resResult(STATUS.AP_IS_FULL);
            }

            let consumeResult = await handleCost(roleId, sid, [{ id: id, count: count }], ITEM_CHANGE_REASON.USE_MEAT);
            if (!consumeResult) return resResult(STATUS.BATTLE_CONSUMES_NOT_ENOUGH);

            let apJson = await setAp(serverId, roleId, ip, role.lv, dicGoods.value * count, sid, ITEM_CHANGE_REASON.USE_MEAT);

            return resResult(STATUS.SUCCESS, {
                apJson
            });
    }

    // 购买体力道具
    public async buyApItem(msg: { id: number, count: number }, session: BackendSession) {
        let { id, count } = msg;
        const roleId: string = session.get('roleId');
        const roleName: string = session.get('roleName');
        const sid: string = session.get('sid');
        const ip: string = session.get('ip');

        if (count <= 0) return resResult(STATUS.WRONG_PARMS);

        let dicGoods = gameData.goods.get(id);
        if (!dicGoods) {
            return resResult(STATUS.DIC_DATA_NOT_FOUND);
        }
        let dicItid = ITID.get(dicGoods.itid);
        if (!dicItid) return resResult(STATUS.DIC_DATA_NOT_FOUND);
        if (dicItid.type != CONSUME_TYPE.AP) {
            return resResult(STATUS.ROLE_METERIAL_ERROR);
        }

        let role = await RoleModel.findByRoleId(roleId, 'lv');
        let { buyTimes = 0 } = await getAp(roleId, ip, role.lv);
        if (buyTimes + count > gameData.apMaxBuyTimes.max) return resResult(STATUS.AP_BUY_TIMES_LACK);

        let cost: RewardInter[] = [];
        for (let i = 0; i < count; i++) {
            let curCost = gameData.apBuy.get(++buyTimes);
            if (curCost) cost = cost.concat(curCost);
        }

        let consumeResult = await handleCost(roleId, sid, cost, ITEM_CHANGE_REASON.BUY_MEAT);
        if (!consumeResult) return resResult(STATUS.BATTLE_CONSUMES_NOT_ENOUGH);

        let goods = await addItems(roleId, roleName, sid, [{ id, count }], ITEM_CHANGE_REASON.BUY_MEAT);
        let apJson = await setApBuyTimes(roleId, ip, role.lv, sid, count);

        return resResult(STATUS.SUCCESS, {
            goods, apJson
        });
    }

    // 兑换礼包码
    public async useGiftCode(msg: { code: string }, session: BackendSession) {
        const roleId: string = session.get('roleId');
        const roleName: string = session.get('roleName');
        const serverId: number = session.get('serverId');
        const sid: string = session.get('sid');
        const channel: string = session.get('channel');
        const { code } = msg;

        let giftCodeDetail = await GiftCodeDetailModel.findByCode(code);
        if(!giftCodeDetail) {
            return resResult(STATUS.GIFT_CODE_NOT_FOUND);
        }
        let giftCode = await GiftCodeModel.findByGiftId(giftCodeDetail.giftId);
        if(!giftCode) {
            return resResult(STATUS.GIFT_CODE_NOT_FOUND);
        }
        if(giftCode.generateType == GIFT_GENERATE_TYPE.ONE_TO_ONE) { // 一人一条，单条不能被多人使用
            if(giftCodeDetail.usedNum > 0) return resResult(STATUS.GIFT_CODE_USED_NUM_MAX);
        }
        if(!giftCode.isEnable) return resResult(STATUS.GIFT_CODE_HAS_EXPIRED);
        if (giftCode.beginTime > nowSeconds()) return resResult(STATUS.GIFT_CODE_NOT_START);
        if (giftCode.endTime < nowSeconds()) return resResult(STATUS.GIFT_CODE_HAS_EXPIRED);

        if(giftCode.channel.indexOf('all') == -1 && giftCode.channel.indexOf(channel) == -1) {
            return resResult(STATUS.GIFT_CODE_CHANNEL_ERR);
        }

        if (giftCodeDetail.roleIds.indexOf(roleId) != -1) {
            return resResult(STATUS.YOU_HAVE_USED_THIS_CODE);
        }

        let checkHasUse = await GiftCodeDetailModel.checkHasUsed(roleId, giftCodeDetail.giftId)
        if(checkHasUse) {
            return resResult(STATUS.YOU_HAVE_USED_THIS_CODE);
        }
        

        await GiftCodeDetailModel.increaseUsedNum(code, roleId, roleName, serverId);
        await GiftCodeModel.increaseUsedNum(giftCode.id);

        let goods = await addItems(roleId, roleName, sid, giftCode.goods, ITEM_CHANGE_REASON.USE_GIFT_CODE);
        return resResult(STATUS.SUCCESS, { goods });
    }

    public async getAp(msg: {}, session: BackendSession) {
        let roleId = session.get('roleId');
        let ip = session.get('ip');

        let role = await RoleModel.findByRoleId(roleId, 'lv');
        let apJson = await getAp(roleId, ip, role.lv);
        return resResult(STATUS.SUCCESS, { apJson });
    }

    public async getApByLv(msg: { lv: number }, session: BackendSession) {
        const { lv } = msg;
        let roleId = session.get('roleId');
        let ip = session.get('ip');

        let { lvRecords = [] } = await ActionPointModel.getAp(roleId);
        let lvRecord = lvRecords.find(cur => cur.lv == lv);
        let ap = 0, apBefore = 0;
        if(!lvRecord) {
            let role = await RoleModel.findByRoleId(roleId, 'lv');
            let apJson = await getAp(roleId, ip, role.lv);
            ap = apJson.ap;
            apBefore = apJson.ap;
        } else {
            ({ ap, apBefore } = lvRecord);
        }
        return resResult(STATUS.SUCCESS, { ap, apBefore });
    }


    public async debugIncAp(msg: { magicWord: string, ap: number }, session: BackendSession) {
        const { magicWord } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }

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

        let role = await RoleModel.findByRoleId(roleId, 'lv');
        let apJson = await setAp(serverId, roleId, ip, role.lv, msg.ap, sid, ITEM_CHANGE_REASON.DEBUG);
        if (!apJson) return resResult(STATUS.BATTLE_ACTION_POINT_LACK)
        return resResult(STATUS.SUCCESS, { apJson });
    }

    public async debugResetBuyTimes(msg: { magicWord: string }, session: BackendSession) {
        const { magicWord } = msg;
        if (magicWord !== DEBUG_MAGIC_WORD) {
            return resResult(STATUS.TOKEN_ERR);
        }
        let roleId = session.get('roleId');
        let ip = session.get('ip');
        let role = await RoleModel.findByRoleId(roleId, 'lv');
        await ActionPointModel.resetBuyTimes(roleId);
        let apJson = await getAp(roleId, ip, role.lv);
        return resResult(STATUS.SUCCESS, { apJson });
    }
}