<script lang="ts" setup>
import type {
  UploadFile,
  UploadFiles,
  UploadProps,
  UploadRawFile,
} from 'element-plus'

import { SYS_INFO } from '@vben/preferences'
import { useAccessStore } from '@vben/stores'

import { Plus } from '@element-plus/icons-vue'

import { downloadFile } from '#/utils/tool'

withDefaults(
  defineProps<{
    modelValue?: string
  }>(),
  {
    modelValue: '',
  },
)
const emits = defineEmits(['update:modelValue'])
const upload = ref()
const { accessToken } = storeToRefs(useAccessStore())
const handleExceed: UploadProps['onExceed'] = (files) => {
  upload.value!.clearFiles()
  const file = files[0] as UploadRawFile
  upload.value!.handleStart(file)
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (_, uploadFile: any) => {
  emits('update:modelValue', uploadFile.response.data.filePath as string)
}

const handleRemove: UploadProps['onRemove'] = (_1, _2) => {
  upload.value!.clearFiles()
  emits('update:modelValue', '')
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  downloadFile(uploadFile.url!)
}

function beforeUpload(file: UploadRawFile) {
  if (file.size > 10 * 1024 * 1024) {
    ElMessage.error('图片大小请不要超过10M')
    return false
  }
}

function error(error: Error, _: UploadFile, _2: UploadFiles) {
  if (String(error).includes('413')) {
    ElMessage.error('上传的图片过大')
  }
}
</script>
<template>
  <div class="content">
    <el-upload
      ref="upload"
      :file-list="(modelValue ? [{ url: modelValue }] : []) as UploadFile[]"
      class="avatar-uploader"
      action="/api/main/sysFileInfo/tenUploadAll"
      list-type="picture-card"
      :limit="1"
      :on-exceed="handleExceed"
      :headers="{
        Authorization: accessToken,
        'X-Tenant-Id': SYS_INFO.tenantId,
      }"
      :on-success="handleAvatarSuccess"
      :on-remove="handleRemove"
      :on-preview="handlePictureCardPreview"
      :before-upload="beforeUpload"
      :on-error="error"
    >
      <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
    </el-upload>
  </div>
</template>
<style lang="scss" scoped>
//
.avatar-uploader {
  :deep(.el-upload-list--picture-card) {
    .el-upload-list__item {
      width: 100px;
      height: 100px;
    }

    .el-upload--picture-card {
      width: 100px;
      height: 100px;
    }
  }
}
</style>
