<template>
  <div class="ws-autograph">
    <el-upload action="#"
               list-type="picture-card"
               :http-request="_handleRequest"
               :file-list="fileList"
               :before-upload="_handleBeforeUpload"
               :accept="accept"
               :multiple="!limit || parseInt(limit) > 1"
               ref="elUpload">
      <template v-slot:trigger>
        <div ref="triggerDiv">-</div>
      </template>
      <template v-slot:file="{ file }">
        <div class="thumbnail-group">
          <img v-if="isPictureFile(file)"
               style="width: 100%; height: 70px;border-radius:4px;"
               v-lazy="_getFileImg(file)" />
        </div>
        <span class="el-upload-list__item-actions"
              style="width: 100%; height: 70px;border-radius:4px;"
              v-if="file.status == 'success' && (editable || download || preview)">
          <span v-if="isPictureFile(file) && preview"
                class="el-upload-list__item-preview"
                @click="_handlePreview(file)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <span v-if="download && !isPictureFile(file)"
                class="el-upload-list__item-delete"
                @click="_handleDownload(file)">
            <i class="el-icon-view"
               v-if="isOnlineFile(file)"></i>
            <i class="el-icon-download"
               v-else></i>
          </span>
          <span v-if="editable"
                class="el-upload-list__item-delete"
                @click="_handleRemove(file)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </template>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible"
               @closed="_handlePreviewClosed"
               :append-to-body="true">
      <img v-lazy="dialogImageUrl"
           width="100%" />
    </el-dialog>
    <template v-if="editableintm">
      <div class="trigger-group"
           v-if="editable">
      </div>
      <div v-if="editablely">--</div>
    </template>
  </div>
</template>

