<template>
    <Tooltip :infos="[t('shop')]" width="8rem">
        <img class="menu-img" :src="menu_icons.shop" @click="showMenu">
    </Tooltip>

    <Dialog :title="t('shop')" v-model="showShop" top="20%" left='8%'>
        <div class="coins">
            {{ t('coins.0') }}:{{ coins }}
        </div>
        <div class="items">
            <div class="item" v-for="(v, k) in shopItems" :key="k"
                @contextmenu.prevent.stop="commit('close_equip_tip'); v && open(k, $event)"
                @mouseover="commit('show_equip_tip', { equip: v, compare: true, e: $event })"
                @mouseleave="commit('close_equip_tip')">
                <EquipIcon :equip="v" @dblclick="commit('close_equip_tip'); buyEquip(k);" />
                <span class="icons" :style="{ 'font-size': (conisOfBuy(v) > 99999 ? 0.9 : 1.1) + 'rem' }">
                    {{ conisOfBuy(v) || '' }}
                </span>
            </div>
        </div>
        <div class="footer">
            <div class="info">
                <span v-show="wait" class="timeStart">{{ t('watiTime') + shop.waitTime }}s</span>
                <br />
                <span>{{ t('refreshTimes') + shop.freeTimes }}</span>
            </div>

            <button class="button" @click="refreshForFree($event)">{{ t('freeRefresh') }}</button>
            <button class="button" @click="refreshByCoins($event)">{{ refreshCoins + t('coinsRefresh') }}</button>
        </div>
    </Dialog>

    <Dialog :show-header="false" v-model="show" :left="left" :top="top" padding="0" :z="10">
        <PopoverMenu :items="[
            { label: t('buy'), onClick: () => buyEquip(index) },
        ]" />
    </Dialog>

    <Confirm ref="confirm" :tip="t('refreshTip')" :confirm="t('refreshConfirm')" :cancel="t('refreshCancel')"
        @confirm="confirmFlag = false; confirmRefresh()" />

</template>

<script lang="ts" setup>
import { useStore } from "vuex";
import { onBeforeUnmount, onMounted, ref, computed } from "vue";
import { useI18n } from "vue3-i18n";
import { Tooltip, EquipIcon, Dialog, PopoverMenu, Confirm } from "@/components"
import { randomEquipQuality } from '@/tool';
import { menu_icons, qualitys } from '@/config';
import { usePopoverMenu, conisOfBuy, getArrayEmptyIdx } from "@/tool";

const { t } = useI18n();
const { state, commit, dispatch } = useStore();
const showShop = computed(() => {
    return state.curMenu == 'shop';
});
const shopItems = computed(() => {
    return state.shop.item;
});
const itemNum = 5;
const wait = ref(false);
const shop = computed(() => {
    return state.shop;
});
const coins = computed(() => { return state.playerAttribute.coins });
const refreshCoins = 10000;
const menu = usePopoverMenu();
const { show, top, left, index, open, close } = menu;

const confirm = ref();
const confirmFlag = ref(true);
let confirmRefresh;
let interval = 0;

const refreshItems = () => {
    const items = new Array(itemNum);
    for (let i = 0; i < itemNum; i++) {
        items[i] = randomEquipQuality(state.playerAttribute.lv);
        if (items[i].quality.quality == qualitys[4]) {
            confirmFlag.value = true;
        }
    }
    const shop = state.shop;
    shop.item = items;
    commit('set_shop', shop);
}

const checkConfirm = () => {
    for (let i = 0; i < itemNum; i++) {
        const item = shop.value.item[i]
        if (item && item.quality.quality == qualitys[4]) {
            return true;
        }
    }
}

const refreshByCoins = (e) => {
    if (confirmFlag.value) {
        if (e && checkConfirm()) {
            confirm.value.open(0, e);
            confirmRefresh = refreshByCoins;
            return;
        }
    }
    if (!coins.value || coins.value < refreshCoins) {
        commit("set_sys_info", { msg: t('noCoinsRefresh'), type: "warning", });
    } else {
        refreshItems();
        confirmFlag.value = true;
        commit('add_player_coins', refreshCoins * -1);
    }

}
const refreshForFree = (e) => {
    if (confirmFlag.value) {
        if (e && checkConfirm()) {
            confirm.value.open(0, e);
            confirmRefresh = refreshByCoins;
            return;
        }
    }
    if (shop.value.freeTimes > 0) {
        refreshItems();
        confirmFlag.value = true;
        shop.value.freeTimes--;
    } else {
        commit("set_sys_info", { msg: t('noRefreshTimes'), type: "warning", });
    }
}

const buyEquip = (idx) => {
    idx && (index.value = idx);
    const equip = shopItems.value[idx];
    const need = conisOfBuy(equip)
    if (need > coins.value) {
        commit("set_sys_info", { msg: t('noCoinsRefresh'), type: "warning", });
        return;
    }
    const grid = state.grid;
    const i = getArrayEmptyIdx(grid);
    if (i != -1) {
        grid[i] = equip;
        commit("add_player_coins", -1 * need);
        commit("set_backpack", grid);
        shopItems.value[idx] = null;
        close();
        if (equip.quality.quality == qualitys[4]) {
            confirmFlag.value = false;
        }
        return;
    }
    commit("set_sys_info", { msg: t('noSpace'), type: "warning", });
}

const showMenu = () => {
    state.curMenu = showShop.value ? null : 'shop';
}

const keydown = (e) => {
    if (e.keyCode == 83 && !e.ctrlKey) {
        showMenu();
    }
}

onMounted(() => {
    interval = setInterval(() => {
        if (shop.value.freeTimes >= 10) {
            wait.value = false;
            return;
        }
        wait.value = true;
        if (--shop.value.waitTime <= 0) {
            shop.value.freeTimes++;
            shop.value.waitTime = 60;
            if (shop.value.freeTimes >= 10) {
                wait.value = false;
            }
        }
    }, 1000)
    document.addEventListener('keydown', keydown)
    document.addEventListener('click', close)
});
onBeforeUnmount(() => {
    document.removeEventListener('keydown', keydown)
    document.removeEventListener('keydown', close)
})
</script>
<style lang="scss" scoped>
.coins {
    display: flex;
    align-items: center !important;
    justify-content: center;
    font-size: 1.1rem;
    color: #2fe20f;
}

.items {
    height: 14rem;
    padding: 4rem 2rem;
}

.item {
    float: left;
    margin: 1rem;
}

.icons {
    color: white;
    text-align: center;
}

.footer {
    height: 3.5rem;
    margin-bottom: 1.8rem;
    padding: 0 1rem;
}

.info {
    height: 100%;
    line-height: 50%rem;
    align-items: flex-start;
    flex-direction: column;
    float: left;
    color: white;
}

.button {
    margin-top: 0.5rem;
    float: right;
}

@media only screen and (max-width: 768px) {
    .coins {
        font-size: 1rem;
    }

    .items {
        height: 10rem;
        padding: 2rem 0.5rem;
    }

    .item {
        margin: 0.9rem;
    }

    .footer {
        height: 3rem;
        margin-bottom: 1rem;
        padding: 0 1rem;
        font-size: 0.8rem;
    }


    .button {
        margin-top: 0.5rem;
    }
}
</style>