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

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

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

defineProps<{ modelValue: string }>()

const emits = defineEmits(['update:modelValue', 'onRefresh'])

// const uplaodUrl = ref();
const { accessToken } = storeToRefs(useAccessStore())
const upload = ref<UploadInstance>()
const handleExceed: UploadProps['onExceed'] = (file) => {
  upload.value!.clearFiles()
  const files = file[0] as UploadRawFile
  files.uid = genFileId()
  upload.value!.handleStart(files)
  submitUpload()
}

const submitUpload = () => {
  upload.value!.submit()
}

const beforeIconUrlUpload = (file: { size: number; type: string }) => {
  const maxSize = 1024 * 1024 * 10
  if (file.size > maxSize) {
    ElMessage.error('上传大小不正确，不能超过10MB')
    return false
  }
}

const successUrlUpload: UploadProps['onSuccess'] = (response, _, _2) => {
  if (response.code === 200) {
    emits('update:modelValue', response.data.filePath)
  }
}

const handleRemove: UploadProps['onRemove'] = (_, _2) => {
  // console.log(uploadFile, uploadFiles)
}

// const handleReupload = () => {
//   //
// }
</script>

<template>
  <div class="upload-box">
    <el-image
      v-if="modelValue"
      :src="modelValue"
      fit="contain"
      class="image"
      :preview-src-list="[modelValue]"
    />
    <el-upload
      ref="upload"
      action="/api/main/sysFileInfo/tenUploadAll"
      :on-remove="handleRemove"
      :headers="{
        Authorization: accessToken,
        'X-Tenant-Id': SYS_INFO.tenantId,
      }"
      :data="{
        type: 1,
      }"
      accept="image/*"
      :show-file-list="false"
      :before-upload="beforeIconUrlUpload"
      :on-success="successUrlUpload"
      :limit="1"
      :on-exceed="handleExceed"
    >
      <el-icon><Switch /></el-icon>
    </el-upload>
  </div>
</template>

<style lang="scss" scoped>
.upload-box {
  display: flex;
  gap: 10px;
  align-items: center;
  justify-content: space-between;

  & > div {
    display: flex;
    align-items: center;
  }

  .image {
    width: 100px;
    height: 100px;
    cursor: pointer;
  }

  :deep(.el-upload) {
    padding: 2px 5px;
    font-size: 20px;
    border-radius: 5px;
    // background-color: red;
    transition: all 0.3s;

    &:hover {
      background-color: #b8e4f8;
    }
  }
}
</style>
