<template>
  <span v-if="isEdit">
    <a-upload :file-list.sync="fileList" :remove="removeFile" @preview="handleDownload">
      <a-button @click.stop="beforeUpload">
        <a-icon type="upload" /> {{ $ft('i18n_common_select_file', '选择文件') }}
      </a-button>
    </a-upload>
    <fast2-upload
      ref="upload"
      v-show="false"
      :btnName="$ft('i18n_common_import_data_from_excel', '导入Excel数据')"
      :isElementBtn="false"
      :key="uploader"
      @file-error="onFileError"
      @file-progress="onFileProgress"
      @file-success="fileSuccess"
    />
  </span>
  <div v-else>
    <div
      class="download-link"
      @click="handleDownload(item)"
      v-for="(item, index) in fileList"
      :key="index"
    >
      <a-icon type="paper-clip" />{{ item.name }}
    </div>
  </div>
</template>

<script>
import { getApiPath } from '../../lib/utils';
const BaseUrl = getApiPath();
export default {
  name: 'BtnUpload',
  props: {
    defaultData: {
      type: String,
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    beforeDownLoad: {
      type: Function
    }
  },
  data() {
    return {
      uploader: new Date().getTime(),
      fileList: []
    };
  },
  watch: {
    defaultData: {
      handler(val) {
        if (val) {
          this.fileList = JSON.parse(val);
        }
      },
      immediate: true
    }
  },
  methods: {
    removeFile(file) {
      const index = this.fileList.indexOf(file);
      const newFileList = this.fileList.slice();
      newFileList.splice(index, 1);
      this.fileList = newFileList;
      this.$emit('change', this.fileList);
    },
    fileSuccess(rootFile, file, message, chunk) {
      const data = JSON.parse(message)?.data;
      data.uid = data.url;
      this.fileList.push(data);
      this.uploader++;
      this.$emit('change', this.fileList);
    },
    // excel 模板: 导入文件上传中
    onFileProgress() {
      console.log('文件上传中');
    },
    // excel 模板: 导入文件上传失败
    onFileError() {
      this.$message.error(
        this.$ft('i18n_common_upload_failed_please_try_again', '上传失败, 请重试')
      );
    },
    beforeUpload() {
      this.$refs.upload.$el.getElementsByTagName('input')[0].click();
      return false;
    },
    handleDownload(file) {
      if (this.beforeDownLoad && typeof this.beforeDownLoad === 'function') {
        const result = this.beforeDownLoad();
        if (result === 'stop') {
          return;
        }
      }
      const blobUrl = `${BaseUrl}/servlet/downloadServlet?filePath=${file.url}`;
      this.download(blobUrl, file.name);
    },
    download(blobUrl, fileName) {
      const a = document.createElement('a');
      a.download = fileName;
      a.href = blobUrl;
      a.click();
    }
  }
};
</script>