<script>
import { getFileList, saveFiles } from '@/model/upload'
import { getOssInterimCredentials } from '@/model/procurement/spare'
import { uuid } from '@/utils/assist'
import downloadNow from '../WsDownload/download'
import { EventBus } from 'base-core-lib'
import { mapActions } from 'vuex'
export default {
  name: 'WsAutograph',
  props: {
    appendixId: String,
    editable: {
      // 是否为编辑模式
      type: Boolean,
      default: true
    },
    remarkWord: {
      // 是否有备注要求
      type: Boolean,
      default: true
    },
    preview: {
      // 是否允许预览
      type: Boolean,
      default: true
    },
    download: {
      // 是否允许下载
      type: Boolean,
      default: true
    },
    showName: {
      // 是否显示文件名
      type: Boolean,
      default: true
    },
    limit: {
      // 文件总数量限制
      type: Number,
      default: undefined
    },
    accept: {
      // 限制文件类型
      type: String,
      default:
        '.jpg, .jpeg, .png, .gif, .pdf, .doc, .docx, .xls, .xlsx, .zip, .rar, .eml'
    },
    ossKey: {
      type: String,
      required: true
    },
    compId: {
      // 公司ID
      type: String,
      required: true
    },
    vesselId: {
      // 船舶ID
      type: String,
      required: false
    },
    tableName: {
      // 要保存的表的名字
      type: String,
      required: false
    }
  },
  data () {
    return {
      vesselBankFlag: 'V',
      // vesselBankFlag:
      //   localStorage.getItem('ws-pf_serviceTypeFlag') == 'true' ? 'B' : 'V',
      curFileNum: 0,
      tempFileList: [],
      initFileList: [],
      loading: false, // 是否正在初始化filelsit
      fileList: [],
      removeList: [],
      dialogImageUrl: '',
      dialogVisible: false,
      editableintm: true,
      editablely: false,
      downloadName: '',
      loadingView: '', // loading弹出层
      uploadParams: {
        companyId: this.compId,
        basePath: '' //config.getUploadPath(this.ossKey, this.compId)
      }
    }
  },
  computed: {
    formatTxt () {
      return this.accept
        .replace(/\./g, '')
        .replace(/ /g, '')
        .replace(/,/g, '、 ')
    },
    thisAppendixIds () {
      return this.appendixId
    }
  },
  watch: {
    // 监听props.appendixId, 变化时向服务器请求
    async thisAppendixIds (newV, oldV) {
      if (!this.appendixId && !this.editable) {
        this.editablely = true
      }
      this.getDefaultFiles(newV)
    }
  },
  mounted () {
    this.getDefaultFiles(this.appendixId)
    const handleChange = this.$refs.elUpload.$refs['upload-inner'].handleChange
    this.$refs.elUpload.$refs['upload-inner'].handleChange = ev => {
      this.initFileList = []
      this.curFileNum = ev.target.files.length
      for (let i = 0; i < this.curFileNum; i++) {
        this.initFileList.push(ev.target.files[i])
        this.tempFileList[i] = i
      }
      handleChange(ev)
    }
  },
  methods: {
    ...mapActions('common', ['uploadShipFiles']),
    // 获取图片文件
    _getFileImg (file) {
      if (!file) {
        return ''
      }
      if (this.isPictureFile(file)) {
        this.editableintm = false
        this.editablely = false
        if (file.url.indexOf('blob') === 0 || this.vesselBankFlag === 'V') {
          return file.url
        }
        return file.url + '?x-oss-process=image/resize,w_120,h_120'
      }
      return ''
    },

    async getDefaultFiles (appendixIds) {
      this.fileList = []
      if (appendixIds) {
        this.loading = true
        const list = await this._getFileList(appendixIds)
        this.loading = false
        if (list) {
          this.fileList = list.map((item, idx) => {
            return {
              appendixId: item.appendixId,
              name: item.appendixName,
              url: this.getFilePath(item.appendixPath),
              uid: uuid()
            }
          })
          this.$emit('onChange', this.fileList.length)
        }
      }
    },

    // 处理上传按钮点击
    handleUploadClick () {
      this.$refs.triggerDiv.click()
    },
    // 处理预览
    _handlePreview (file) {
      this.dialogImageUrl = file.url
      this.downloadName = file.name
      this.dialogVisible = true
    },
    // 处理预览关闭
    _handlePreviewClosed () {
      this.dialogImageUrl = ''
      this.downloadName = ''
    },

    // 处理删除
    _handleRemove (file) {
      if (file.appendixId) {
        // 这是要删除已经存在的附件
        const index = this.fileList.findIndex(
          itm => itm.appendixId === file.appendixId
        )
        this.fileList.splice(index, 1)
        this.removeList.push(file.appendixId)
      } else {
        // 这是删除已上传但还未保存的附件
        const index = this.fileList.findIndex(itm => itm.uid === file.uid)
        this.fileList.splice(index, 1)
      }
      this.editableintm = true
      this.$emit('onChange', this.fileList.length)
    },

    // 自定义上传过程
    _handleRequest (param) {
      if (this.vesselBankFlag === 'V') {
        //船端
        this._uploadFilesShip(param)
      }
    },


    async _uploadFilesShip (param) {
      this.loading = true
      const file = param.file
      try {
        const data = await this.uploadShipFiles({
          file: file,
          companyId: this.compId || '',
          modelId: this.isNull(this.tableName)
            ? ''
            : this.tableName.split('_')[0]
        })
        const item = {
          appendixName: data.appendixName,
          appendixPath: data.appendixPath,
          appendixSize: this.toKB(file.size),
          appendixType: localStorage.getItem('ws-pf_serviceTypeFlag') == 'true'
            ? 'B'
            : 'V',
          fromTableName: this.tableName,
          vesselId: this.vesselId,
          uid: file.uid,
          url: this.getFilePath(data.appendixPath),
          name: file.name
        }
        this.$emit('uploadSuccess', item)
        let fileIndex = this.getFileIndex(item.uid)
        if (fileIndex >= 0) {
          this.tempFileList.splice(fileIndex, 1, item)
          this._handleSuccessOnce()
        }
      } catch (error) {
        this.handleError()
      }
    },

    // 处理单个文件上传成功
    _handleSuccessOnce () {
      this.curFileNum--
      if (this.curFileNum === 0) {
        this.fileList.push.apply(
          this.fileList,
          this.tempFileList.filter(item => {
            return !this.isNull(item.uid)
          })
        )
        EventBus.$emit('success', this.$t('showMessage.saveautographOss'))
        this.tempFileList = []
        this.$emit('onChange', this.fileList.length)
      }
    },

    // 处理下载
    _handleDownload (file) {
      downloadNow(file.url, file.name, this.vesselBankFlag)
    },

    _handleBeforeUpload (file) {
      if (file.size > 15 * 1024 * 1024) {
        EventBus.$emit('error', this.$t('showMessage.filesCannot15m'))
        return false
      }
      if (this.limit) {
        let limitFileNum = parseInt(this.limit)
        let currentFileNum = this.fileList.length + this.curFileNum
        if (limitFileNum > 1 && currentFileNum > limitFileNum) {
          this._handleExceed()
          return false
        }
        if (limitFileNum === 1) {
          this.fileList = []
        }
      }
      return true
    },
    //处理文件上传失败
    _handleError () {
      this.curFileNum--
      EventBus.$emit('error', this.$t('showMessage.saveErrorOss'))
    },

    _handleExceed () {
      EventBus.$emit('warning', `最多只能上传${this.limit}个文件`)
    },

    // 传入appendixIds 从服务器获取文件列表信息
    _getFileList (appendixIds) {
      return new Promise(async next => {
        try {
          next(await getFileList({ appendixIds }).toPromise() || [])
        } catch (error) {
          next()
        }
      })
    },

    handleSaveBill () {
      return new Promise((resolve, reject) => {
        const oldAppendixIds = this.removeList.join()
        const newAppendixs = this.fileList
        const params = { newAppendixs, oldAppendixIds }
        saveFiles(params)
          .toPromise()
          .then(res => {
            resolve(res.join())
          })
          .catch(err => {
            EventBus.$emit('error', this.$t('showMessage.saveFilesError'))
            reject()
          })
      })
    },

    // 获取文件样式
    getFileClass (file) {
      const ext = this.getExtName(file.name)
      return 'ext ' + ext
    },
    // 是否为图片
    isPictureFile (file) {
      if (file && file.name) {
        const name = this.getExtName(file.name)
        return (
          name === 'jpg' ||
          name === 'png' ||
          name === 'jpeg' ||
          name === 'gif' ||
          name === 'webp' ||
          name === 'bmp'
        )
      }
      return false
    },
    // 是否为在线打开文件
    isOnlineFile (file) {
      if (file && file.name) {
        const name = this.getExtName(file.name)
        return name === 'pdf' || name === 'tet'
      }
      return false
    },

    getOssInter () {
      return new Promise(async next => {
        try {
          const data = await getOssInterimCredentials().toPromise()
          next(data)
        } catch (error) {
          next()
        }
      })
    },

    getFileIndex (uid) {
      for (let i = 0; i < this.initFileList.length; i++) {
        if (this.initFileList[i].uid === uid) {
          return i
        }
      }
      return -1
    },

    // 显示loading
    showLoading () {
      this.loadingView = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    },
    // 隐藏loading
    hideLoading () {
      this.loadingView.close()
    },
    // 获取后缀名
    getExtName (url) {
      if (!url) {
        return url
      }
      url = url.substr(url.lastIndexOf('.') + 1)
      if (url.indexOf('?') >= 0) {
        url = url.substr(url.indexOf('?'))
      }
      return url
    },
    checkUrl (path) {
      if (path.indexOf('http://') > -1 || path.indexOf('https://') > -1) {
        let pathSplit = path.split('.com/')
        if (pathSplit) {
          path = pathSplit[1]
        }
      }
      return path
    },
    getFilePath (path) {
      // if (this.vesselBankFlag === 'V') {
      //   return (
      //     localStorage.getItem('ws-pf_systemUrl') +
      //     '/static/' +
      //     this.slash(path)
      //   )
      // }
      // return path
      // let sysUrl =  process.env.NODE_ENV === "production"?"http://" + window.location.host+"/":"http://product-dev.winsea.com/";
      let sysUrl = this.$store.getters.baseInfo.fileUrl
      path = this.checkUrl(path)
      // if (this.clientFag === "B") {
      //   // sysUrl+="pb/"
      // }
      return sysUrl + this.slash(path)
    },
    // 字节转KB
    toKB (bt) {
      return (bt / 1024).toFixed(2) + 'KB'
    },

    clearFiles () {
      this.fileList = []
    },
    // 反斜杠转斜杠
    slash (str) {
      return str.replace(/\\/g, '/')
    }
  }
}
</script>

