<template>
  <div>
    <h3>PCT槁转CN稿</h3>
    <el-alert
      title="此功能将协助您将PCT稿快速转换成CN稿的排版"
      type="info"
    />
    <br>
    <el-form ref="searchForm" size="small" label-width="160px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="PCT稿" prop="business">
            <el-upload
              ref="upload"
              class="upload-demo"
              drag
              :limit="1"
              :file-list="fileList"
              :action="uploadURL"
              :on-change="handelFileChange"
              :on-remove="handleFileRemove"
              :on-exceed="handleExceed"
              :auto-upload="false"
              accept="application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
            >
              <i class="el-icon-upload" />
              <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em>
              </div>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" :offset="10">
          <el-button
            style="margin-left: 10px"
            size="small"
            type="success"
            @click="submitUpload"
          >
            开始转换
          </el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>
<script>
import GraphApiService from '@utils/GraphApiService'

export default {
  name: 'Cn2CpcForm',
  data: function() {
    return {
      uploadURL: 'Word/CN2CPC',
      fileList: []
    }
  },
  props:{
    baseUrl:{
      type: String
    }
  },
  methods: {
    // 上传到服务器
    submitUpload() {
      console.log(this.fileList)
      if (this.fileList.length <= 0) {
        this.$message.error('请先选择需要上传的文件！')
        return false
      }
      const formData = new FormData()
      this.fileList.forEach(e => {
        formData.append('file', e.raw)
      })
      GraphApiService
        .post('Word/PCT2CN', formData)
        .then(res => {
          if (res.status === 200) {
            this.fileList = []
            this.$refs.upload.clearFiles()
            const excelFileName = res.data
            GraphApiService
              .get('RequestPayment/DownloadFile', {
                params: {
                  fileName: excelFileName
                },
                responseType: 'blob'
              })
              .then(response => {
                const blob = new Blob([response])
                const downloadElement = document.createElement('a')
                const href = window.URL.createObjectURL(blob)
                downloadElement.href = href
                downloadElement.download = excelFileName.split('/')[1]
                document.body.appendChild(downloadElement)
                downloadElement.click()
                document.body.removeChild(downloadElement)
                window.URL.revokeObjectURL(href)
              })
          } else {
            this.$refs.upload.abort()
            this.$message.error('下载档案失败!')
          }
          console.log(res.data)
        })
        .catch(error => {
          console.log('error', error)
          this.$refs.upload.abort()
          this.$message.error('下载档案失败!')
        })
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    handelFileChange(file, fileList) {
      // 存在文件标识
      let existsFileFlag = false

      for (let i = 0; i < this.fileList.length; i++) {
        if (
          file.name === this.fileList[i].name &&
          file.size === this.fileList[i].size
        ) {
          // 如果存在了，赋值true
          existsFileFlag = true
        }
      }
      // 遍历的这个文件存在当前列表直接结束
      if (existsFileFlag) {
        // 否则不加入
        fileList.pop()
        // console.log(`文件已经存在：${file.name}`)
        // this.handleMsg(`文件已经选择过了：${file.name})`);
        this.$message({
          showClose: true,
          message: `文件已经选择过了：${file.name})`,
          type: 'error'
        })
        return
      }
      this.fileList.push(file)
    },
    handelDetailFileChange(file, fileList) {
      // 存在文件标识
      let existsFileFlag = false

      for (let i = 0; i < this.detailFileList.length; i++) {
        if (
          file.name === this.detailFileList[i].name &&
          file.size === this.detailFileList[i].size
        ) {
          // 如果存在了，赋值true
          existsFileFlag = true
        }
      }
      // 遍历的这个文件存在当前列表直接结束
      if (existsFileFlag) {
        // 否则不加入
        fileList.pop()
        // console.log(`文件已经存在：${file.name}`)
        // this.handleMsg(`文件已经选择过了：${file.name})`);
        this.$message({
          showClose: true,
          message: `文件已经选择过了：${file.name})`,
          type: 'error'
        })
        return
      }
      this.detailFileList.push(file)
    },
    // 文件列表移除文件时的钩子
    handleFileRemove(file, fileList) {
      this.fileList = fileList
    },
    handleDetailFileRemove(file, fileList) {
      this.detailFileList = fileList
    },
    handleExceed(files, fileList) {
      this.$set(fileList[0], 'raw', files[0])
      this.$set(fileList[0], 'name', files[0].name)
      this.$refs['rebateUpload'].clearFiles()// 清除文件
      this.$refs['rebateUpload'].handleStart(files[0])// 选择文件后的赋值方法
    }
  }
}
</script>
