<template>
  <el-dialog
    title="上传文件"
    append-to-body
    width="478px"
    :close-on-click-modal="false"
    @close="closeHandle"
    :visible.sync="visible">
    <el-upload
      drag
      :action="url"
      :before-upload="beforeUploadHandle"
      :on-success="successHandle"
      multiple
      :file-list="fileList"
      style="text-align: center;">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">预览只支持.jpg、.png、.gif、.pdf格式！</div>
    </el-upload>
  </el-dialog>
</template>

<script>
import {updateOssRef} from '@/api/oss/oss.js'

export default {
  data() {
    return {
      visible: false,
      url: '',
      num: 0,
      successNum: 0,
      fileList: [],
      folder: '系统文件',
      fileMappingDto: {
        fileType: '',
        orderRef1: '',
        orderRef2: '',
        orderRef3: '',
      }
    }
  },
  methods: {
    init(val) {
      this.url = this.$http.adornUrl(`/ftp/file/upload?token=${this.$cookie.get('token_plm')}&folder=` + this.folder)
      this.visible = true
      this.fileMappingDto = val
    },
    // 上传之前
    beforeUploadHandle(file) {
      // if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
      //   this.$message.error('只支持jpg、png、gif格式的图片！')
      //   return false
      // }
      this.num++
    },
    // 上传成功
    successHandle(response, file, fileList) {

      console.log(file)
      this.fileList = fileList
      this.successNum++
      if (response && response.code === 0) {
        if (this.num === this.successNum) {
          // 回写文件的订单属性
          let ossRet = response.ossEntity
          let ossTo = {
            id: ossRet.id,
            fileType: this.fileMappingDto.fileType,
            orderRef1: this.fileMappingDto.orderRef1,
            orderRef2: this.fileMappingDto.orderRef2,
            orderRef3: this.fileMappingDto.orderRef3,
            fileTypeCode: 1,
            fileSuffix: file.name.substring(file.name.indexOf(".")+1),
          }
          updateOssRef(ossTo).then(({data}) => {
            if (data.code == 0) {
              this.$confirm('操作成功, 是否继续操作?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).catch(() => {
                this.visible = false
              })
            }else {
             this.$message.warning('上传失败,请重新上传')
            }
          })
        }
      } else {
        this.$message.error(response.msg)
      }
    },
    // 弹窗关闭时
    closeHandle() {
      this.fileList = []
      this.$emit('refreshDataList')
    }
  }
}
</script>
