<template>
  <p-card :title='title'>
    <div v-for='(item,index) in localList' class='upload-box' @click='viewImg(index)'>
      <img v-if='item.isImg' :alt='item.originFileName' :src='item.fileUrl' class='upload-box-img'/>
      <a-icon v-else type='file-text' style='font-size: 40px;color: #e2e2e2;'/>
      <div v-if='type === "add"' class='upload-box-del' @click.stop='delFile(item)'>
        <p-icon :iconStyle='{color:"#ffffff"}' type='delete'/>
      </div>
      <div v-if='type === "view"' class='upload-box-download' @click.stop='downLoadFile(item)'>
        <p-icon :iconStyle='{color:"#ffffff"}' type='download'/>
      </div>
    </div>
    <a-alert v-if='localList.length === 0 && type === "view"' message='暂无附件' type='info' show-icon/>
    <a-upload v-if='type !=="view"' :showUploadList='false' :customRequest='receiveFile'>
      <div class='upload-box plus'>
        <p-icon :type="updateLoading ? 'loading' : 'plus'"/>
        <div class='ant-upload-text'>请上传文件</div>
      </div>
    </a-upload>
  </p-card>
</template>

<script>
import {fileGetFormBiz, fileDelToBiz, uploadFilePipe, downloadFileForOne} from '../api/fileSever'

export default {
  props: {
    type: '',
    editData: {
      type: Object,
      default: () => ({})
    },
    title: '',
    bizType: {
      type: String,
      default: ''
    },
    // 文件服务路径
    directory: {
      type: String,
      default: ''
    },
  },
  data() {
    return {
      updateLoading: false,
      localList: []
    }
  },
  mounted() {
    this.getFiles()
  },
  methods: {
    // 获取文件
    async receiveFile(event) {
      const formData = new FormData()
      formData.append('file', event.file)
      formData.append('directory', this.directory)
      formData.append('storageType', '0')
      formData.append('isFileName', '0')
      this.updateLoading = true
      try {
        const fileForm = {...this.editData, bizType: this.bizType}
        const sysBizRes = await uploadFilePipe(fileForm, formData)
        this.$message.success('上传成功')
        this.getFiles()
      } catch (err) {
        this.$message.error(err)
      } finally {
        this.updateLoading = false
      }
    },
    // 获取远程文件列表
    getFiles() {
      this.updateLoading = true
      const {rqcPassCode, bizId} = this.editData
      const params = {
        bizId,
        bizType: this.bizType,
        pageNum: 1,
        pageSize: 99,
      }
      fileGetFormBiz(params).then(res => {
        if (res.success) {
          this.localList = res.data.list.map(item => {
            const {fileName} = item
            const isImg = /(png|jpg|gif|jpeg|webp|bmp)$/.test(fileName)
            return {...item, isImg}
          })
        } else {
          this.$message.warn(res.message)
        }
      }).finally(() => this.updateLoading = false)
    },
    // 预览
    viewImg(index = 0) {
      const viewItem = this.localList[index]
      if (!viewItem || !viewItem.isImg) return
      this.$viewerApi({
        options: {initialViewIndex: 0},
        images: [viewItem.fileUrl]
      })
    },
    // 删除文件
    delFile(file) {
      console.log(file)
      const {id} = file
      const self = this
      this.$confirm({
        title: `确定是否要删除${file.fileName}?`,
        onOk() {
          return new Promise((resolve, reject) => {
            const params = {
              "includeIds": [
                id
              ]
            }
            fileDelToBiz(params).then(res => {
              if (res.success) {
                self.$message.success(res.message)
                self.$emit('delChange', self.localList.length - 1)
                self.getFiles()
                resolve()
              } else {
                self.$message.warn(res.message)
                resolve()
              }
            }).catch(() => {
              resolve()
            })
          })
        }
      })
    },
    // 下载文件
    downLoadFile(file) {
      const {fileFolderId, id, fileName} = file
      downloadFileForOne({id: fileFolderId}).then(res => {
        if (res?.success === false) {
          this.$message.error('下载失败:' + res?.message)
          return
        }
        let blob = new Blob([res])
        let downloadElement = document.createElement('a')
        let href = window.URL.createObjectURL(blob) //创建下载的链接
        downloadElement.href = href
        downloadElement.download = fileName //下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() //点击下载
        document.body.removeChild(downloadElement) //下载完成移除元素
        window.URL.revokeObjectURL(href) //释放掉blob对象
      }).catch(e => {
        this.$message.error('下载失败:' + e,)
      })
    },
    getList() {
      return this.localList
    }
  }
}
</script>

<style lang='less' scoped>
.upload-box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  width: 100px;
  height: 100px;
  margin-right: 8px;
  margin-bottom: 8px;
  text-align: center;
  vertical-align: top;
  border: 1px dashed #d9d9d9;
  border-radius: 2px;
  float: left;
  overflow: hidden;
  position: relative;

  .upload-box-del {
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    transition: all 200ms;
    background: #ff4d4f;
  }

  .upload-box-download {
    position: absolute;
    top: 0;
    right: 0;
    cursor: pointer;
    transition: all 200ms;
    background: #1890ff;
  }

  .upload-box-img {
    width: 100%;
    height: 100%;
  }

  &.plus {
    cursor: pointer;
  }
}
</style>