import { Application, BackendSession } from "pinus";
import { gameData } from "../../../pubUtils/data";
import { parseGoodStr, resResult } from "../../../pubUtils/util";
import { STATUS, GUILD_STRUCTURE, ITID, CONSUME_TYPE, HERO_QUALITY_TYPE, HERO_GROW_MAX } from "../../../consts";
import { DicShopListModel } from "../../../db/DicShopList";
import { UserShopModel } from "../../../db/UserShop";
import { handleCost, addItems } from "../../../services/rewardService";
import { GuildModel } from "../../../db/Guild";
import { SHOP } from "../../../pubUtils/dicParam";
import { getHonourObject } from "../../../pubUtils/itemUtils";
import { HeroModel } from "../../../db/Hero";
import { getShopListById } from "../../../services/shopService";
import { RewardInter } from "../../../pubUtils/interface";

export default function(app: Application) {
    return new ShopHandler(app);
}

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

    // 获得商品列表
    async getShopList(msg: { shopId: number }, session: BackendSession) {
        let roleId = session.get('roleId');
        let { shopId } = msg;

        if(!gameData.shopList.has(shopId)) {
            return resResult(STATUS.WRONG_PARMS);
        }

        const shopItemList = await getShopListById(shopId, roleId);
        return resResult(STATUS.SUCCESS, { shopItemList });
    }

    // 购买商品
    async purchase(msg: { shopItemId: number, count: number }, session: BackendSession) {
        let roleId = session.get('roleId');
        let roleName = session.get('roleName');
        let sid = session.get('sid');
        let guildCode = session.get('guildCode');
        let serverId = session.get('serverId');

        let { shopItemId, count } = msg;

        let dicShopItem = gameData.shopItem.get(shopItemId);
        if(!dicShopItem) return resResult(STATUS.DIC_DATA_NOT_FOUND);

        if(dicShopItem.guildLvLimit) {
            let myGuild = await GuildModel.findByCode(guildCode, serverId);
            if(!myGuild) return resResult(STATUS.GUILD_LV_LIMIT);
            let { structure } = myGuild;
            let curStructure = structure.find(cur => cur.id == GUILD_STRUCTURE.STORE);
            if(!curStructure || curStructure.lv < dicShopItem.guildLvLimit) {
                return resResult(STATUS.GUILD_LV_LIMIT);
            }
        }

        let userShop = await UserShopModel.findByRoleAndItem(roleId, dicShopItem.id);
        if(dicShopItem.purchaseLimit != -1) {
            if(userShop && userShop.count + count > dicShopItem.purchaseLimit) {
                return resResult(STATUS.BUY_COUNT_OVER);
            }
        }

        // 消耗
        let cost = [{
            id: dicShopItem.money,
            count: Math.round(dicShopItem.price * count)
        }];
        let costResult = await handleCost(roleId, sid, cost);
        if(!costResult) return resResult(STATUS.BATTLE_CONSUMES_NOT_ENOUGH);

        // 次数
        userShop = await UserShopModel.purchase(roleId, roleName, dicShopItem, count);
        if(!userShop) return resResult(STATUS.BUY_COUNT_OVER);

        // 获得
        let reward = [{
            id: dicShopItem.goodid,
            count
        }];
        let goods = await addItems(roleId, roleName, sid, reward);

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

    // 将魂回收
    async recycleSoul(msg: { goodsId: number, count: number }, session: BackendSession) {
        let roleId = session.get('roleId');
        let roleName = session.get('roleName');
        let sid = session.get('sid');
        let { goodsId, count } = msg;
        if(!count || count < 0) return resResult(STATUS.WRONG_PARMS);

        let dicGoods = gameData.goods.get(goodsId);
        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.SOUL) {
            return resResult(STATUS.ITEM_NOT_SOUL);
        }

        let hero = await HeroModel.findByHidAndRole(dicGoods.hid, roleId);
        if(!hero) return resResult(STATUS.HERO_NOT_MAX);
        if(hero.colorStar != HERO_GROW_MAX.COLORSTAR) return resResult(STATUS.HERO_NOT_MAX);

        // 检查自己的数量
        let cost = [{
            id: goodsId, count
        }];
        let costResult = await handleCost(roleId, sid, cost);
        if(!costResult) return resResult(STATUS.BATTLE_CONSUMES_NOT_ENOUGH);

        let reward: RewardInter[] = [];
        switch (dicGoods.quality) {
            case HERO_QUALITY_TYPE.BLUE:
                reward = parseGoodStr(SHOP.HERO_SOUL_BULE); break;
            case HERO_QUALITY_TYPE.PURPLE:
                reward = parseGoodStr(SHOP.HERO_SOUL_PURPLE); break;
            case HERO_QUALITY_TYPE.GOLD:
                reward = parseGoodStr(SHOP.HERO_SOUL_GOLDEN); break;
        }
        // 增加货币
        let goods = await addItems(roleId, roleName, sid, reward.map(cur => { return {id: cur.id, count: cur.count * count} }));

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

    // !测试接口。 去除限购次数
    async debugClearPurchaseLimit(msg: { }, session: BackendSession) {
        let roleId = session.get('roleId');

        await UserShopModel.deleteAccount(roleId);
        return resResult(STATUS.SUCCESS);
    }
}