<template>
  <div>
    <h3>公式转换图片</h3>
    <el-alert title="此功能将协助您将CN稿内中的公式快速转换为图像" type="info" />
    <br>
    <el-form ref="visioForm" :model="form" size="small" label-width="160px">
      <el-row>
        <el-col :span="16">
          <el-form-item label="稿件" prop="file">
            <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-form-item label="图像设置" prop="isImgSetting">
            <el-switch
              v-model="form.isImgSetting"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>
          <el-form-item
            v-show="form.isImgSetting"
            label="寬度小于"
            prop="width"
          >
            <el-col :span="4">
              <el-input v-model="form.width" />
            </el-col>
            <el-col :span="3">
              <el-select v-model="form.includeType" placeholder="是否或是高度">
                <el-option label="无" value="无" />
                <el-option label="同时" value="同时" />
                <el-option label="或是" value="或是" />
              </el-select>
            </el-col>
            <el-col v-show="form.includeType !== '无'" :span="2">
              <span>高度小于</span>
            </el-col>
            <el-col v-show="form.includeType !== '无'" :span="2">
              <el-input v-model="form.height" />
            </el-col>
          </el-form-item>
          <el-form-item
            v-show="form.isImgSetting"
            label="放大倍率"
            prop="width"
          >
            <el-col :span="4">
              <el-input v-model="form.magn" />
            </el-col>
            <el-col :span="2">
              <span>倍</span>
            </el-col>
          </el-form-item>
          <el-form-item label="行距设置" prop="isSetLineHeight">
            <el-switch
              v-model="form.isSetLineHeight"
              active-color="#13ce66"
              inactive-color="#ff4949"
            />
          </el-form-item>
          <el-form-item
            v-show="form.isSetLineHeight"
            label="行距"
            prop="lineHeight"
          >
            <el-col :span="4">
              <el-input v-model="form.lineHeight" />
            </el-col>
          </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 {fetchConvertEquations,fetchDownloadFile} from "@api/convertApi"
export default {
  name: 'VisioForm',
  data: function() {
    return {
      form: {
        isImgSetting: true,
        width: 100,
        height: 100,
        magn: 1.8,
        includeType: '无',
        isSetLineHeight: true,
        lineHeight: 18
      },
      uploadURL: 'Word/ConvertEquations',
      fileList: []
    }
  },
  props:{
    baseUrl:{
      type: String
    }
  },
  methods: {
    // 上传到服务器
    async  submitUpload() {
      console.log(this.fileList)
      if (this.fileList.length <= 0) {
        this.$message.error('请先选择需要上传的文件！')
        return false
      }
      window._paq && window._paq.push(['trackEvent', 'Tool', 'Click', '公式转换图片'])
      const formData = new FormData()
      this.fileList.forEach(e => {
        formData.append('file', e.raw)
      })
      formData.append('height', this.form.height)
      formData.append('width', this.form.width)
      formData.append('magn', this.form.magn)
      formData.append('isImgSetting', this.form.isImgSetting)
      formData.append(
        'isIncludeHeight',
        this.form.includeType !== '无'
      )
      formData.append('includeType', this.form.includeType)
      formData.append('isSetLineHeight', this.form.isSetLineHeight)
      formData.append('lineHeight', this.form.lineHeight)
      const res = await fetchConvertEquations(this.baseUrl,formData)
          if (res.status === 200) {
            this.fileList = []
            this.$refs.upload.clearFiles()
            const excelFileName = res.data
            const response = await fetchDownloadFile(this.baseUrl,{fileName: excelFileName})
            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)
    },
    // 文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
    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>
