<template>
  <div>
    <!--带文件上传的Dialog-->
    <el-dialog title="上传文件" :visible.sync="uploadFileDialogVisible" size="tiny" @close="uploadFileDialogCloseHandler">
      <div v-loading="uploadFileDialogLoading" style="text-align: center;">
        <div class="el-upload__tip" style="margin-bottom: 10px;"><em style="color: red;">注</em>：请检查文件名称,如果文件名称中包含中文,将会导致文件在UNIX,LINX系统中显示异常.</div>
        <el-upload
            ref="uploadFile"
            action=""
            class="upload-demo"
            :http-request="fileUploadHandler"
            :accept="acceptFileType"
            :on-remove="uploaderRemoveHandler"
            :on-change="uploaderChangeHandler"
            :on-success="uploadFileSuccessHandler"
            :on-error="uploadFileErrorHandler"
            :before-upload="beforeUploadFileHandler"
            :file-list="fileList"
            :auto-upload="false"
            >
          <el-row :gutter="3">
            <el-col :span="4">
              <label>文件：</label>
            </el-col>
            <el-col :span="16">
              <el-input disabled v-model="acceptFileType"></el-input>
            </el-col>
            <el-col :span="4">
              <el-button type="primary">选择文件</el-button>
            </el-col>
          </el-row>
          <div slot="tip" class="el-upload__tip">
            <el-checkbox v-model="uploadFileForm.autoUnzip" :checked="uploadFileForm.autoUnzip" @change="autoUnzipChangeHandler">批量上传模式（压缩文件自动解压缩）</el-checkbox>
          </div>
        </el-upload>
        <el-progress :percentage="progressInfo.percent" v-show="progressInfo.visible"></el-progress>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doFileUpload" :loading="btnLoading">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import util from '@src/common/util.js'

export default {
  data() {
    return {
      uploadFileDialogVisible: false,
      uploadFileDialogLoading: false,
      allowUploadType: [], // 允许上传的文件类型
      acceptFileType: '',
      fileList: [],
      uploadFileForm: {
        name: '',
        size: 0,
        lastModifiedDate: null,
        path: '',
        autoUnzip: true,
        type: ''
      }, // 上传文件表单
      inputParams: {
        platformID: '',
        siteID: '',
        platformPath: '',
        currentFilePath: ''
      },
      progressInfo: {
        visible: false,
        percent: 0
      },
      btnLoading: false
    }
  },
  methods: {
    initDialog(params) {
      !util.isEmptyObject(params) && Object.assign(this.inputParams, params)
      this.uploadFileDialogVisible = true
      this.uploadFileForm.autoUnzip = true
      if (!this.allowUploadType.length || !this.acceptFileType) {
        this.loadAllowtTypes()
      }
      this.progressInfo = {
        visible: false,
        percent: 0
      }
      this.btnLoading = false
    },

    // 加载允许上传的文件类型
    async loadAllowtTypes() {
      this.uploadFileDialogLoading = true
      let res = await axios.get('/ui/core/file/initallowtypes')
      let data = res.data
      if (data.status === 1) {
        this.allowUploadType = data.data.allowedtypes.split(',')
        this.acceptFileType = '.' + this.allowUploadType.join(',.')
      }
      this.uploadFileDialogLoading = false
    },

    // 文件上传Dialog关闭事件
    uploadFileDialogCloseHandler() {
      // this.MsgPop("取消上传 ！");
      this.$refs.uploadFile.abort()
      this.$refs.uploadFile.clearFiles()
    },

    // 文件上传onchange事件
    uploaderChangeHandler(file, fileList) {
    //  console.log(file fileList)
    },

    // 文件上传onremove事件
    uploaderRemoveHandler(file, fileList) {
    //  console.log(file fileList)
    },

    // 文件上传成功后处理事件
    uploadFileSuccessHandler(response, file, fileList) {
      this.MsgPop('上传成功 ！', 'success')
      this.uploadFileDialogVisible = false
      this.$emit('success')
    },

    // 文件上传出错后处理事件
    uploadFileErrorHandler(err, file, fileList) {
      this.Dialog(err)
      return false
    },

    // 文件上传前处理事件
    beforeUploadFileHandler(file) {
      let ext = file.name.substring(file.name.lastIndexOf('.') + 1)
      let flag = false
      for (var types of this.allowUploadType) {
        if (types.toLowerCase() === ext.toLowerCase()) {
          flag = true
          break
        }
      }
      this.uploadFileForm.type = ext
      this.uploadFileForm.lastModifiedDate = file.lastModifiedDate
      this.uploadFileForm.size = file.size
      this.uploadFileForm.name = file.name
      if (!flag) {
        this.Dialog('不支持后缀名为 ' + ext + ' 的文件 ！')
        this.$refs.uploadFile.clearFiles()
        return false
      }
      return true
    },

    doUploadFile(formData, onUploadProgress) {
      let progressInfo = this.progressInfo
      progressInfo.visible = true
      this.btnLoading = true
      return axios
        .post('/ui/core/file/upload', formData, {
          onUploadProgress: function(e, file) {
          // console.log(e)

            let total = e.total - 0
            let loaded = e.loaded - 0
            progressInfo.percent = total === loaded ? 100 : (loaded / total * 100).toFixed() - 0
          },
          timeout: 6000000,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        .then(res => res.data)
    },

    // 文件上传
    fileUploadHandler(event) {
      const { file, onSuccess, onProgress, onError } = event
      const formData = new FormData()
      formData.append('file', file)
      formData.append('path', this.inputParams.currentFilePath)
      formData.append('autounzip', this.uploadFileForm.autoUnzip ? 'Y' : 'N')
      formData.append('siteID', this.inputParams.siteID)
      formData.append('platformID', this.inputParams.platformID)

      this.doUploadFile(formData, event => {
        onProgress(event, file)
      })
        .then(data => {
          onSuccess(data)
        })
        .catch(e => {
          onError(e)
        })
    },

    // 确认上传文件
    doFileUpload() {
      this.$refs.uploadFile.submit()
    },

    // 文件上传Dialog中checkBox改变事件
    autoUnzipChangeHandler(e) {
    // console.log(e)
    },

    // 消息Dialog封装
    Dialog(msg) {
      this.$confirm(msg, '系统提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning'
      })
    },

    // 消息显示封装
    MsgPop(msg, type) {
      if (!type) {
        this.$message(msg)
        return
      }
      this.$message({
        message: msg,
        type: type
      })
    }
  }
}
</script>
