<script setup>
import { REQUEST } from '~/utils/request'
import { resolveFileString } from '~/utils/helper'

const attrs = useAttrs()

const props = defineProps({
  // part: String,
  // full: String,
  modelValue: String,
})

// const emits = defineEmits(['update:part', 'update:full'])
const emits = defineEmits(['update:modelValue'])
const fileList = $ref(resolveFileString(props.modelValue).map(_ => ({ ..._, res: _ })))

// if (props.part) {
//   fileList = resolveFileString(props.part)
// }
// if (props.full) {
//   fileList = resolveFileString(props.full)
// }

const handleAfterRead = (fileProxy) => {
  fileProxy.status = 'uploading'
  fileProxy.message = '上传中...'
  const { file } = fileProxy
  REQUEST.upload({
    url: '/upload/main/file',
    data: { filedata: file },
  }).then((res) => {
    console.log('res :>> ', res)
    console.log('fileList :>> ', fileList)
    if (res.code === '1') {
      // fileList.value.push(res.data)
      fileProxy.url = `${window.GLOBAL_CONFIG.oss}/${res.data.url}`
      fileProxy.res = {
        name: res.data.file_name,
        url: fileProxy.url,
        origin: res.data.url,
      }
      fileProxy.status = 'done'
      fileProxy.message = ''

      // emits('update:part', fileList.map((item) => item.res.name + ',' + item.res.url).join(';'))
      // emits('update:part', fileList.map((item) => item.res.name + ',' + item.res.url).join(';'))
      // emits('update:modelValue', fileList.map(item => `${item.res.name},${item.res.origin}`).join(';'))
      emits('update:modelValue', fileList.map(item => `${item.res.origin}`).join(';'))
    }
    else {
      fileProxy.status = 'failed'
      fileProxy.message = '上传失败'
    }
  }).catch((err) => {
    console.error(err)
  })
}
</script>

<template>
  <van-uploader v-model="fileList" :after-read="handleAfterRead" :=attrs ><slot></slot></van-uploader>
</template>
