<!-- 共通模块 上传组件 -->
<template>
  <div>
    <el-upload action
               ref="uploadFile"
               class="upload-demo"
               :disabled="!editable"
               :on-preview="handlePreview"
               :on-remove="handleRemove"
               :on-success="successCallback"
               :before-upload="beforeAvatarUpload"
               :before-remove="beforeRemove"
               :file-list="fileList"
               :auto-upload="autoUpload"
               :show-file-list="showFile"
               list-type="picture"
               :http-request="uploadSectionFile"
               multiple>
      <template v-if="editable">
        <el-button size="small"
                   type="primary">{{
          $t('upload.uploadButton')
        }}</el-button>
        <div slot="tip"
             class="el-upload__tip">
          {{ $t('upload.uploadText01') }}
          <br />
          {{ $t('upload.uploadText02') }}
        </div>
      </template>
    </el-upload>
    <!-- 放大图片 -->
    <div v-show="enlargeShow"
         class="enlarge"
         @click="shutDown">
      <div class="img_box">
        <img v-lazy="zoomInPicture" />
      </div>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
// import { getOssInterimCredentials } from '@/model/procurement/spare'
import { EventBus } from 'base-core-lib'
export default {
  name: 'Upload',
  props: {
    autoUpload: {
      // 表单ID
      type: Boolean,
      default: function () {
        return true
      }
    },
    appendixFileUrls: {
      // 表单ID
      type: Array,
      default: function () {
        return []
      }
    },
    detailId: {
      // 详细ID
      type: String,
      default: function () {
        return null
      }
    },
    modelId: {
      // 模块ID（同步数据用）
      type: String,
      default: function () {
        return null
      }
    },
    editable: {
      // 是否可编辑
      type: Boolean,
      default: function () {
        return true
      }
    },
    procurementName: {
      // 模块名称
      // 是否可编辑
      type: String,
      default: function () {
        return null
      }
    },
    frameName: {
      // 业务(画面)名称
      type: String,
      default: function () {
        return null
      }
    }
  },

  data () {
    return {
      showFile: true, // 是否显示已上传文件列表
      enlargeShow: false,
      zoomInPicture: '',
      fileList: [],
      fileIndex: 0,
      fileOssInfo: null,
      preventUpload: false,
      // eslint-disable-next-line vue/no-reserved-keys
      _appendixId: null,
      message: {}
    }
  },
  created () {
    if (this.appendixFileUrls) {
      this.getFileList()
    } else {
      this.showFile = true
    }
  },
  methods: {
    initUpload () {
      this.showFile = true
      this.enlargeShow = false
      this.zoomInPicture = ''
      this.fileList = []
      this.fileIndex = 0
      this.fileOssInfo = null
      this.preventUpload = false
      this.appendixId = null
      this.message = {}
      this.appendixFileUrls = []
    },
    // 确认上传
    submitUpload (billId, detailId) {
      this.billId = billId
      if (detailId) {
        this.detailId = detailId
      }
    },
    // 自定义文件上传
    uploadSectionFile (param) {
      // let ossInter = null
      // const oldFileName = param.file.name
      // const now = new Date()
      // const year = now.getFullYear()
      // let month = now.getMonth() + 1
      // let date = now.getDate()
      // month = month > 9 ? month.toString() : '0' + month
      // date = date > 9 ? date.toString() : '0' + date
      // // fileName 生成
      // // 生成规则 saas/1/finance/payment/2019/0620/d496c207-16ca-45ce-976d-4982be23571b.txt
      // const fileName = `saas/${localStorage.getItem('ws-pf_tenantId')}/${this.procurementName
      //   }/${this.frameName}/${year}${month}${date}/${oldFileName}`

      // this.fileImage()

      // getOssInterimCredentials().then(response => {
      //   ossInter = response.data
      //   const loading = this.loading()
      //   client(ossInter, Cookies.getJSON('ossAccessConfig'))
      //     .put(fileName, param.file)
      //     .then(result => {
      //       // 关闭遮罩
      //       loading.close()
      //       // 阿里云传输成功
      //       this.fileOssInfo = result
      //       this.fileOssInfo.odName = param.file.name
      //       this.message.fileName = fileName
      //       this.message.fileOssInfo = this.fileOssInfo
      //       this.getFileUrl(this.message.fileName)
      //       this.$emit('getMessage', this.message)
      //       EventBus.$emit('success', this.$t('showMessage.saveSuccessOss'))
      //     })
      // })
    },

    /**
     * 注意 vue的v-bind(语法糖为:)会有延迟，请注意同步问题
     * @isDelay 是否延迟执行，默认延迟执行
     */
    getFileList (isDelay = true) {
      if (isDelay) {
        setTimeout(() => {
          this.getFileList(false)
        })
        return
      }
      // 初始化文件显示
      this.fileList = [] // 重置文件列表数组
      this.appendixId = '' // 重置变量 补丁代码

      const config = Cookies.getJSON('ossAccessConfig')
      if (Array.isArray(this.appendixFileUrls)) {
        for (const i in this.appendixFileUrls) {
          this.getFileUrl(this.appendixFileUrls[i].url)
          const str = this.regFileAfter(this.appendixFileUrls[i].name)

          if (str == 'png' || str == 'gif' || str == 'jpg' || str == 'jpeg') {
            this.appendixFileUrls[i].url =
              'http://' +
              config.bucket +
              '.' +
              config.endpoint +
              '/' +
              this.appendixFileUrls[i].url +
              '?x-oss-process=image/resize,w_100,h_100/quality,q_80'
          } else {
            this.appendixFileUrls[i].url =
              'http://' +
              config.bucket +
              '.' +
              config.endpoint +
              '/' +
              this.appendixFileUrls[i].url
          }
          this.fileList.push(this.appendixFileUrls[i])
        }
      } else {
        /* this.showFile = false*/
        this.getFileUrl(this.appendixFileUrls.url)
        const str = this.regFileAfter(this.appendixFileUrls.name)
        if (str == 'png' || str == 'gif' || str == 'jpg' || str == 'jpeg') {
          this.appendixFileUrls.url =
            'http://' +
            config.bucket +
            '.' +
            config.endpoint +
            '/' +
            this.appendixFileUrls.url +
            '?x-oss-process=image/resize,w_100,h_100/quality,q_80'
        } else {
          this.appendixFileUrls.url =
            'http://' +
            config.bucket +
            '.' +
            config.endpoint +
            '/' +
            this.appendixFileUrls.url
        }

        this.fileList.push(this.appendixFileUrls)
      }

      this.fileIndex = this.fileList.length
      this.fileImage()
    },
    fileImage () {
      this.$nextTick(function () {
        const element = document.getElementsByClassName(
          'el-upload-list__item-name'
        )
        for (const i in element) {
          if (element.item(i) == null) {
            continue
          }
          const fileName = element.item(i).innerText
          element.item(i).title = fileName
          const regFileAfterClass =
            this.regFileAfter(fileName) + ' el-upload-list__item-thumbnail'
          element.item(i).previousSibling.className = regFileAfterClass
        }
      })
    },
    // 某个文件上传成功都会执行该方法
    successCallback (res, file, fileList) {
      if (res.data) {
        this.fileIndex++
      }
      if (fileList.length == this.fileIndex) {
        this.getFileList()
      }
    },
    set appendixId (val) {
      val = (val || '').replace(
        /x-oss-process=image\/resize,w_100,h_100\/quality,q_80/g,
        ''
      )
      this._appendixId = val
    },
    // eslint-disable-next-line vue/no-dupe-keys
    get appendixId () {
      return this._appendixId
    },
    // 上传文件url获取
    getFileUrl (msg) {
      if (!this.appendixId) {
        this.appendixId = msg
      } else {
        this.appendixId = this.appendixId + ',' + msg
      }
    },
    // 上传文件删除
    delFileUrl (msg) {
      if (this.appendixId !== null && this.appendixId !== '') {
        const urlList = this.appendixId.split(',')
        let urlSubStr = ''

        for (const i in urlList) {
          if (urlList[i].indexOf(msg) == -1) {
            if (urlSubStr == '') {
              urlSubStr = urlList[i]
            } else {
              urlSubStr = urlSubStr + ',' + urlList[i]
            }
          }
        }
        this.appendixId = urlSubStr
      } else {
        this.appendixId = ''
      }
    },
    // 文件列表移除文件时的钩子
    handleRemove (file, fileList) {
      if (this.preventUpload) {
        return
      }

      for (const i of fileList) {
        if (this.message.delName) {
          this.message.delName = this.message.delName + ',' + i.name
        } else {
          // 下载
          // window.location.href = file.url
        }
      }
      this.delFileUrl(file.name)
      this.$emit('delMessage', this.message)
      const ids = []
      ids.push(file.id)
      EventBus.$emit('success', this.$t('upload.message01'))
    },
    // 判断文件后缀名
    regFileAfter (item) {
      const d = /\.[^\\.]+$/.exec(item)
      if (d === null || d.length === 0) {
        return 'no'
      }
      return d
        .toString()
        .substring(1)
        .toLowerCase()
    },
    // 点击文件列表中已上传的文件时的钩子 点击附件预览
    handlePreview (file) {
      // 点击附件预览
      // 判断是图片不下载/显示
      const str = this.regFileAfter(file.name)
      if (str == 'png' || str == 'gif' || str == 'jpg' || str == 'jpeg') {
        this.zoomInPicture = (file.url || '').replace(
          /x-oss-process=image\/resize,w_100,h_100\/quality,q_80/g,
          ''
        )
        this.enlargeShow = true
      } else {
        // 下载
        window.location.href = file.url
      }
    },
    // 关闭图片
    shutDown () {
      this.enlargeShow = false
    },
    // 删除文件之前的钩子
    beforeRemove (file, fileList) {
      if (this.preventUpload) {
        return
      }
      return this.$confirm(
        this.$t('upload.message02') +
        `${file.name}` +
        this.$t('common.question')
      )
    },
    // 上传文件之前的钩子 判断文件类型是否合法
    beforeAvatarUpload (file) {
      this.preventUpload = false
      const type = this.regFileAfter(file.name)
      // this.companyId = 1
      // this.billId = 1
      this.fileName = file.name
      // this.modelId = 1
      // this.myData

      // 判断文件类型是否合法jpg、gif、png、xlsx、pdf、xls、doc、docx、jpeg、zip、rar
      if (
        type === 'jpg' ||
        type === 'gif' ||
        type === 'png' ||
        type === 'xlsx' ||
        type === 'pdf' ||
        type === 'xls' ||
        type === 'doc' ||
        type === 'docx' ||
        type === 'jpeg' ||
        type === 'zip' ||
        type === 'rar'
      ) {
        const isLt2M = file.size / 1024 / 1024 < 15
        if (!isLt2M) {
          EventBus.$emit('error', this.$t('upload.message03'))
          this.preventUpload = true
          return false
        }
      } else {
        EventBus.$emit('error', this.$t('upload.message04'))
        this.preventUpload = true
        return false
      }
      if (this.fileNameRepeat(file.name)) {
        EventBus.$emit('error', this.$t('showMessage.saveErrorOssName'))
        this.preventUpload = true
        return false
      }
    },
    // 文件名称重复验证
    fileNameRepeat (fileName) {
      if (this.appendixId != null) {
        const urlList = this.appendixId.split(',')
        for (const i in urlList) {
          if (urlList[i].indexOf(fileName) == -1) {
            return false
          } else {
            return true
          }
        }
      }
    },
    loading () {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
        target: document.querySelector('.div1')
      })
      return loading
    }
  }
}
</script>

