<template>
  <div>
    <el-dialog title="上传附加词典" class="upload-attach-dic-dlg" :visible.sync="isShow" @open="beforeDialogOpen">
      <el-form ref="form" label-width="25%">
        <el-form-item label="文件：">
          <el-upload
            class="upload-additional-dic" ref="upload"
            action=""
            :limit="1"
            :file-list="fileList"
            :multiple="false"
            :http-request="fileUploadSuccessHandler"
            :before-upload="beforeFileUpload"
            :on-change="selectFileChangeHandler"
            accept=".dic">
            <el-button slot="trigger" type="primary">选取文件</el-button>
            <div slot="tip" class="el-upload__tip">
                请选择您要上传的词典(utf8字符集)：<br>上传文件只能是dic格式</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-checkbox label="覆盖同名文件" disabled v-model="coverFlag"></el-checkbox>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>

import util from '@src/common/util.js'
export default {
  computed: {
    isShow: {
      get() {
        return this.show
      },
      set(val) {
        this.$emit('update:show', val)
      }
    }
  },
  props: {show: Boolean},
  data() {
    return {
      coverFlag: true, //  覆盖同名文件
      fileList: [] //   导入附加词典临时变量
    }
  },
  methods: {
    beforeDialogOpen() {},
    // 上传文件
    async fileUploadSuccessHandler(event) {
      if (!this.fileList.length) {
        this.$emit('dialog', '请选择文件')
        return
      }
      if (!this.beforeFileUpload(this.fileList[0])) {
        return
      }
      const { file, onProgress } = event
      const formData = new FormData()
      formData.append('file', file)
      try {
        let res = await axios.post(
          '/ui/attachmentdic/upload',
          formData,
          event => {
            onProgress(event, file)
          },
          {
            headers: { 'Content-Type': 'multipart/form-data' }
          }
        )
        util.showMessage(res)
        if (res.data.status === 1) {
          this.fileList = []
          this.$emit('update:show', false)
          this.$emit('callback')
        }
      } catch (e) {
        // util.showErrorNotification(e)

      }
    },
    selectFileChangeHandler(file, files) {
      if (!this.beforeFileUpload(file)) {
        return
      }
      this.fileList = files.slice(-1)
    },
    // 检查上传附加词典的文件类型
    beforeFileUpload(file) {
      const isDic = file.name.lastIndexOf('dic') === -1
      if (isDic) {
        this.$emit('dialog', '上传文件只能是dic格式')
      }
      return !isDic
    }
  },
  components: {}
}
</script>
<style>
.upload-attach-dic-dlg .el-dialog{
  width:400px;
}
@media (max-width:480px){
  .upload-attach-dic-dlg .el-dialog{
    width:96%;
  }
}
</style>
