<!--
 * @Author: liuzhenlin 461480418@qq.ocm
 * @Date: 2023-01-10 15:03:27
 * @LastEditors: liuzhenlin
 * @LastEditTime: 2023-05-18 15:09:27
 * @Description: file content
 * @FilePath: \订单全流程管理系统\src\views\contract\components\DetailsEnclosure.vue
-->
<template>
  <!-- 附件 -->
  <div class="enclosure-container">
    <el-row class="mb10">
      <el-col class="text-right" :span="24">
        <el-upload
          ref="uploadRef"
          action="#"
          :before-upload="
            (file) => {
              return beforeAvatarUpload(file)
            }
          "
          :file-list="fileList"
          :http-request="uploadrequest">
          <el-button size="mini" type="primary">点击上传</el-button>
          <el-button v-permissions="['business:detail:enclosure:add']" size="mini" type="primary">点击上传</el-button>
        </el-upload>
      </el-col>
    </el-row>
    <el-table border :data="enclosureData" height="calc(100% - 80px)">
      <el-table-column
        v-for="(item, index) in columns"
        :key="index"
        align="center"
        :label="item.label"
        :min-width="item.width"
        :prop="item.prop"
        show-overflow-tooltip>
        <template #default="{ row }">
          <span v-if="item.prop == 'createdTime'">
            {{ parseTime(row.createdTime, '{y}-{m}-{d} {h}:{i}') }}
          </span>
          <span v-else>{{ row[item.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button v-permissions="['business:detail:enclosure:download']" type="text" @click="downFile(scope.row)">
            下载
          </el-button>
          <el-button v-permissions="['business:detail:enclosure:delete']" type="text" @click="handleDel(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog title="编辑" :visible.sync="editVisible" width="300px">
      <el-form ref="editForm" :model="editFiles" :rules="editRules">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="新名称" prop="contractCode">
              <el-input v-model="editFiles.fileName" placeholder="请输入新名称" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer">
        <el-button type="primary" @click="saveEditName">保存</el-button>
        <el-button @click="editVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import axios from 'axios'
  import to from 'await-to-js'
  import enclosureApi from '@/api/proj/business'
  import asyncUploadFile from '@/utils/uploadajax'
  import downloadFileByByte from '@/utils/base64ToFile'

  export default {
    name: 'DetailsEnclosure',
    // props: {
    //   // 项目Id
    //   busId: {
    //     type: Number,
    //     default: 0,
    //   },
    // },
    data() {
      return {
        busId: undefined,

        fileList: [],
        fileSettings: {
          // 文件配置信息
          fileSize: 52428800,
          fileTypes: '.doc,.docx,.zip,.xls,.xlsx,.rar,.jpg,.jpeg,.gif,.png,.jfif,.txt,.pdf',
          pictureSize: 52428800,
          pictureTypes: '.jpg,.jpeg,.gif,.png,.jfif,.txt',
          types: '.doc,.docx,.zip,.xls,.xlsx,.rar,.jpg,.jpeg,.gif,.png,.jfif,.mp4,.txt,.pdf',
          videoSize: 104857600,
          videoType: '.mp4',
        },
        editVisible: false, //编辑
        // 编辑文件
        editFiles: {
          fileName: '',
          id: 0,
        },
        editRules: {
          fileName: [{ required: true, trigger: 'blur', message: '请输入新名称' }],
        },
        enclosureData: [],
        columns: [
          {
            label: '附件名称',
            width: '300px',
            prop: 'fileName',
          },
          {
            label: '上传人',
            width: '60px',
            prop: 'createdName',
          },
          {
            label: '上传时间',
            width: 'auto',
            prop: 'createdTime',
          },
        ],
      }
    },

    mounted() {
      // this.getEnclosureList()
    },

    methods: {
      open(busId) {
        console.log('busId', busId)
        this.busId = busId
        this.getEnclosureList()
      },
      async getEnclosureList() {
        let params = { busId: this.busId }
        const [err, res] = await to(enclosureApi.getBusinessEnclosureList(params))
        if (err) return
        this.enclosureData = res.data
      },
      // 下载
      /**
       * 下载文件以及自定义文件名称
       */
      downFile(row) {
        this.$message.warning('开始下载，请稍后。')
        if (row.fileUrl.startsWith('dingtalk')) {
          this.downDingtalkFile(row)
          return
        }

        let url = row.fileUrl
        let fileName = row.fileName
        const xhr = new XMLHttpRequest()
        xhr.open('GET', url, true)
        xhr.responseType = 'blob' // 通过文件下载url拿到对应的blob对象
        xhr.onload = () => {
          if (xhr.status === 200) {
            let link = document.createElement('a')
            let body = document.querySelector('body')
            link.href = window.URL.createObjectURL(xhr.response)
            link.download = fileName
            link.click()
            this.$message.success('下载成功')
            body.removeChild(link)
            window.URL.revokeObjectURL(link.href)
          }
        }

        xhr.send()
      },
      downDingtalkFile(row) {
        enclosureApi
          .downDingTalkFile({ id: row.id })
          .then((res) => {
            if (res.code == 200) {
              this.$message.success('下载成功')
              downloadFileByByte(res.data, row.fileName)
            }
          })
          .catch((err) => {
            this.$message.error('下载失败')
            console.error(err)
          })
      },
      // 重命名
      rename(id) {
        this.editFiles.id = id
        this.editVisible = true
      },
      // 编辑新名称
      async saveEditName() {
        let params = { ...this.editFiles }
        const [valid] = await to(this.$refs.editForm.validate())
        if (valid == false) return
        const [err, res] = await to(enclosureApi.updateEnclosure(params))
        if (err) return
        if (res.code == 200) this.getEnclosureList()
        else return
        this.editVisible = false
      },

      // 上传图片
      beforeAvatarUpload(file) {
        let flag1 = file.size < this.fileSettings.fileSize
        if (!flag1) {
          this.$message.warning('文件过大，请重新选择！')
          return false
        }
        let flag2 = this.fileSettings.fileTypes.split(',').includes('.' + file.name.split('.').pop())
        if (!flag2) {
          this.$message.warning('文件类型不符合，请重新选择！')
          return false
        }
        return true
      },
      // 上传
      uploadrequest(option) {
        let _this = this
        let url = process.env.VUE_APP_UPLOAD_WEED
        axios
          .post(url)
          .then(function (res) {
            if (res.data && res.data.fid && res.data.fid !== '') {
              option.action = `${process.env.VUE_APP_PROTOCOL}${res.data.publicUrl}/${res.data.fid}`
              let file_name = option.file.name
              let index = file_name.lastIndexOf('.')
              let file_extend = ''
              if (index > 0) {
                // 截取名称中的扩展名
                file_extend = file_name.substr(index + 1)
              }
              let uploadform = {
                fileName: file_name, // 资料名称
                fileSize: option.file.size.toString(), // 资料大小
                fileType: file_extend, // 资料文件类型
                fileUrl: `${process.env.VUE_APP_PROTOCOL}${res.data.publicUrl}/${res.data.fid}`, // 资料存储url
                fileSource: '附件上传',
              }
              asyncUploadFile(option).then(() => {
                let params = Object.assign({ ...uploadform, busId: _this.busId })
                _this.addEnclosure(params)
                // 一秒后删除上传信息
                setTimeout(() => {
                  _this.$refs.uploadRef.clearFiles()
                }, 1000)
              })
            } else {
              _this.$message({
                type: 'warning',
                message: '未上传成功！请刷新界面重新上传！',
              })
            }
          })
          .catch(function () {
            _this.$message({
              type: 'warning',
              message: '未上传成功！请重新上传！',
            })
          })
      },
      // 新增附件接口
      async addEnclosure(params) {
        const [err, res] = await to(enclosureApi.createBusinessEnclosure(params))
        if (err) return
        if (res.code == 200) await this.getEnclosureList()
      },
      // 删除图片
      handleDel(row) {
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            const [err, res] = await to(enclosureApi.deleteBusinessEnclosure({ ids: [row.id] }))
            if (err) return
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功!',
              })
              this.getEnclosureList()
            }
          })
          .catch(() => {})
      },
    },
  }
</script>

<style lang="scss" scoped>
  .enclosure-container {
    height: 100%;
    .mb10 {
      margin-bottom: 10px;
    }
    .collection {
      height: 100%;
      .el-row {
        height: 30px;
      }
    }
    .text-right {
      text-align: right;
    }
  }
</style>
