<template>
  <div>
      <el-dialog title="敏感词批量导入" :visible.sync="isShow" @open="beforeDialogOpen" @close="beforeDialogClose" class="batch-import-upload-dialog">
            <el-form :model="tmpBadImport" ref="badImportForm" label-width="100px">
              <el-form-item class="bad-notice">
                <span style="color:red">注：</span>
          请检查文件名称，如果文件名称中包含中文，将会导致文件在UNIX，LINX系统中显示异常。
          <br/>支持上传的格式：xls、xlsx ；表格必须有2列：第一列【敏感词】，第二列【替换词】； 表格第一行为列名。
          </el-form-item>
          <el-form-item label="模板下载：">
            <el-button @click="downExcelTemplate" type="success" priv="WordManage.Bad">
              <i class="fa fa-arrow-down"></i>Excel模板文件下载</el-button>
          </el-form-item>
          <el-form-item label="文件：">
            <el-upload
              class="upload-iamge"
              action=""
              ref="upload"
              :http-request="fileUploadHandler"
              :multiple="false"
              :on-change="badImportHandleChange"
              :on-success="fileUploadSuccessHandler"
              :file-list="tmpBadImport.fileList"
              :disabled="tmpBadImport.isShowProgress"
              accept=".xls,.xlsx">
              <el-tag type="gray" class="gray-tags">*.xls,*.xlsx</el-tag>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<!-- :auto-upload="false"-->
              <el-button slot="trigger" type="primary">选取文件</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item >
            <el-checkbox label="覆盖已经存在的敏感词"  v-model="coverChecked" @change="coverFlagChange(coverChecked)"></el-checkbox>
          </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="isShow = false">取 消</el-button>
          <!--  <el-button type="primary" @click="confirmBadImportClick" :loading="badImportHandlerLoading">确 定</el-button> -->
          </div>

          <div class="progress-wrap" v-show="tmpBadImport.isShowProgress">
                <el-progress :text-inside="true" :stroke-width="18" :percentage="tmpBadImport.percentage"></el-progress>
                <p class="progress-text">{{tmpBadImport.text}}</p>
            </div>

      </el-dialog>

      <!--<el-dialog title="正在导入敏感词" :visible.sync="badImportProgressDialog" :before-close="closeBadImportProgressDialog">
        {{badImport.record}}条记录已导入
        <el-progress v-if="badImport.percent === 100" :text-inside="true" :stroke-width="18" :percentage="badImport.percent" status="success"></el-progress>
        <el-progress v-else :text-inside="true" :stroke-width="18" :percentage="badImport.percent"></el-progress>
        <div slot="footer">
          <el-button @click="closeBadImportProgressDialog">关 闭</el-button>
        </div>
      </el-dialog>-->

</div>
</template>

<script>
export default {
  data() {
    return {
      taskID: 0,
      // 敏感词导入是否覆盖已存在的敏感词状态
      coverChecked: true,

      // 对话框加载
      badImportHandlerLoading: false,

      // 敏感词导入进度条对话框
      badImportProgressDialog: false,

      // 敏感词批量导入定义
      tmpBadImport: {
        fileList: [],
        coverFlag: 'Y',
        isShowProgress: false,
        text: '准备中...',
        percentage: 0
      }
    }
  },
  computed: {
    isShow: {
      get() {
        return this.batchImportDialog
      },
      set(val) {
        this.$emit('update:batchImportDialog', val)
      }
    }
  },
  methods: {
    // 文件上传成功时事件
    fileUploadSuccessHandler() {
      this.tmpBadImport.text = '文件上传成功，准备导入...'
      this.tmpBadImport.isShowProgress = true

      let pollingTask = taskID => {
        let fetchInfo = async () => {
          let res = await axios.get(`/ui/framework/longtimetasks/${taskID}`)
          Vue.set(this.tmpBadImport, 'completeFlag', res.data.data.completeFlag)
          // console.log(res.data.data.completeFlag)
          if (res.data.data.completeFlag) {
            this.tmpBadImport.percentage = 100
          } else {
            this.tmpBadImport.percentage = res.data.data.percent
          }
          this.tmpBadImport.text = res.data.data.currentInfo + '...'
        }

        return new Promise(resolve => {
          let intervalId = setInterval(() => {
            fetchInfo()
            if (
              this.tmpBadImport.completeFlag ||
              this.tmpBadImport.percentage === 100
            ) {
              this.isShow = false
              this.$message({
                message: '导人成功！',
                type: 'success'
              })
              this.$emit('callback')
              clearInterval(intervalId)
              resolve()
            }
          }, 1000)
        })
      }
      pollingTask(this.taskID)
    },

    // 自定义上传方式
    async fileUploadHandler(event) {
      const { file } = event
      const formData = new FormData()
      formData.append('file', file)
      formData.append('coverFlag', this.tmpBadImport.coverFlag)
      let res = await axios.post('/ui/badwords/batchupload', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      this.taskID = res.data.dealTaskID
    },

    // 导入时是否覆盖已存在的敏感词事件
    coverFlagChange(val) {
      if (val) {
        this.tmpBadImport.coverFlag = 'Y'
      } else {
        this.tmpBadImport.coverFlag = 'N'
      }
    },

    // 敏感词excel模板下载
    downExcelTemplate() {
      window.open(`${window.location.href.split('app.html')[0]}assets/wordmanage/FileData/demo.xlsx`)
      /*  window.location.href = `ui/badwords/baddownloads?fileName=demo.xlsx` */
    },

    // 敏感词批量导入  文件改变时触发事件
    badImportHandleChange(file, files) {
      this.tmpBadImport.fileList = files.slice(-1)
    },

    // 敏感词批量导入点击确定触发事件
    /*  confirmBadImportClick() {
      if (!this.tmpBadImport.fileList.length) {
        this.$emit('dialog', '请先选取文件')
        return
      }
      // this.fileUploadSuccessHandler(res);
    },

    // 关闭敏感词导入对话框
    closeBadImportProgressDialog() {
      this.badImportProgressDialog = false
      this.isShow = false
      this.tmpBadImport.fileList = []
    }, */

    // 重置清空数据
    beforeDialogOpen() {
      this.tmpBadImport.fileList = []
      this.tmpBadImport.isShowProgress = false
      this.tmpBadImport.percentage = 0
      this.tmpBadImport.text = ''
      this.tmpBadImport.coverFlag = 'Y'
    },
    beforeDialogClose() {
      this.$refs['upload'].clearFiles()
    }
  },
  props: {
    batchImportDialog: {
      type: Boolean,
      required: true,
      default: false
    }
  }
}
</script>

<style>
/* 在一般情况下dialog宽为450像素，在逻辑分辨率480像素以下dialog宽为96% */
.batch-import-upload-dialog .el-dialog {
  width: 450px;
}
@media (max-width: 480px) {
  .batch-import-upload-dialog .el-dialog{
    width: 96%;
  }
}
</style>
<style scoped>
.gray-tags {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 196px;
  height: 28px;
  margin-top: 6px;
  float: left;
}
</style>
