<script lang="ts" setup>
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadRequestOptions, UploadUserFile } from 'element-plus'
import { upload } from '@/utils/upload'

const props = withDefaults(
  defineProps<{
    modelValue: string | []
    prefix?: string
    size?: number
    beforeUploadFiles?: (file: any) => boolean | void
    onChange?: (file: any, files: any) => void
  }>(),
  {
    prefix: 'upload/admin/'
  }
)

const emit = defineEmits(['update:modelValue'])

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

watch(
  () => props.modelValue,
  value => {
    fileList.value = Array.isArray(value) ? [...value] : []
  }
)

const showFileList = computed(() => {
  return Array.isArray(props.modelValue)
})

const handleBeforeUpload = async (file: any) => {
  // Keep a pseudo-url for legacy validators that inspect file.url/file name before upload.
  file.url = file.name
  const fileName = file.name
  if (props.beforeUploadFiles) {
    return props.beforeUploadFiles({ ...file, url: fileName })
  }
}

const handleUploadRequest = async (option: UploadRequestOptions) => {
  try {
    const url = await upload(option.file)
    ;(option.file as any).url = url
    ;(option.file as any).raw = Object.assign((option.file as any).raw || {}, { url })
    option.onSuccess({ url })
  } catch (error: any) {
    option.onError(error)
  }
}

// 上传成功
const handleSuccess: UploadProps['onSuccess'] = (response, file: any, files: any) => {
  if (!files.every((item: any) => item.status === 'success')) return
  if (showFileList.value) {
    emit(
      'update:modelValue',
      files.map((item: any) => {
        return {
          name: item.name,
          url: item.url || item.raw.url,
          size: item.size || item.raw.size,
          type: item.type || item.raw.type
        }
      })
    )
  } else {
    emit('update:modelValue', file.raw.url)
  }
  props.onChange?.(file, files)
}

// 上传限制
const handleExceed: UploadProps['onExceed'] = () => {
  ElMessage.warning('文件超出个数限制')
}

// 删除
const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  if (showFileList.value) {
    emit(
      'update:modelValue',
      uploadFiles.map((item: any) => {
        return { name: item.name, url: item.url || item.raw.url, size: item.size, type: item.type }
      })
    )
  } else {
    emit('update:modelValue', '')
  }
}

// 预览
const handlePreview: UploadProps['onPreview'] = uploadFile => {
  console.log(uploadFile)
}
</script>

<template>
  <el-upload
    action="#"
    :http-request="handleUploadRequest"
    :show-file-list="showFileList"
    :before-upload="handleBeforeUpload"
    :on-exceed="handleExceed"
    :on-remove="handleRemove"
    :on-preview="handlePreview"
    :on-success="handleSuccess"
    :file-list="fileList"
    class="uploader">
    <template v-if="showFileList">
      <template v-if="$attrs['list-type'] === 'picture-card'">
        <el-icon><Plus /></el-icon>
      </template>
      <template v-else-if="props.beforeUploadFiles">
        <el-button type="primary" size="default" round>上传图片/视频附件</el-button>
      </template>
      <template v-else>
        <el-button type="primary" class="app-upload-btn">点击上传</el-button>
      </template>
    </template>
    <div class="avatar-uploader" v-else>
      <el-image :src="(modelValue as string)" fit="contain" v-if="modelValue" />
      <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
    </div>
    <template #tip>
      <div class="el-upload__tip"><slot name="tip"></slot></div>
    </template>
  </el-upload>
</template>

<style lang="scss">
.uploader {
  flex: 1;
}
.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
  .el-image {
    width: 100%;
    height: 100%;
  }
}
.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  text-align: center;
}
</style>
