<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="labelField" @confirm="onSelect"
            :defaultIndex="current.defaultIndex"></uv-picker>
    </view>
</template>

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

const props = defineProps<FieldItemInfo>()
const emit = defineEmits()
const items = ref<Data[]>();
const picker = ref();
const current = ref();

const { title, dataIndex, lookup } = props

const fieldItemProp = dataIndex.join('.')
const labelField = lookup!.labelField
const valueField = lookup!.valueField

const store = lookupStore();

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

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

const syncCurrent = () => {
    const value = getByPaths(props.modelValue, dataIndex)
    const index = items?.value?.findIndex((item) => item?.[valueField] === value)
    const text = index != undefined && items?.value?.[index]?.[labelField]
    console.log(text, index)
    current.value = { text, value, defaultIndex: [index] }
}

watch(items, syncCurrent, { immediate: true })
watch(
  () => getByPaths(props.modelValue, dataIndex),
  syncCurrent,
  { immediate: true }
)


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

const fetchLookupData = async () => {
    const lookupData = await store.getLookupData(lookup!)
    items.value = lookupData?.items
}

onMounted(() => {
    fetchLookupData()
})

const columns = computed(() => [items.value])
</script>