<template>
  <el-dialog id="upload-dialog" :visible.sync="uploadParams.uploadDialogVisible" :title="uploadParams.uploadDialogTitle">
    <el-form ref="upload-form" :model="form" size="small" label-width="120px">
      <el-form-item label="文件名称">
        <el-input v-model="form.name" />
      </el-form-item>

      <el-form-item label="上传会议文件">
        <el-upload
          ref="fileUpload"
          :action="fileUploadApi +'?name='+ form.name"
          :limit="limit"
          :auto-upload="true"
          :multiple="isMultiple"
          accept=".xlsx,.xls,.doc,.docx,.pdf,.dwg,.dxf,.dwt"
          :before-upload="beforeUpload"
          :on-success="handleSuccess"
          :on-error="handleError"
          :on-preview="handleDownload"
          :on-remove="handleRemoveFile"
          :headers="headers"
          :file-list="fileList"
        >
          <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>
    <div slot="footer" class="dialog-footer">
      <el-button type="text" @click="closeUploadDialog">取消</el-button>
      <el-button :loading="uploadLoading" type="primary" @click="submitUpload">确认</el-button>
    </div>
  </el-dialog>

</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { del, getFiles } from '@/api/tools/localStorage.js'
// import { presenter, header, form, crud } from '@crud/crud'

// const defaultForm = { name: null }
export default {
  // mixins: [presenter(), header(), form(defaultForm), crud()],
  props: {
    uploadParams: {
      type: Object,
      required: true,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      headers: { 'Authorization': getToken() },
      fileIds: [], // 文件列表
      form: { name: '' },
      fileList: this.uploadParams.fileList, // 文件列表
      disabled: this.uploadParams.disabled,
      limit: this.uploadParams.limit, // 可上传个数
      isMultiple: this.uploadParams.isMultiple, // 是否可以多选
      uploadDialogVisible: this.uploadParams.uploadDialogVisible,
      uploadDialogTitle: this.uploadParams.uploadDialogTitle,
      uploadLoading: this.uploadParams.uploadLoading,
      plusVisible: true,
      uploadFiles: ''
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'imagesUploadApi', // 图片上传
      'fileUploadApi' // 文件上传
    ])
  },
  watch: {
    'fileList'() {
      if (this.fileList.length === 0) {
        // this.$emit('callback', '')
        this.uploadFiles = ''
      } else {
        var ids = ''
        for (var i = 0; i < this.fileList.length; i++) {
          var file = this.fileList[i]
          if (ids.length === 0) {
            ids += file.id
          } else {
            ids += ',' + file.id
          }
        }
        if ((!this.uploadParams.fileIds) || (this.uploadParams.fileIds && this.uploadParams.fileIds !== ids)) {
          // this.$emit('callback', ids)
          this.uploadFiles = ids
        }
      }
    },
    'uploadParams.fileIds': {
      handler: function(val, oldVal) {
        if (this.uploadParams.fileIds.length > 0) {
          getFiles(val).then(res => {
            for (var i = 0; i < res.length; i++) {
              this.fileList.push({
                id: res[i].id || res[i].storageId,
                name: res[i].name,
                url: this.baseApi + '/file/' + res[i].type + '/' + res[i].realName
              })
            }
          })
        } else {
          this.fileList = []
        }
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    beforeUpload(file) {
      console.log('开始上传')
      console.log(file)
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 100
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 100MB!')
      }
      this.form.name = file.name
      this.$set(this.form, 'name', file.name)
      console.log('fileName : ' + this.form.name)
      return isLt2M
      // return false
    },
    // 监听上传成功
    handleSuccess(response, file, fileList) {
      console.log('上传成功')
      console.log(response)
      console.log(file)
      console.log(fileList)
      file.id = response.id
      file.url = this.baseApi + '/file/' + response.type + '/' + response.realName
      for (const f of fileList) {
        f.id = f.response.storageId
      }
      this.fileList = fileList
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    },
    handleRemoveFile(file) {
      console.log('删除文件')
      del([file.id || file.storageId]).then(res => {
        this.removeFileListObj(file)
        // this.$refs.fileUpload.handleRemove(file)
      })
    },
    handleDownload(file) {
      console.log(file)
      this.download(file.url, file.name)
    },
    removeFileListObj(file) {
      console.log('移除文件')
      for (var i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].id === file.id) {
          this.fileList.splice(i, 1)
          break
        }
      }
      console.log(this.fileList)
    },
    download(href, name) {
      var eleLink = document.createElement('a')
      eleLink.download = name
      eleLink.href = href
      eleLink.click()
      eleLink.remove()
    },
    closeUploadDialog() {
      this.uploadParams.uploadDialogVisible = false
      this.uploadFiles = ''
      this.fileList = []
    },
    submitUpload() {
      console.log('提交上传文件')
      if (this.uploadFiles === '' || this.uploadFiles === null || this.uploadFiles === undefined) {
        this.$notify({
          title: '请上传需要提交的会议文件',
          type: 'error',
          duration: 2500
        })
        return false
      }
      this.form.name = ''
      this.fileList = []
      // this.uploadParams.uploadDialogVisible = false
      this.$emit('callback', this.uploadFiles)
    }
  }
}
</script>

<style>
</style>