<style lang="scss" scoped>
$picture-hsize: 70px;
$picture-wsize: 100%;
$ctrl-margin-left: 10px;

.ws-autograph {
  width: 100%;
  height: 70px !important;
  margin-bottom: 0px;
  .upload-noramark-btn {
    padding: 0px;
    border: none;
  }
  .trigger-group {
    margin-bottom: 10px;

    .upload-btn {
      display: inline-block;
      border-radius: 4px;
    }
    .tip {
      display: inline-block;
      margin: 0;
      padding: 0;
      font-size: 12px;
      line-height: 17px;
      color: #999;
      margin-bottom: 4px;
      margin-top: 4px;
      vertical-align: middle;
    }
  }
  /deep/ .el-upload-list--picture-card .el-upload-list__item {
    margin: 0 0px 0px 0;
  }
  /deep/ .el-loading-mask {
    height: $picture-hsize;
  }
  /deep/ .thumbnail-group {
    width: $picture-wsize;
    height: $picture-hsize;

    .el-upload-list__item-thumbnail {
      display: block;
      border-radius: 6px;
      border: 1px solid #ccd6e3;
      background-color: #fff;
    }
  }

  /deep/ .el-upload-list__item-actions {
    height: $picture-hsize;
    overflow: hidden;
    border-radius: 6px;
    align-items: center;
    display: flex;
    justify-content: center;
  }

  .fileName {
    font-size: 12px;
    color: #666;
    margin: 0;
    text-align: center;
    margin-top: 4px;
    margin-bottom: 4px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  /deep/
    .el-upload-list--picture-card
    .el-upload-list__item-actions
    span
    + span {
    margin-left: $ctrl-margin-left;
  }

  /deep/ .el-upload.el-upload--picture-card {
    display: none;
  }

  /deep/ .el-upload-list__item {
    width: $picture-wsize;
    height: auto;
    border: 0;
    background: none;
  }

  .ws-upload-progress {
    width: 84%;
    top: 88px;
  }

  .ext {
    background-size: $picture-hsize * 0.7;
    background-repeat: no-repeat;
    background-position: center;
  }
  .doc {
    background-image: url('~@/assets/images/common/upload/doc.png');
  }
  .docx {
    background-image: url('~@/assets/images/common/upload/docx.png');
  }
  .eml {
    background-image: url('~@/assets/images/common/upload/eml.png');
  }
  .pdf {
    background-image: url('~@/assets/images/common/upload/pdf.png');
  }
  .rar {
    background-image: url('~@/assets/images/common/upload/rar.png');
  }
  .xls {
    background-image: url('~@/assets/images/common/upload/xls.png');
  }
  .xlsx {
    background-image: url('~@/assets/images/common/upload/xlsx.png');
  }
  .zip {
    background-image: url('~@/assets/images/common/upload/zip.png');
  }
}

// 取消ele动画
/deep/ .el-list-leave-active {
  transition: all 0s;
}
/deep/ .el-list-enter-active {
  transition: all 0s;
}
.el-button--text {
  color: #666666;
}
.el-button--text:hover {
  color: #4a89f1;
}
.el-button--text:focus {
  color: #ffffff;
}
</style>
