<script lang="ts" setup>
import type {
  UploadFile,
  UploadFiles,
  UploadUserFile,
} from 'element-plus'
import { useAppUserStore } from '@/common/app/app-user-store.ts'
import { serverBaseUrl } from '@/common'
import { type R } from '@/common/utils/http-util.ts'
import Strings from '@/common/utils/strings.ts'
import AppApi from '@/common/app/app-api.ts'

const props = defineProps<{
  files?: string[]
  file?: string
  limit: number
}>()

const emit = defineEmits([ 'update:files', 'update:file' ])
const appUserStore = useAppUserStore()

const headers = computed(() => ({
  Authorization: appUserStore.token!,
}))
const uploadUrl = serverBaseUrl + '/oss/upload'

const files = ref<UploadUserFile[]>([])

function uploadSuccHandler(response: R<string>, _: UploadFile, uploadFiles: UploadFiles) {
  if (props.limit === 1) {
    emit('update:file', response.data)
  } else {
    const urls = uploadFiles.filter(it => it.response != null && (it.response as R<string>).success).map(it => (it.response as R<string>).data)
    emit('update:files', urls)
  }
}

function rmFileHandler(_: UploadFile, uploadFiles: UploadFiles) {
  if (props.limit === 1) {
    if (uploadFiles.length > 0) {
      emit('update:file', (files.value[0].response as R<string>).data)
    } else {
      emit('update:file', undefined)
    }
  } else {
    const urls = uploadFiles.filter(it => it.response != null && (it.response as R<string>).success).map(it => (it.response as R<string>).data)
    emit('update:files', urls)
  }
}

function uploadFailHandler(response: any, uploadFile: UploadFile, uploadFiles: UploadFiles) {
  console.log(response, uploadFile, uploadFiles)
}

defineExpose({
  setDefaultFiles(urls: string[]) {
    if (urls.length > 0) {
      for (let i = 0; i < urls.length; i++) {
        const url = urls[i]
        if (Strings.isBlank(url)) {
          continue
        }
        files.value?.push({
          uid: i,
          name: url.substring(url.lastIndexOf('/') + 1),
          url: AppApi.fileUrl(url),
          response: {code: 0, success: true, msg: '', message: '', data: url},
        })
      }
    }
  },
})


</script>

<template>
  <ElUpload
    v-model:file-list="files"
    :action="uploadUrl"
    :headers="headers"
    :limit="limit"
    :on-error="uploadFailHandler"
    :on-remove="rmFileHandler"
    :on-success="uploadSuccHandler"
    v-bind="$attrs">
    <slot/>
  </ElUpload>
</template>

<style lang="stylus" scoped>

</style>
