<script setup lang="ts">
import { deleteFile, upload } from '@af-mobile-client-vue3/services/api/common'
import {
  Button as vanButton,
  Uploader as vanUploader,
} from 'vant'
import { onBeforeUnmount, ref, watch } from 'vue'

const props = defineProps({
  imageList: Array<any>,
  outerIndex: { default: undefined },
  authority: { default: 'user' },
  uploadMode: { default: 'server' },
})
const emit = defineEmits(['updateFileList'])

const imageList = ref(props.imageList)

// 监听 props.imageList 的变化
const stopWatchImageList = watch(() => props.imageList, (newVal) => {
  if (newVal?.length > 0) {
    const existingIds = imageList.value ? imageList.value.map(item => item.id) : []
    const newItems = newVal.filter(item => !item.id || !existingIds.includes(item.id)).map((item) => {
      return { id: item.id, name: item.f_filename, url: item.f_downloadpath }
    })
    if (newItems.length > 0) {
      if (!imageList.value) {
        imageList.value = newItems
      }
      else {
        imageList.value = [...imageList.value, ...newItems]
      }
    }
  }
}, { immediate: true, deep: true })

onBeforeUnmount(() => {
  stopWatchImageList()
})
// 上传图片
function fileUpload(file: any): void {
  const formData = new FormData()

  formData.append('avatar', file.file)
  formData.append('resUploadMode', props.uploadMode)
  formData.append('pathKey', 'Default')

  formData.append('formType', 'image')
  formData.append('useType', 'Default')
  formData.append('resUploadStock', '1')
  formData.append('filename', file.file.name)
  formData.append('filesize', (file.file.size / 1024 / 1024).toFixed(4))
  formData.append('f_operator', '')

  imageList.value[imageList.value.length - 1].message = '上传中...'
  imageList.value[imageList.value.length - 1].status = 'uploading'
  imageList.value[imageList.value.length - 1]!.name = file.file.name

  upload(formData, 'af-system', { 'Content-Type': 'multipart/form-data' }).then((res: any) => {
    if (res.success || res.id) {
      imageList.value[imageList.value.length - 1].uid = res.data.id
      imageList.value[imageList.value.length - 1].id = res.data.id
      delete imageList.value[imageList.value.length - 1].message
      imageList.value[imageList.value.length - 1].status = 'done'
      imageList.value[imageList.value.length - 1].url = res.data.f_downloadpath
    }
    else {
      imageList.value[imageList.value.length - 1].status = 'failed'
      imageList.value[imageList.value.length - 1].message = '上传失败'
    }
    if (props.outerIndex !== undefined)
      emit('updateFileList', imageList.value.filter(item => item.status === 'done'), props.outerIndex)
    else
      emit('updateFileList', imageList.value.filter(item => item.status === 'done'))
  })
}

// 删除图片
function deleteFileFunction(file: any) {
  if (file.id) {
    deleteFile({ ids: [file.id], f_state: '删除' }).then((res: any) => {
      if (res.msg !== undefined) {
        let target = -1
        for (let i = 0; i < imageList.value.length; i++) {
          if (imageList.value[i].id === Number.parseInt(file.id)) {
            target = i
            break
          }
        }
        imageList.value.splice(target, 1)
        if (props.outerIndex !== undefined)
          emit('updateFileList', imageList.value.filter(item => item.status === 'done'), props.outerIndex)
        else
          emit('updateFileList', imageList.value.filter(item => item.status === 'done'))
      }
    })
  }
}
</script>

<template>
  <van-uploader
    v-if="props.authority === 'user'"
    v-model="imageList"
    :after-read="fileUpload"
    :show-upload="false"
    :deletable="false"
  >
    <vanButton icon="photograph" type="primary">
      上传
    </vanButton>
  </van-uploader>
  <van-uploader
    v-else-if="props.authority === 'admin'"
    v-model="imageList"
    multiple
    :preview-image="true"
    :after-read="fileUpload"
    :before-delete="deleteFileFunction"
  >
    <vanButton icon="photograph" type="primary">
      上传
    </vanButton>
  </van-uploader>
</template>

<style scoped lang="less">
</style>
