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

const props = defineProps({
  theme: {
    type: String,
    default: 'image',
  },
  accept: {
    type: String,
    default: '.jpg,.jpeg,.png',
  },
  maxSize: {
    // 单位kb
    type: Number,
    default: 20 * 1024,
  },
  config: {
    type: Object,
  },
  modelValue: { type: Array },
});
const emit = defineEmits(['update:modelValue', 'change']);

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 = () => {
  console.log(files.value);
  const data = files.value.map((item) => item.response);
  emit('update:modelValue', data);
  emit('change', data);
};

onMounted(() => {
  files.value = props.config.value || [];
});
// watch(
//   () => props.modelValue,
//   (val, oldval) => {
//     if (val === oldval) return;
//     files.value = val || [];
//   },
//   {
//     immediate: true,
//   }
// );
</script>
