<template>
    <view>
        <uv-form-item :label="title" :prop="fieldItemProp" borderBottom @click="showPicker">
            <FBFormField>
                <text>{{ current.text }}</text>
            </FBFormField>
            <template v-slot:right>
                <uv-icon name="arrow-right"></uv-icon>
            </template>
        </uv-form-item>
        <uv-picker ref="picker" :columns="columns" keyName="text" @confirm="onSelect"
            :defaultIndex="current.defaultIndex"></uv-picker>
    </view>
</template>

<script setup lang="ts">
import { computed, nextTick, ref } from 'vue'
import type { FieldItemInfo } from '../../../types/basic';
import { getByPaths, setByPaths } from '../../../commons/utils/dataPath';
import FBFormField from './fb-form-field.vue'

const props = defineProps<FieldItemInfo>()
const emit = defineEmits()
const picker = ref();

const { title, dataIndex, valueEnum, fieldProps = {} } = props

const fieldItemProp = dataIndex.join('.')

const items: any[] = []

if (valueEnum) {
    Object.keys(valueEnum).forEach(key => {
        items.push({ text: valueEnum[key]?.text, value: key })
    })
}

const columns: any[][] = [items]

const showPicker = () => {
    picker.value?.open();
};

const onSelect = (e) => {
    console.log('confirm', e);
    updateValue(e.value[0].value)
}

const current = computed(() => {
    const value = getByPaths(props.modelValue, dataIndex)
    const index = items.findIndex((item) => item.value === value)
    const text = items[index]?.text
    return { text, value, defaultIndex: [index] }
})

const updateValue = (val: any) => {
    const oldVal = getByPaths(props.modelValue, dataIndex)
    if (val !== oldVal) {
        nextTick(() => {
            setByPaths(props.modelValue, dataIndex, val)
            emit('update:modelValue', props.modelValue)
        })
    }
}
</script>