<script setup lang="ts">
import { nextTick, ref, watch } from 'vue'
import type { UploadFileInfo } from 'naive-ui'
import { fetchUpload } from '@/apis/upload'

interface Emit {
  (e: 'afterUpload', data: UploadFileInfo[]): void
  (e: 'remove', data: number): void
}

const props = defineProps({
  fileArr: {
    type: Array,
    default: () => {
      return []
    },
  },
  fileType: {
    type: String,
    default: 'image-card',
  },
  maxNum: {
    type: Number,
    default: 1,
  },
  listType: {
    type: String,
    default: '.doc,.docx,.pdf,.xls,.xlsx,.zip,.rar,.jpg,.png,.jpeg,.svg,.gif',
  },
})

const emit = defineEmits<Emit>()

const fileList = ref<UploadFileInfo[]>([])
const previewImageUrl = ref('')
const uploadPhotoRef = ref()
const imageRef = ref()
const showImage = false

watch(
  () => props.fileArr,
  (newValue) => {
    fileList.value = []
    if (newValue?.length) {
      newValue?.forEach((item) => {
        const params = {
          id: new Date().getTime().toString(),
          name: new Date().getTime().toString(),
          status: 'finished' as any,
          url: item as string,
        }
        fileList.value.push(params)
      })
    }
  },
  { deep: true, immediate: true },
)

function handleUpload(file: any) {
  if (file.event) {
    const formdata = new FormData()
    formdata.append('file', file.file.file)

    fetchUpload(formdata).then((res) => {
      if (res.code === 0) {
        const fileData = {
          id: file.file.id,
          name: file.file.name,
          status: 'finished' as any,
          url: (res.data as string) || null,
        }
        fileList.value.push(fileData)
      } else {
        const fileData = {
          id: file.file.id as string,
          name: file.file.name,
          status: 'error' as any,
        }
        fileList.value.push(fileData)
      }

      fileList.value = fileList.value.filter((item) => {
        return item.status !== 'pending'
      })
      emit('afterUpload', fileList.value)
    })
  } else {
    const fileId = file.file.id
    fileList.value = fileList.value.filter((item) => {
      return item.id !== fileId
    })
    emit('afterUpload', fileList.value)
  }
}

function handlePreview(file: UploadFileInfo) {
  const { url } = file
  previewImageUrl.value = url as string
  nextTick(() => {
    imageRef.value.click()
  })
}

function handleRemove(options: { file: UploadFileInfo; fileList: UploadFileInfo[]; index: number }) {
  emit('remove', options.index)
}
</script>

<template>
  <NUpload
    ref="uploadPhotoRef"
    v-model:file-list="fileList"
    :max="props.maxNum"
    :list-type="props.fileType"
    @change="handleUpload"
    @preview="handlePreview"
    @remove="handleRemove"
  >
  </NUpload>

  <NImage
    v-show="showImage"
    ref="imageRef"
    width="100"
    :src="previewImageUrl"
    :show-toolbar="false"
    :preview-src="previewImageUrl"
  />
</template>
