<!--  合约 - 合约明细 -->
<template>
    <app-view class="contract-detail g-form">
        <template #header>
            <app-navbar :title="t('digital.contractdetails')" />
        </template>
        <app-block class="g-account-total" v-if="accountItem">
            <div class="g-account-total__inner">
                <div class="g-account-total__header">
                    <div class="g-account-total__title">
                        <span>
                            {{ `${t('digital.currencydecimalplace')}
                            (${getGoodsCurrencyItemName(accountItem.currencyid)})` }}
                        </span>
                        <img :src="`./img/icons/${isAmountVisible ? 'eye' : 'eye-hidden'}.svg`"
                            @click="isAmountVisible = !isAmountVisible" />
                    </div>
                    <div class="g-account-total__info" v-if="isAmountVisible">
                        <span :class="handlePriceColor(accountItem.profitLoss)">
                            {{ formatNumber(accountItem.profitLoss, accountItem.currencydecimalplace) }}
                        </span>
                        <span :class="accountItem.hazardRatioColor">
                            {{ parsePercent(accountItem.hazardRatio) }}
                        </span>
                    </div>
                </div>
                <div class="g-account-total__balance">
                    {{ getAccountAmount(accountItem.currentbalance) }}
                </div>
                <div class="g-account-total__footer">
                    <ul>
                        <li>
                            <span>
                                {{ `${t('mine.availableFunds')} (${getGoodsCurrencyItemName(accountItem.currencyid)})`
                                }}
                            </span>
                            <span>{{ getAccountAmount(accountItem.avaiableBalance) }}</span>
                        </li>
                        <li>
                            <span>
                                {{ `${t('account.usedMargin')} (${getGoodsCurrencyItemName(accountItem.currencyid)})` }}
                            </span>
                            <span>{{ getAccountAmount(accountItem.usedmargin) }}</span>
                        </li>
                        <li>
                            <span>
                                {{ `${t('account.freeze')} (${getGoodsCurrencyItemName(accountItem.currencyid)})` }}
                            </span>
                            <span>{{ getAccountAmount(accountItem.freezeMargin) }}</span>
                        </li>
                    </ul>
                </div>
            </div>
        </app-block>
        <app-grid :items="gridItems" @click="() => navigateToContractDetail()" />
        <Tabs class="g-tabs" type="card" v-model:active="activeTab" shrink>
            <Tab :title="t('digital.position')">
                <contract-position :params="{ accids: accountid.toString() }" v-if="activeTab === 0" />
            </Tab>
            <Tab :title="t('digital.order')">
                <contract-order v-bind="{ accountid }" v-if="activeTab === 1" />
            </Tab>
            <Tab :title="t('digital.trade')">
                <contract-trade v-bind="{ accountid }" v-if="activeTab === 2" />
            </Tab>
            <Tab :title="t('digital.funds')">
                <contract-statement v-bind="{ accountid }" v-if="activeTab === 3" />
            </Tab>
        </Tabs>
        <ActionSheet v-model:show="showSheet" :title="t('common.choice')">
            <CellGroup style="min-height: 200px;">
                <template v-for="(item, index) in quotes" :key="index">
                    <Cell :title="goodsname(item.goodscode)" :value="item.goodscode" :border="false" is-link clickable
                        @click="navigateToContractDetail(item.goodsid)" />
                </template>
            </CellGroup>
        </ActionSheet>
    </app-view>
</template>

<script lang="ts" setup>
import { shallowRef, computed, watch, onActivated } from 'vue'
import { Cell, CellGroup, Tab, Tabs, ActionSheet } from 'vant'
import { handlePriceColor, parsePercent, formatNumber } from '@/filters'
import { useNavigation } from '@mobile/router/navigation'
import { i18n, useAccountStore, useFuturesStore } from '@/stores'
import { GridItem } from '@/packages/digital/components/grid/types'
import AppGrid from '@/packages/digital/components/grid/index.vue'
import ContractOrder from '../components/order/index.vue'
import ContractTrade from '../components/trade/index.vue'
import ContractPosition from '../components/position/detail/index.vue'
import ContractStatement from '../components/statement/index.vue'
import { getGoodsCurrencyItemName } from '@/constants/order'

const { router, getQueryStringToNumber } = useNavigation()

const { global: { t } } = i18n

const futuresStore = useFuturesStore()
const accountStore = useAccountStore()

const accountid = getQueryStringToNumber('id')
const activeTab = shallowRef(0)
const showSheet = shallowRef(false)
const isAmountVisible = shallowRef(true)

// 合约账户
const accountItem = computed(() => accountStore.getAccountItem({ accountid }))

const quotes = computed(() => futuresStore.quotationList.filter((e) => e.trademode === 10 && (e.goodscurrencyid === accountItem.value?.currencyid || e.currencyid === accountItem.value?.currencyid)))

const gridItems = computed(() => {
    const items: GridItem[] = [
        {
            text: t('digital.wallet-transfer'),
            icon: './img/icons/transfer.svg',
            to: { name: 'wallet-transfer' }
        }
    ]

    if (quotes.value.length) {
        items.push({
            text: t('digital.spot-goods-detail'),
            icon: './img/icons/trade.svg'
        })
    }

    return items
})

const goodsname = (code: string) => {
    return futuresStore.getI18nGoodsName(code)
}

// 获取金额
const getAccountAmount = (value: number) => {
    if (isAmountVisible.value) {
        return value.toFixed(accountItem.value?.currencydecimalplace)
    }
    return '**********'
}

const navigateToContractDetail = (goodsid?: number) => {
    showSheet.value = false

    // 多个商品弹出列表选择，单个商品直接跳转
    if (quotes.value.length > 1 && !goodsid) {
        showSheet.value = true
    } else {
        router.push({
            name: 'contract-goods-detail',
            query: {
                id: goodsid ?? quotes.value[0].goodsid
            }
        })
    }
}

watch(isAmountVisible, (val) => {
    localStorage.setItem('isAmountVisible', JSON.stringify(val))
})

onActivated(() => {
    const visible = localStorage.getItem('isAmountVisible') || 'true'
    isAmountVisible.value = JSON.parse(visible)
})
</script>