<template>
    <!-- 显示区域 -->
    <view class="filter-picker" @click="open" :class="{ disabled }">
        <view class="picker-value">
            <view class="picker-text">
                {{ currentLabel || placeholderText }}
            </view>
            <uni-icons type="down" size="14" color="#6b7280" />
        </view>
    </view>

    <!-- u-picker -->
    <!-- v-model="show" -->
    <u-picker v-if="show" :show="show" :cancelText="t('common.cancel')" :confirmText="t('common.confirm')"
        confirmColor="#ea002a" :columns="columns" keyName="label" :defaultIndex="defaultIndex" @confirm="onConfirm"
        @cancel="onCancel" />
</template>
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'

type Option = {
    value: string | number | undefined
    label: string
}
const props = defineProps<{
    modelValue?: string | number | null
    options: Record<string, string> | Option[]
    placeholder?: string
    disabled?: boolean
    showAll?: boolean
}>()
const emit = defineEmits<{
    (e: 'update:modelValue', value: string | number | undefined): void
    (e: 'change', option: Option): void
}>()
const { t } = useI18n()
const show = ref(false)
const placeholderText = computed(() =>
    props.placeholder || t('common.select')
)
const optionList = computed<Option[]>(() => {
    let list: Option[] = []

    if (Array.isArray(props.options)) {
        list = props.options.map(i => ({
            value: i.value,
            label: i.label
        }))
    } else {
        list = Object.entries(props.options).map(([value, label]) => ({
            value: isNaN(Number(value)) ? value : Number(value),
            label:
                typeof label === 'string' && label.includes('.')
                    ? t(label)
                    : String(label)
        }))
    }

    if (props.showAll !== true) {
        list.unshift({
            value: undefined,
            label: props.placeholder || t('State.All')
        })
    }

    return list
})
const currentIndex = computed(() => {
    const index = optionList.value.findIndex(
        i => i.value === props.modelValue
    )
    return index === -1 ? 0 : index
})
const defaultIndex = computed(() => [currentIndex.value])
const currentLabel = computed(() => {
    return optionList.value[currentIndex.value]?.label || ''
})
const columns = computed<Option[][]>(() => {
    return [optionList.value]
})

function open() {
    if (props.disabled) return
    show.value = true
}
function onConfirm(e: any) {
    const index = e.indexs[0]
    const selected = optionList.value[index]

    emit('update:modelValue', selected.value)
    emit('change', selected)
    show.value = false
}

function onCancel() {
    show.value = false
}
</script>
