<template>
  <el-form ref="uploadExcel" class="upload-excel-file">
    <!-- 文件 -->
    <el-form-item :label="$t('trials:consistencyCheck:label:file2')">
      <div class="upload-container">
        <el-upload class="upload-demo" action accept=".xlsx,.xls,.csv" :before-upload="beforeUpload"
          :http-request="handleUploadFile" :on-preview="handlePreview" :show-file-list="true" :limit="1"
          :on-exceed="handleExceed">
          <el-button size="small" type="primary">
            {{ $t('trials:consistencyCheck:dialogButton:upload') }}
          </el-button>
          <span slot="tip" style="margin-left:10px;" class="el-upload__tip">
            ({{ $t('trials:consistencyCheck:message:excelFileOnly') }})
          </span>
        </el-upload>
      </div>
    </el-form-item>
  </el-form>
</template>
<script>
import { readingImport } from '@/api/reading'
export default {
  props: {
    visitTaskId: {
      type: String,
      required: true
    },
    lesionType: {
      type: Number,
      required: true
    },
    TableName: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
    }
  },
  methods: {
    beforeUpload(file) {
      // 检测文件类型是否符合要求
      if (this.checkFileSuffix(file.name)) {
        return true
      } else {
        // Must be xls or xlsx format
        this.$alert(this.$t('trials:consistencyCheck:message:xlsx'))

        return false
      }
    },
    async handleUploadFile(param) {
      const loading = this.$loading({ fullscreen: true })
      try {
        var data = new FormData()
        data.append('file', param.file)
        data.append('visitTaskId', this.visitTaskId)
        data.append('readingImportType', 3)
        data.append('TableName', this.TableName)
        await readingImport(data)
        this.$emit('close')
        this.$message.success(this.$t('common:message:savedSuccessfully'))
        loading.close()
      } catch (e) {
        loading.close()
        console.log(e)
      }
    },
    handlePreview(file) {
      if (file.fullPath) {
        window.open(file.fullPath, '_blank')
      }
    },
    handleExceed(files, fileList) {
      // Upload is currently limited to 1 file
      this.$message.warning(this.$t('trials:consistencyCheck:message:onlyOneFile'))
    },
    checkFileSuffix(fileName) {
      var typeArr = ['xls', 'xlsx', 'csv']
      var extendName = fileName.substring(fileName.lastIndexOf('.') + 1).toLocaleLowerCase()
      if (typeArr.indexOf(extendName) !== -1) {
        return true
      } else {
        return false
      }
    }
  }
}
</script>

<style lang="scss">
.upload-excel-file {
  .upload-container .el-upload--text {
    border: none;
    width: 80px;
    height: 40px;
  }

  .upload-container .el-input--small {
    margin-bottom: 5px;
  }

  .upload-container .el-icon-circle-check {
    color: #428bca;
    font-size: 13px;
  }

  .account_item_clear {
    .el-tag__close {
      display: none !important;
    }
  }
}
</style>
