<script setup lang="ts">
import type { UploadFile, UploadFiles } from 'element-plus'
import { user } from '~/store/index'
const props = defineProps<{
  part?: string
  full?: string
  d?: object
}>()
const emits = defineEmits(['update:part', 'update:full'])

const action = `${window.GLOBAL_CONFIG.api}/upload/main/file`

function getFullUrl(str: string) {
  return /https?:\/\//.test(str) ? str : `${window.GLOBAL_CONFIG.oss}/${str}`
}
function handleString(str: string, hasName: boolean) {
  const arr = str.split(';')
  if (hasName) {
    return arr.map((item) => {
      const [url, name] = item.split('|')
      return {
        name,
        url: getFullUrl(url),
        part: url,
        status: 'success',
      }
    })
  }
  else {
    return arr.map(item => ({ url: getFullUrl(item) }))
  }
}

const fileList = reactive(
  props.part
    ? handleString(props.part, false)
    : props.full
      ? handleString(props.full, true)
      : [],
)

type _UploadFile = UploadFile & { part?: string }
type _UploadFiles = _UploadFile[]
function handleSuccess(
  response: any,
  uploadFile: _UploadFile,
  uploadFiles: _UploadFiles,
) {
  uploadFile.part = response.data.url
  const files = uploadFiles.filter(item => item.status === 'success')
  emits('update:part', files.map(({ part }) => part).join(';'))
  emits(
    'update:full',
    files.map(({ part, name }) => `${part}|${name}`).join(';'),
  )
}
</script>

<template>
  <el-upload v-model:file-list="fileList" :action="action" :data="{ token: user.token, ...props.d }" name="filedata" class="w-full" :on-success="handleSuccess">
    <template #default>
      <slot name="default">
        <el-button type="primary" size="default">
          点击上传
        </el-button>
      </slot>
    </template>
    <!-- <template #trigger>
      <slot name="trigger" />
    </template> -->
    <template #tip>
      <slot name="tip" />
    </template>
    <template #file="{ file }">
      <slot name="file" :file="file" />
    </template>
  </el-upload>
</template>
