<template>
  <div>
    <!-- v-if="!imgUrl" -->
    <el-upload
      v-show="!imgUrl"
      class="upload-demo"
      :action="actionUrl"
      :file-list="files"
      :show-file-list="false"
      :headers="header"
      :on-success="success"
      :on-error="error"
      :on-remove="removeFile"
      :before-remove="beforeRemove"
      :accept="accept"
      :disabled="disabled"
      :before-upload="beforeAvatarUpload"
      ref="upload"
      list-type="picture-card"
      :data="updata"
      multiple
    >
      <el-tooltip placement="right" effect="light">
        <div slot="content">
          附件格式支持：{{ accept }} <br />附件大小限制：单个文件不超过50MB
        </div>
        <i slot="default" class="el-icon-plus"></i>
      </el-tooltip>
    </el-upload>
    <div class="el-upload-list el-upload-list--picture-card" v-if="imgUrl">
      <div class="el-upload-list__item is-success">
        <img v-if="imgUrl" :src="imgUrl" width="100%" height="100%" />
        <label class="el-upload-list__item-status-label">
          <i class="el-icon-upload-success el-icon-check"></i>
        </label>
        <span class="el-upload-list__item-actions" style="border-radius: 6px">
          <span class="el-upload-list__item-delete">
            <i class="el-icon-delete" @click="remove"></i>
          </span>
          <span class="el-upload-list__item-delete">
            <i
              class="el-icon-zoom-in"
              @click.stop="handlePictureCardPreview()"
            ></i>
          </span>
        </span>
      </div>
    </div>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="imgUrl" alt />
    </el-dialog>
  </div>
</template>

