<template>
  <t-upload
    class="upload-button"
    theme="custom"
    :size-limit="maxSize"
    :accept="accept"
    :disabled="disabled"
    :before-upload="handleBeforeUpload"
    :request-method="upload"
    @fail="handleError"
    @success="handleSuccess"
    @validate="handleValidate"
    :allowUploadDuplicateFile="true"
  >
    <slot>
      <t-button theme="primary" v-bind="buttonProps"></t-button>
    </slot>
  </t-upload>
</template>

<script setup name="UploadButton">
import { MessagePlugin } from 'tdesign-vue-next';
import { request } from '@/utils/request.js';
import { getFileMD5 } from '@/utils/crypto.js';

const props = defineProps({
  accept: {
    type: String,
  },
  format: {
    type: Array,
    default() {
      return ['jpg', 'jpeg', 'png'];
    },
  },
  uploadUrl: {
    type: String,
    required: true,
  },
  uploadData: {
    type: Object,
    default() {
      return {};
    },
  },
  maxSize: {
    // 单位kb
    type: Number,
    default: 20 * 1024,
  },
  headers: {
    type: Object,
    default() {
      return { 'Content-Type': 'multipart/form-data' };
    },
  },
  buttonProps: {
    type: Object,
    default() {
      return {};
    },
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  paramFileName: {
    type: String,
    default: 'file',
  },
  successText: {
    type: String,
    default: '导入成功',
  },
});

const emit = defineEmits(['on-fail', 'on-success', 'on-validate-error']);

const checkFileFormat = (fileType) => {
  const _file_format = fileType.split('.').pop().toLocaleLowerCase();
  return props.format.length
    ? props.format.some((item) => item.toLocaleLowerCase() === _file_format)
    : true;
};
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.format.join('/');
    MessagePlugin.error(content);
    return false;
  }
  return true;
};

const upload = async (file) => {
  // console.log(file);
  let formData = new FormData();
  Object.entries(props.uploadData).forEach(([k, v]) => {
    formData.append(k, v);
  });
  formData.append(props.paramFileName, file.raw);

  const md5 = await getFileMD5(file.raw);
  // console.log(md5);
  const res = await request({
    url: props.uploadUrl,
    data: formData,
    headers: { ...props.headers, md5 },
  }).catch(() => {});

  if (res) {
    MessagePlugin.success(props.successText);
    return { status: 'success', response: res };
  } else {
    return { status: 'fail', error: '上传失败' };
  }
};

const handleValidate = (data) => {
  console.log(data);
  emit('on-validate-error', data);
};
const handleError = (error) => {
  console.log(error);
  emit('on-fail', error);
};
const handleSuccess = (data) => {
  console.log(data);
  emit('on-success', data);
};
</script>
