<script lang="ts" setup>
import { ElMessage } from 'element-plus'
// import { Plus } from '@element-plus/icons-vue'
import type { UploadProps, UploadUserFile } from 'element-plus'
import md5 from 'blueimp-md5'
import { getSignature } from '@/api/base'

type UploadFileItem = { name: string; url: string }

const props = withDefaults(defineProps<{ modelValue: string | UploadFileItem[]; prefix?: string }>(), {
  prefix: 'upload/admin/'
})
const emit = defineEmits(['update:modelValue'])

const uploadData = ref()

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) => {
  const fileName = file.name
  const key = props.prefix + md5(fileName + new Date().getTime()) + fileName.substr(fileName.lastIndexOf('.'))
  const response: Record<string, any> = await getSignature()
  uploadData.value = {
    key,
    host: response.host,
    OSSAccessKeyId: response.accessid,
    policy: response.policy,
    signature: response.signature,
    success_action_status: '200',
    url: `${response.host}/${key}`
  }
  file.url = `${response.host}/${key}`
}

// 上传成功
const handleSuccess = (response: any, 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 }
      })
    )
  } else {
    emit('update:modelValue', file.raw.url)
  }
}

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

// 删除
const handleRemove: UploadProps['onRemove'] = (file, files) => {
  emit(
    'update:modelValue',
    files.map((item: any) => {
      return { name: item.name, url: item.url || item.raw.url }
    })
  )
}

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

<template>
  <el-upload
    :action="uploadData?.host"
    :data="uploadData"
    :show-file-list="false"
    :before-upload="handleBeforeUpload"
    :on-exceed="handleExceed"
    :on-remove="handleRemove"
    :on-preview="handlePreview"
    :on-success="handleSuccess"
    :file-list="fileList"
    class="uploader">
    <el-button type="primary">选择本地图片</el-button>
  </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>
