<template>
    <view>
        <uv-form-item :label="title" :prop="fieldItemProp" borderBottom @click="showPicker">
            <FBFormField>
                <text>{{ value }}</text>
            </FBFormField>
            <template v-slot:right>
                <uv-icon name="arrow-right"></uv-icon>
            </template>
        </uv-form-item>
        <uv-calendars ref="calendar" @confirm="onSelect"></uv-calendars>
    </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 calendar = ref();

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

const fieldItemProp = dataIndex.join('.')

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

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

const value = computed(() => getByPaths(props.modelValue, dataIndex))

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