<template>
    <view>
        <uv-form-item :label="title" :prop="fieldItemProp" borderBottom>
            <UniFilePicker v-model="value" file-mediatype="image" :limit="limit" @delete="deleteFile" @select="uploadFile" />
        </uv-form-item>
        <!-- <uv-upload :fileList="value" accept="image" multiple
            @afterRead="({ file, lists, name }) => { console.log(file, lists, name); uploadFile(file) }" /> -->
    </view>
</template>

<script setup lang="ts">
import { computed, defineEmits, defineProps, nextTick } from 'vue'
import type { FieldItemInfo } from '../../../types/basic';
import { getByPaths, setByPaths } from '../../../commons/utils/dataPath';
import { doUpload } from '../../../commons/api/component';
import FBFormField from './fb-form-field.vue'
import UniFilePicker from '@dcloudio/uni-ui/lib/uni-file-picker/uni-file-picker.vue'

interface AttachmentProps extends FieldItemInfo {
    multi: boolean
}


const props = defineProps<AttachmentProps>()
const emit = defineEmits()

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

const limit = multi ? 9 : 1

const fieldItemProp = dataIndex.join('.')

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

const deleteFile = (fileIndex: any) => {
    const newValue = value.value.filter((_: any, index: number) => index !== fileIndex.index)
    setValue(newValue)
}

const uploadFile = async ({ tempFiles }) => {
    let fileUrls = await doUpload(tempFiles)
    if(multi && value.value?.length) {
        fileUrls = [...value.value, ...fileUrls]
    }
    setValue(fileUrls)
}

const setValue = (newValue: any[]) => {
    nextTick(() => {
        console.log(newValue, 'newValue')
        setByPaths(props.modelValue, dataIndex, multi ? newValue : newValue[0])
        emit('update:modelValue', props.modelValue)
    })
}
</script>