<template>
    <Field v-bind="$attrs" :placeholder="t('common.choice')" arrow-direction="down" is-link readonly @click="showSheet = true">
        <template #input v-if="currencyItem">
            <app-image-icon :url="getCurrencyIconUrl(currencyItem.enumitemvalue)" size="small" />
            <span>{{ currencyItem.label }}</span>
        </template>
    </Field>
    <ActionSheet v-model:show="showSheet" :title="t('common.choice')" teleport="body">
        <CellGroup style="min-height: 200px;">
            <RadioGroup v-model="currencyId" v-if="currencyList.length">
                <template v-for="(item, index) in currencyList" :key="index">
                    <Cell size="large" :title="item.label" :border="false" clickable center
                        @click="onRadioClick(item.value)">
                        <template #icon>
                            <app-image-icon :url="getCurrencyIconUrl(item.enumitemvalue)" size="small"
                                style="margin-right: 8px;" />
                        </template>
                        <template #right-icon>
                            <Radio :name="item.value" />
                        </template>
                    </Cell>
                </template>
            </RadioGroup>
            <Empty :description="t('common.nodatas')" v-else />
        </CellGroup>
    </ActionSheet>
</template>

<script lang="ts" setup>
import { shallowRef, computed, onMounted, nextTick } from 'vue'
import { Field, ActionSheet, CellGroup, RadioGroup, Cell, Radio, Empty } from 'vant'
import { getCurrencyIconUrl } from '@/filters'
import { getDigitalCurrencyList } from '@/constants/order'
import { useSpotAccountStore } from '../../views/wallet/components/spot/composables'
import AppImageIcon from '@mobile/components/base/image-icon/index.vue'
import { i18n } from '@/stores'

const props = defineProps({
    modelValue: {
        type: Number
    }
})

const emit = defineEmits(['update:modelValue', 'change'])
const { global: { t } } = i18n
const showSheet = shallowRef(false)
const spotAccountStore = useSpotAccountStore()
const digitalCurrencyList = getDigitalCurrencyList()

// 过滤未激活账户
const currencyList = computed(() => {
    const ids = new Set()
    for (const item of spotAccountStore.dataList) {
        if (item.digitalaccountid) {
            ids.add(item.currencyid)
        }
    }
    return digitalCurrencyList.filter((e) => ids.has(e.enumitemname))
})

const currencyItem = computed(() => currencyList.value.find((e) => e.enumitemname === currencyId.value))

const currencyId = computed({
    get: () => props.modelValue,
    set: (val) => emit('update:modelValue', val)
})

const onChange = () => {
    emit('change', currencyItem.value)
}

const onRadioClick = (value: number) => {
    currencyId.value = value
    showSheet.value = false
    nextTick(() => onChange())
}

onMounted(() => {
    onChange()
})
</script>