<style scoped lang="scss">
.upload-demo {
  overflow: hidden;
}
.el-button--primary {
  border-radius: 20px;
  padding: 0px 25px;
  height: 32px;
}
/deep/ .el-upload-list--picture .el-upload-list__item {
  float: left;
  height: 120px;
  width: 106px !important;
  border: 1px solid #ccc;
  padding: 20px 10px 10px 90px;
  outline: 0;
}
/deep/ .el-upload-list--picture .el-upload-list__item-thumbnail {
  margin-left: -73px;
}
/deep/ .el-icon-document:before {
  opacity: 0;
}
/deep/ .el-upload-list--picture .el-upload-list__item-status-label {
  opacity: 0;
}
.el-upload__tip {
  color: #999;
  padding-left: 10px;
  line-height: 15px;
  margin-top: 0px;
  display: inline-block;
  vertical-align: -webkit-baseline-middle;
  // height: 39px;
}
/* 放大查看上传附件预览图 */
.enlarge {
  position: fixed;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.8);
  width: 100%;
  height: 100%;
  z-index: 1000;
  .img_box {
    padding-top: 8%;
    width: 70%;
    height: 70%;
    margin: 0 auto;
    img {
      display: block;
      margin: 0 auto;
      height: 100%;
      max-width: 100%;
      max-height: 100%;
    }
  }
}
/deep/ .el-icon-close-tip {
  opacity: 0;
}

/deep/ .el-list-leave-active {
  transition: all 0s;
}
/deep/ .el-list-enter-active {
  transition: all 0s;
}
</style>

<style lang="scss" scoped>
.el-upload-list--picture {
  .el-upload-list__item {
    width: 200px !important;
    float: left !important;
    margin: 8px !important;
  }
  .el-upload-list__item-thumbnail {
    background-size: contain;
  }
}
</style>
