<!-- 上传文本文件并读取其内容 -->
<!-- Example: 客户-支付中心-支付渠道管理-新增 -->
<template>
  <div>
    <el-upload
      ref="upload"
      class="upload-demo"
      :on-change="onChange"
      :auto-upload="false"
      :show-file-list="false"
      :file-list="fileList"
      :accept="accept"
      :before-upload="beforeUpload"
    >
      <!-- :auto-upload="false" -->
      <!-- :http-request="submitUpload" -->
      <el-button class="btn" size="small">点击上传</el-button>
    </el-upload>
    <div v-if="fileInfo" class="file-list">
      <span>{{ fileInfo.name }}</span><i class="el-icon-delete" @click="delFile" />
    </div>
  </div>
</template>

<script>
export default {
  props: {
    value: {
      type: Object,
      default: () => {
        return {}
      }
    },
    accept: {
      type: String,
      default: '.pem'
    },
    fileSize: {
      type: [Number, String],
      default: 2
    },
    base64: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      fileInfo: null
    }
  },
  watch: {
  },
  created() {
    if (typeof FileReader == 'undefined') {
      this.$message.warning('您的浏览器不支持文件内容读取，请手动填写密钥文件内容')
    }
  },
  methods: {
    onChange(file) {
      // let fileData = new FormData()
      // fileData.append('file', file.raw)
      // fileData.append('file', file)
      console.log(`output->file`, file)
      this.fileInfo = file
      this.readAsText(file.raw) // 直接赋值文件内容
      this.$emit('input', file.raw)
      this.$emit('change')
    },
    delFile() {
      this.fileInfo = null
      this.$emit('update:inputValue', '')
      this.$emit('input', null)
      this.$emit('change')
    },
    readAsText(file) {
      var reader = new FileReader()
      // 将文件以文本形式读入
      if (this.base64) {
        reader.readAsDataURL(file) // base64
      } else {
        reader.readAsText(file) // 原内容
      }
      reader.onload = (f) => {
        if (this.base64) {
          this.$emit('update:inputValue', reader.result.split(',')[1])
        } else {
          this.$emit('update:inputValue', reader.result)
        }
      }
    },
    beforeUpload(file) {
      // 校检文件大小
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize
        if (!isLt) {
          this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`)
          return Promise.reject()
        }
      }
      return Promise.resolve()
    }
  }
}
</script>

<style lang="scss" scoped>
.file-list {
  display: flex;
  justify-content: space-between;

  /deep/ .el-icon-delete {
    cursor: pointer;
  }
}

.upload-demo {
  /deep/ .el-upload {
    margin-top: 3px;
  }
}

.btn {
  color: #246cff;
  border-color: #246cff;
}
</style>
