<template>
  <t-upload
    ref="uploadRef3"
    v-model="files"
    :theme="theme"
    :tips="`最多只能上传 ${imgLength} 张图片`"
    accept="image/*"
    :abridge-name="[6, 6]"
    :auto-upload="true"
    :upload-all-files-in-one-request="false"
    multiple
    :max="imgLength"
    :before-upload="handleBeforeUpload"
    :request-method="upload"
    @fail="handleFail"
    @change="handleChange"
  >
  </t-upload>
</template>
<script setup name="MyUpload">
import { ref } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import { uploadFiles } from '@/api/common';
import { getFileMD5 } from '@/utils/crypto';

const emit = defineEmits(['change']);
const props = defineProps({
  theme: {
    type: String,
    default: 'image',
  },
  accept: {
    type: String,
    default: '.jpg,.jpeg,.png',
  },
  imgLength: {
    type: Number,
    default: 3,
  },
  maxSize: {
    // 单位kb
    type: Number,
    default: 20 * 1024,
  },
});
const files = ref([]);
const checkFileFormat = (fileType) => {
  const _file_format = '.' + fileType.split('.').pop().toLocaleLowerCase();
  return props.accept.split(',').includes(_file_format.toLocaleLowerCase());
};
const handleBeforeUpload = (file) => {
  if (file.size > props.maxSize * 1024) {
    const size =
      props.maxSize < 1024
        ? `${props.maxSize}kb`
        : `${Math.floor(props.maxSize / 1024)}M`;
    const content = '文件大小不能超过' + size;
    MessagePlugin.error(content);
    return false;
  }

  if (!checkFileFormat(file.name)) {
    const content = '只支持文件格式为' + props.accept;
    MessagePlugin.error(content);
    return false;
  }

  return true;
};
const handleFail = ({ file }) => {
  MessagePlugin.error(`文件 ${file.name} 上传失败`);
};

const upload = async (files) => {
  let formData = new FormData();
  const file = files[0].raw;
  const md5 = await getFileMD5(file);
  formData.append('file', file);
  formData.append('type', 'FILE');

  const res = await uploadFiles(formData, md5).catch(() => {});
  if (res) {
    return { status: 'success', response: { id: res.id, url: res.previewUrl } };
  } else {
    return { status: 'fail', error: '上传失败' };
  }
};
const handleChange = () => {
  emit(
    'change',
    files.value.map((item) => item.response)
  );
};
</script>
