<template>
  <div>
    <el-form ref="searchForm" size="small" label-width="160px">
      <el-form-item prop="business">
        <el-upload
          ref="upload"
          drag
          :limit="1"
          :file-list="fileList"
          :action="uploadURL"
          :on-change="handelFileChange"
          :on-remove="handleFileRemove"
          :on-exceed="handleExceed"
          :auto-upload="false"
          accept=".docx, .doc"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            将文件拖到此处，或<em>点击上传</em>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <span>申請類型</span>
        <el-radio-group v-model="form.applyType">
          <el-radio label="1">發明</el-radio>
          <el-radio label="2">新型</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item class="split-style">
        <span>分割方式</span>
        <el-radio-group v-model="form.split">
          <el-radio label="splitAccording">按照標題拆分</el-radio>
          <el-radio label="pageNum">選擇自訂頁數</el-radio>
        </el-radio-group>
        <div v-show="form.split === 'pageNum'" class="choose-box">
          <div v-for="(item, i) in inpFields" :key="item.label">
            <span>{{ item.label }}</span>
            <input
              v-model="form[`${item.field}`]"
              :placeholder="`${item.placeholder}`"
              :disabled="i !== editInpIndex && editInpIndex !== -1"
              @input="onInput($event, i)"
            >
          </div>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button
          size="medium"
          type="primary"
          @click="handleSplitClick"
          :disabled="startSplit"
        >
          分割
        </el-button>
        <el-button
          v-if="showDownload"
          size="medium"
          type="primary"
          @click="handleDownloadClick"
        >
          下載
        </el-button>
      </el-form-item>
    </el-form>
    <el-alert type="error">
      <template slot="title">
        注意: 切割的最後一頁 要加 分節符號且不可和文字同行
        <br>
        <h3><b>正確</b></h3>
        <img src="../picture/success.png" width="60%">
        <h3><b>錯誤</b></h3>
        <img src="../picture/error.png" width="60%">
      </template>
    </el-alert>
  </div>
</template>
<script>
import { SplitRevisionDoc} from '@api/fileApi'
import { downloadFile } from '@api/graphApi'
export default {
  name: 'SplitWordForm',
  props:{
    baseUrl:{
      type: String
    }
  },
  data: function() {
    return {
      uploadURL: 'Word/SplitRevisionDoc',
      fileList: [],
      showDownload:false,
      startSplit: false,
      form: {
        applyType: '1',
        split: 'splitAccording',
        abstPageRange: '',
        specPageRange: '',
        claimPageRange: '',
        figPageRange: ''
      },
      disabled: {
        1: false,
        2: false,
        3: false,
        4: false
      },
      showPage: false,
      inpFields: [
        {
          label: 'ABST',
          field: 'abstPageRange',
          placeholder: '請輸入頁數如: 1-10'
        },
        {
          label: 'SPEC',
          field: 'specPageRange',
          placeholder: '請輸入頁數如: 11-20'
        },
        {
          label: 'CLAIM',
          field: 'claimPageRange',
          placeholder: '請輸入頁數如: 21-30'
        },
        {
          label: 'FIG',
          field: 'figPageRange',
          placeholder: '請輸入頁數如: 31-40'
        }
      ],
      editInpIndex: -1

    }
  },
  watch: {
    'form.split'(val) {
      if (val === 'splitAccording') {
        this.form.abstPageRange = ''
        this.form.specPageRange = ''
        this.form.claimPageRange = ''
        this.form.figPageRange = ''
      }
    }

  },
  methods: {
    onInput(e, i) {
      if (e.target.value) {
        this.editInpIndex = i
      } else {
        this.editInpIndex = -1
      }
    },
    async handleSplitClick() {
      this.startSplit = true
      if (this.fileList.length <= 0) {
        this.$message.error('请先选择需要上传的文件！')
        return false
      }
      const formData = new FormData()
      const { form } = this
      formData.append('file', this.fileList[0].raw)
      formData.append('applyType', form.applyType)
      formData.append('abstPageRange', form.abstPageRange)
      formData.append('specPageRange', form.specPageRange)
      formData.append('claimPageRange', form.claimPageRange)
      formData.append('figPageRange', form.figPageRange)
      this.response = await SplitRevisionDoc(this.baseUrl, formData)
      if (this.response.status === 200) {
        this.showDownload = true
      }
      this.startSplit = false
    },
    // 點擊下載按鈕
    handleDownloadClick() {
      if (this.response.status === 200) {
        this.fileList = []
        this.$refs.upload.clearFiles()
        const zipFileName = this.response.data
        this.downloadFile(zipFileName)
        this.showDownload = false
      } else {
        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])// 选择文件后的赋值方法
    },
    async downloadFile(zipFileName) {
      try {
        const formData = new FormData()
        formData.append('fileName', zipFileName)
        const response = await downloadFile(this.baseUrl, formData)
        if (response) {
          const blob = new Blob([response])
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob)
          downloadElement.href = href
          downloadElement.download = zipFileName.split('\\').pop().split('/').pop()
          document.body.appendChild(downloadElement)
          downloadElement.click()
          document.body.removeChild(downloadElement)
          window.URL.revokeObjectURL(href)
        }
      } catch (error) {
        console.log('error', error)
        this.$refs.upload.abort()
        this.$message.error('下载档案失败!')
      }
    }
  }
}
</script>
<style scoped lang="scss">
.el-form .el-form-item{
  margin: 10px 0;
  .el-radio-group{
    margin-left: 20px;
  }
  input{
    width: 126px;
    margin-left: 10px;
    outline: none;
    border: 0;
    background: #C6C6C6;
  }
}
.choose-box{
  margin-left:200px;
  border: 1px solid #000;
  width: 220px;
  div > span{
    display: inline-block;
    width: 56px;
    text-align: center;
    margin: 10px 5px;
    border: 1px solid #000;
  }
}
input::-webkit-input-placeholder{
  font-size: 12px;
  opacity: 0.8;
}
::v-deep .el-form-item__content{
  line-height: 1.5!important;
  }
</style>
