<template>
    <div>
        <div>
            <input v-model="itemNameInput" placeholder="输入物品名(英)"/>
            <input v-model="tNameQuery" placeholder="译名反查(!)"/>
        </div>
        <select v-if="selectOpts.length" v-model="itemSelected" @change="onSelectChange">
            <option disabled value="">{{ optDefault }}</option>
            <option v-for="item in selectOpts" :value="item">
                {{ item }}
                {{ itemNameDict[item] ? '(' + itemNameDict[item] + ')' : '' }}
            </option>
        </select>
    </div>
    <div v-if="itemInfo.id !== -1">
        <p><img :alt="itemInfo.id.toString()" :src="`/images/items/${itemInfo.id}/medium.png`"/></p>
        <p>
            物品名：{{ itemInfo.name }}{{ itemNameDict[itemInfo.name] ? '(' + itemNameDict[itemInfo.name] + ')' : '' }}
        </p>
        <p>估价 (缓存)：{{ itemInfo.price }}</p>
        <div>
            <span>实时市价 (API)：</span>
            <span v-if="apiPriceResult.status === -1">
        <button class="torn-btn" @click="(ev) => onApiPricePress(itemInfo.name, ev)">API查询</button>
      </span>
            <div v-else class="apiResults">
                <ul>
                    <li v-for="item in apiPriceResult.data">{{ moneyFormat(item.cost) }} x {{ item.quantity }}</li>
                </ul>
                <button class="torn-btn" @click="(ev) => onApiPricePress(itemInfo.name, ev)">刷新</button>
            </div>
        </div>
        <p>
            <span>昨日市值 (Value)：</span>
            <span v-if="itemInfo.value">{{ itemInfo.value }}</span>
            <span v-else>...</span>
        </p>
        <p>
        </p>
        <p>
            <a :href="'/imarket.php#/p=shop&step=shop&type=&searchname=' + String(itemInfo.name).replaceAll(' ','+')"
               class="torn-btn" target="_blank">前往市场</a>
        </p>
    </div>
    <div v-else><p>未选择或未找到</p></div>
</template>

<script lang="ts">
import ItemHelper from "../ts/class/utils/ItemHelper";
import toThousands from "../ts/func/utils/toThousands";
import FetchUtils from "../ts/class/utils/FetchUtils";
import Alert from "../ts/class/utils/Alert";
import { defineComponent } from "vue";
import BazaarApiResponse from "../ts/interface/BazaarApiResponse";
import { ItemPrice } from "../ts/interface/PriceData";
import { itemNameDict } from "../ts/dictionary/translation";
import { Container } from "../ts/container/Container";
import TornPDAUtils from "../ts/class/utils/TornPDAUtils";
import Logger from "../ts/class/Logger";

export default defineComponent({
    name: "ItemPrice",
    data() {
        return {
            itemNameInput: '',
            itemInfo: {
                id: -1,
                name: '',
                price: '',
                value: '',
            },
            // mounted加载物品名-id对应
            itemNameMap: <{ [k: string]: number }>{},
            optDefault: '加载中...',
            itemSelected: '',
            apiPriceResult: {
                status: -1,
                data: <BazaarApiResponse['bazaar']>[]
            },
            tNameQuery: '',
            itemNameTranslated: <{ translatedName: string, itemName: string }[]>[],
            selectOpts: <string[]>[],
            itemNameDict,
        };
    },
    computed: {
        // itemNameDict() {
        //   return itemNameDict
        // },
        // filteredItems() {
        //   if (!this.itemNameMap) return [];
        //   let out: string[] = [];
        //   if (this.itemNameInput) {
        //     Object.keys(this.itemNameMap).forEach(v => {
        //       v.toLowerCase().includes(this.itemNameInput.toLowerCase()) && out.push(v);
        //     })
        //   }
        //   return out;
        // }
    },
    methods: {
        async onApiPricePress(itemName, ev) {
            let fetchUtils = Container.factory(FetchUtils);
            ev.target.disabled = true;
            let res: BazaarApiResponse["bazaar"] = null;
            let apiKey = Container.factory(TornPDAUtils).isPDA() ? Container.factory(TornPDAUtils).APIKey : localStorage.getItem('APIKey');
            try {
                if (!apiKey) return new Error('无APIKEY');
                res = JSON.parse(
                    await fetchUtils
                        .fetchText(`//api.torn.com/market/${ this.itemNameMap[itemName] }?selections=bazaar&key=${ apiKey }`)
                ).bazaar.slice(0, 5);
            } catch (e) {
                Container.factory(Logger).error(e.stack || e.message || e);
                new Alert(e.message || e.toString());
                ev.target.disabled = false;
            }
            this.apiPriceResult.status = 0;
            this.apiPriceResult.data = res;
            ev.target.disabled = false;
        },
        onSelectChange() {
            let itemHelper = Container.factory(ItemHelper);
            this.apiPriceResult.status = -1;
            this.itemInfo.value = '';
            let priceData = itemHelper.getLocalPriceData();
            let update = (data: { [p: number]: ItemPrice }) => {
                this.itemInfo.name = this.itemSelected;
                this.itemInfo.price = '$' + toThousands(data[this.itemNameMap[this.itemSelected]]?.price);
                this.itemInfo.id = this.itemNameMap[this.itemSelected];
            };
            if (priceData.data) {
                update(priceData.data);
            } else {
                window.setTimeout(async () => update(await priceData.promise), 0);
            }
            itemHelper.getItemData(this.itemSelected).then((data) => {
                this.itemInfo.value = data.itemValue;
            });
        },
        moneyFormat(input) {
            return '$' + toThousands(input);
        },
    },
    mounted() {
        let itemName = Container.factory(ItemHelper).getItemNameMap();
        if (itemName.data) {
            this.itemNameMap = itemName.data;
            this.optDefault = '-';
        } else {
            window.setTimeout(async () => {
                this.itemNameMap = await itemName.promise;
                this.optDefault = '-';
            }, 0);
        }
    },
    watch: {
        tNameQuery(newVal) {
            this.selectOpts = [];
            if (this.itemNameTranslated.length === 0) {
                Object.keys(itemNameDict).forEach(iName => {
                    let tName = itemNameDict[iName];
                    if (tName) {
                        this.itemNameTranslated.push({ translatedName: tName, itemName: iName });
                    }
                });
            }
            this.itemNameTranslated.forEach(el => {
                if (el.translatedName.includes(newVal)) {
                    this.selectOpts.push(el.itemName);
                }
            });
        },
        itemNameInput(newVal) {
            // if (!newVal) return [];
            if (newVal) {
                this.selectOpts = [];
                Object.keys(this.itemNameMap).forEach(v => {
                    v.toLowerCase().includes(this.itemNameInput.toLowerCase()) && this.selectOpts.push(v);
                })
            }
        }
    }
});
</script>

<style scoped>
select {
    padding: 0.5em;
}

.apiResults {
    background: #ebebeb;
    padding: 1em;
}
</style>