<script>
import {mapState} from 'vuex'
import basicData from '@/api/basicData.js'
import req from '@/request.js'
export default {
  // props: ['accept', 'fileAction', 'disabled'],
  props: {
    dadToSon: {
      type: Object,
      default: () => {
        return ''
      },
    },
    accept: {
      type: String,
    },
    disabled: {
      type: Boolean,
    },
    fileAction: {
      type: String,
    },
  },
  data() {
    return {
      // limits: this.limit,
      src: '',
      fileId: '',
      fileTree: '',
      iframeSrc: '',
      files: [],
      uploadingFiles: {},
      list: [],
      isChecking: true,
      num: 0,
      imgUrl: '',
      dialogVisible: false,
      updata: {
        sourceId: this.dadToSon.sourceId,
      },
    }
  },
  computed: mapState({
    header: (state) => {
      if (state.login && state.login.currentUser) {
        return {
          Authorization: `Bearer ${state.login.currentUser.token}`,
        }
      }
      return {}
    },
    actionUrl: function () {
      //工程图纸中文件上传
      if (this.fileAction) {
        return window.context.portal + this.fileAction
      } else {
        return window.context.portal + '/bizAccessory/v1/minioWorkOrderUpload'
      }
    },
  }),
  mounted() {
    // let add = []
    // add = this.dadToSon.fileList.map((item) => {
    //   return item.url
    // })
    // this.getUrlByfileId(add)
    // if (!this.limit) {
    //   this.limits = 9999999
    // }
    this.getFiles()
    if (!this.accept) {
      this.accept =
        '.jpg,.jpeg,.png,.bmp,.pdf,.JPG,.JPEG,.PNG,.BMP,.PDF,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.rtf,.txt,.zip,.rar,.vsd,.dwg'
    }
  },
  methods: {
    handlePictureCardPreview() {
      this.dialogVisible = true
    },
    // exceed(file, fileList) {
    //   if (this.limit == 5 && (fileList.length == 5 || file.length > 5)) {
    //     this.$message.warning('正文只能上传一个文件')
    //   }
    // },
    preview(files) {
      var id = files.id
      this.$store.dispatch('menu/onlinePreview', id).then((data) => {
        this.fileId = id
        if (data.result == 'html') {
          this.iframeSrc = window.context.portal + data.pdfUrl
          this.$refs.iframeSrcSearch.handleOpen()
        } else if (data.result == 'txt') {
          this.iframeSrc = window.context.portal + data.TxtUrl
          this.$refs.iframeSrcSearch.handleOpen()
        } else if (data.result == 'picture') {
          this.iframeSrc = window.context.portal + data.currentUrl
          this.$refs.iframeSrcSearch.handleOpen()
        } else if (data.result == 'compress') {
          this.fileTree = JSON.parse(data.fileTree).childList
          this.$refs.fileTreeSearch.handleOpen()
        } else {
          this.src = window.context.portal + data.pdfUrl
          this.$refs.pdfSearch.handleOpen()
        }
      })
    },
    removeFile(file, fileList) {
      console.log(file, fileList, 'fffff')
    },
    remove(file, fileList) {
      this.$refs.upload.clearFiles()
      this.files = []
      this.uploadingFiles = {}
      this.list = []
      this.imgUrl = ''
      this.num = 0
    },
    beforeRemove(file, fileList) {
      console.log(file, 'file')
      if (this.isChecking) {
        return this.$confirm(`确定移除 ${file.name}？`).then(() => {
          this.num = 0
          let value = {}
          if (file.response) {
            value = JSON.parse(file.response.value)
          } else {
            value = file
            value.fileId = file.id
          }
          for (var i = 0; i < this.files.length; i++) {
            if (this.files[i].id == value.fileId) {
              this.files.splice(i, 1) //删除数组某一项
            }
          }
        })
      } else {
        this.num = 0
        let value = {}
        if (file.response) {
          value = JSON.parse(file.response.value)
        } else {
          value = file
          value.fileId = file.id
        }
        for (var i = 0; i < this.files.length; i++) {
          if (this.files[i].id == value.fileId) {
            this.files.splice(i, 1) //删除数组某一项
            delete this.uploadingFiles[Base64.encode(this.files[i].name)]
          }
        }
      }
    },
    error(response, file, fileList) {
      console.log(response, file, fileList, '失败')
      delete this.uploadingFiles[Base64.encode(file.name)]
    },
    success(response, file, fileList) {
      this.$emit('imgUrl', response)
      console.log(response, file, fileList, '成功')
      for (let i = 0; i < fileList.length; i++) {
        delete this.uploadingFiles[Base64.encode(fileList[i].name)]
      }
      if (this.num == 0) {
        this.list = []
        for (let i = 0; i < fileList.length; i++) {
          this.list.push(fileList[i])
        }
      }
      this.num = this.num + 1
      for (let j = 0; j < this.list.length; j++) {
        if (!this.list[j].raw) {
          for (let k = 0; k < fileList.length; k++) {
            if (this.list[j].name == fileList[k].name) {
              fileList.splice(k, 1)
              break
            }
          }
        }
      }
      // console.log(this.num, 'this.num')
      if (this.num == fileList.length) {
        // console.log('执行了')
        for (let n = 0; n < fileList.length; n++) {
          if (fileList[n].response) {
            let value = fileList[n].response
            let arrarFile = {}
            this.getUrlByfileId(response)
            arrarFile.id = value.fileId
            arrarFile.name = value.fileName
            arrarFile.size = value.size
            this.files.push(arrarFile)
          }
        }
        this.$emit('input', JSON.stringify(this.files))
      }
    },
    getUrlByfileId(imgUrl) {
      this.imgUrl = imgUrl
      //   req
      //     .get(
      //       window.context.portal +
      //         '/file/onlinePreviewController/v1/getFileById_' +
      //         id,
      //       'arraybuffer'
      //     )
      //     .then(response => {
      //       let type = response.headers['content-type']
      //       if (type) {
      //         this.imgUrl = window.URL.createObjectURL(
      //           new Blob([response.data], {type: type})
      //         )
      //       } else {
      //         this.imgUrl = window.URL.createObjectURL(new Blob([response.data]))
      //       }
      //     })
    },
    // handleChange(file, fileList) {
    //     if(file.status=="success"){
    //       let value = JSON.parse(file.response.value);
    //       let arrarFile = {};
    //       arrarFile.id = value.fileId;
    //       arrarFile.name = value.fileName;
    //       arrarFile.size = value.size;
    //       this.files.push(arrarFile);
    //       this.$emit("input", JSON.stringify(this.files));
    //     }
    // },
    getFiles() {
      // if (this.files.length == 0) {
      //   return ''
      // } else {
      //   return this.files
      // }
      this.files = this.dadToSon.fileList
    },
    //清除附件
    clearFiles() {
      this.$refs.fileUp.clearFiles()
    },
    setFiles(files) {
      this.files = files
    },
    isFinishUpload() {
      if (JSON.stringify(this.uploadingFiles) != '{}') {
        this.$message.warning('正在上传附件，请稍后！')
        throw '正在上传附件，请稍后！'
      }
    },
    beforeAvatarUpload(file) {
      // 文件类型限制
      const name = file.name ? file.name : ''
      const ext = name
        ? name.substr(name.lastIndexOf('.') + 1, name.length)
        : true
      const isExt = this.accept.indexOf(ext) < 0
      this.isChecking = !isExt
      if (isExt) {
        if (this.accept == 'false') {
          this.$message.error('请配置可上传文件的格式!')
        } else {
          this.$message.error('上传的附件只能是 ' + this.accept + '格式!')
        }
        return !isExt
      }
      this.uploadingFiles[Base64.encode(name)] = 'eror'
    },
  },
}
</script>
<style lang="stylus" scoped>
.upload-demo {
  max-width: 570px;
  margin-top: 5px;
}
</style>
