<template>
  <div>
    <h3>华星请款单(横表)</h3>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="业务量表" name="first">
        <el-form ref="searchForm" size="small" label-width="160px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="合同号" prop="agent_date">
                <el-input
                  v-model="contractNumber"
                  placeholder="HETONG-1901306-10F074"
                />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="明细表" prop="detail">
                <el-upload
                  class="upload-demo"
                  drag
                  :file-list="detailFileList"
                  :action="uploadURL"
                  :on-change="handelDetailFileChange"
                  :on-remove="handleDetailFileRemove"
                  :auto-upload="false"
                  accept=".xls, .xlsx"
                  multiple
                >
                  <i class="el-icon-upload" />
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                  <div slot="tip" class="el-upload__tip">
                    只能上传xls/xlsx文件
                    <br>
                    档案名称请加上QK号并用-分隔,
                    例如QK2021016093-翼盛202012127-深圳华星（授权）明细表
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="业务量表" prop="business">
                <el-upload
                  class="upload-demo"
                  drag
                  :file-list="fileList"
                  :action="uploadURL"
                  :on-change="handelFileChange"
                  :on-remove="handleFileRemove"
                  :auto-upload="false"
                  accept=".xls, .xlsx"
                  multiple
                >
                  <i class="el-icon-upload" />
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                  <div slot="tip" class="el-upload__tip">
                    只能上传xls/xlsx文件<br>
                    档案名称请加上QK号并用-分隔,
                    例如QK2021016093-翼盛202012127-深圳华星（授权）业务量表
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24" :offset="10">
              <el-button
                style="margin-left: 10px"
                size="small"
                type="success"
                @click="submitUpload"
              >
                上传到服务器
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="开帐单" name="second">
        <el-form ref="submitForm" size="small" label-width="160px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="明细表" prop="detail">
                <el-upload
                  class="upload-demo"
                  drag
                  :file-list="detailFileList2"
                  :action="uploadURL2"
                  :on-change="handelDetail2FileChange"
                  :on-remove="handleDetail2FileRemove"
                  :auto-upload="false"
                  accept=".xls, .xlsx"
                  multiple
                >
                  <i class="el-icon-upload" />
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                  <div slot="tip" class="el-upload__tip">
                    只能上传xls/xlsx文件
                    <br>
                    档案名称请加上QK号并用-分隔,
                    例如QK2021016093-翼盛202012127-深圳华星（授权）明细表
                  </div>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="24" :offset="10">
              <el-button
                style="margin-left: 10px"
                size="small"
                type="success"
                @click="submitUpload2"
              >
                上传到服务器
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {
  createHxRequestPaymentVerticalTotal,
  createHxRequestPaymentVerticalTotal2,
  downloadFile
}
from '@api/uploadApi'
import moment from 'moment'
export default {
  name: 'upload',
  props:{
    baseUrl:{
      type: String,
      default: 'prod_sz'
    }
  },
  data: function() {
    return {
      activeName: 'first',
      projectName: '',
      uploadURL: 'RequestPayment/ChangeHXRequestPaymentVerticalTotal',
      uploadURL2: 'RequestPayment/ChangeHXRequestPaymentVerticalTotal2',
      fileList: [], // 上传的業務量文件列表
      detailFileList: [], // 上传的詳細文件列表
      detailFileList2: [],
      contractNumber: '',
      createMonth: ''
    }
  },
  created() {
    // eslint-disable-next-line no-undef
    this.createMonth = moment().format('YYYY年MM月')
  },
  methods: {
    handleClick(tab) {
      this.activeName = tab.name
    },
    // 上传到服务器
    async  submitUpload() {
      console.log(this.fileList)
      if (this.fileList.length <= 0) {
        this.$message.error('请先选择需要上传的文件！')
        return false
      }
      let excelFileName = ''
      const formData = new FormData()
      if (!this.contractNumber || this.contractNumber === '') {
        this.$message.error('请输入合同号')
        return false
      }
      formData.append('contractNumber', this.contractNumber)
      this.fileList.forEach(e => {
        formData.append('fileList', e.raw)
      })
      this.detailFileList.forEach(e => {
        formData.append('detailFileList', e.raw)
      })
      const res = await createHxRequestPaymentVerticalTotal(this.baseUrl, formData)
      if (res.status === 200) {
        excelFileName = res.data
        const response = downloadFile(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.$message.error('下载档案失败!')
      }
      console.log(res.data)
    },
    async submitUpload2() {
      console.log(this.detailFileList2)
      if (this.detailFileList2.length <= 0) {
        this.$message.error('请先选择需要上传的文件！')
        return false
      }
      let excelFileName = ''
      const formData = new FormData()
      this.detailFileList2.forEach(e => {
        formData.append('detailFileList', e.raw)
      })
      const res = await createHxRequestPaymentVerticalTotal2(this.baseUrl,formData)
      if (res.status === 200) {
        excelFileName = res.data
        const response = downloadFile(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.$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)
    },
    handelDetail2FileChange(file, fileList) {
      // 存在文件标识
      let existsFileFlag = false

      for (let i = 0; i < this.detailFileList2.length; i++) {
        if (
          file.name === this.detailFileList2[i].name &&
          file.size === this.detailFileList2[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.detailFileList2.push(file)
    },
    // 文件列表移除文件时的钩子
    handleFileRemove(file, fileList) {
      this.fileList = fileList
    },
    handleDetailFileRemove(file, fileList) {
      this.detailFileList = fileList
    },
    handleDetail2FileRemove(file, fileList) {
      this.detailFileList2 = fileList
    }
  }
}
</script>
