<template>
  <el-dialog
    title="文件上传"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="500px">
    <el-form :model="dataForm" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
      <el-form-item label="文件名" prop="name">
        <el-input v-model="dataForm.name" placeholder="文件名"></el-input>
      </el-form-item>
      <el-form-item label="上传">
        <el-upload
          ref="upload"
          :limit="1"
          :before-upload="beforeUpload"
          :auto-upload="false"
          :headers="headers"
          :on-success="handleSuccess"
          :on-error="handleError"
          :action="$baseUrl + '/api/localStorage' + '?name=' + dataForm.name"
        >
          <div class="eladmin-upload"><i class="el-icon-upload" />添加文件</div>
          <div slot="tip" class="el-upload__tip">可上传任意格式文件，且不超过100M</div>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="upload">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    data () {
      return {
        visible: false,
        dataForm: {
          name: ''
        },
        headers: { 'Authorization': 'Bearer ' + this.$cookie.get('token') }
      }
    },
    methods: {
      init (id) {
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
        })
      },
      beforeUpload(file) {
        let isLt2M = true
        isLt2M = file.size / 1024 / 1024 < 100
        if (!isLt2M) {
          this.$message.error('上传文件大小不能超过 100MB!')
        }
        this.dataForm.name = file.name
        return isLt2M
      },
      handleSuccess(response, file, fileList) {
        this.$notify({title: '上传成功',type: 'success'})
        this.$refs.upload.clearFiles()
      },
      handleError(e, file, fileList) {
        const msg = JSON.parse(e.message)
        this.$notify({
          title: msg.message,
          type: 'error',
          duration: 2500
        })
      },
      upload() {
        this.$refs.upload.submit()
        this.visible = false
        this.$emit('refreshDataList')
      }
    }
  }
</script>