<template>
    <div class="billWay_container">
      <div class="title">
        <el-row>
          <el-col :span="24">
            <div class="top">
              <div class="demo-input-suffix" style="margin-left: 10px;">
                  <el-upload  :action="url" :http-request="importExcel" list-type="text" :show-file-list="false" >
                            <el-button  type="primary">导入参数</el-button>
                             <el-select style="margin-left: 110px;" v-model="formCondition.status" placeholder="交易状态">
                      <el-option
                        v-for="item in tradeStatus"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                </el-select>
                <el-button style="margin-left: 10px;" @click="DownloadTemplate">查询模板下载</el-button>
                </el-upload>

              </div>
               <div class="demo-input-suffix" style="margin-top: 5px;">
               <el-input  placeholder="公司名称" class="input-demo" v-model="formCondition.companyName"></el-input>
                <el-input  placeholder="etc卡号" class="input-demo" v-model="formCondition.cardId"></el-input>
                <el-input  placeholder="税号" class="input-demo" v-model="formCondition.companyReferencenum"></el-input>
                <el-input  placeholder="交易id" class="input-demo" v-model="formCondition.tradeId"></el-input>

              </div>
              <div class="demo-input-suffix" style="margin-top: 5px;margin-left: 10px;">
                 <el-date-picker v-model="formCondition.exTimeBegin" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="交易时间始" end-placeholder="交易时间止"></el-date-picker>
                 <el-date-picker v-model="formCondition.aclTimeBegin" type="datetimerange" value-format="yyyy-MM-dd HH:mm:ss" range-separator="至" start-placeholder="申请开票时间始" end-placeholder="申请开票时间止"></el-date-picker>
                 <el-button type="success" style="margin-left: 1%;" @click="firstLoadData">查询</el-button>
                 <el-button type="success" style="margin-left: 1%;" @click="update">更新</el-button>
                  <el-button type="primary"  @click="exportExcel">导出报表</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- 表格部分 -->
        <template>
        <el-table
          class="table"
          v-loading="loading"
          ref="multipleTable"
          :data="selfcarTrade"
           :height="heightt"

          border
          tooltip-effect="dark" @selection-change="handleSelectionChange">
           <el-table-column
              type="selection"
              width="55">
               </el-table-column>
         <el-table-column
            label="企业编号"
            prop="companyNum"
            show-overflow-tooltip>
          </el-table-column>
           <el-table-column
            prop="companyName"
            label="公司名称"
            show-overflow-tooltip>
          </el-table-column>
           <el-table-column
            prop="companyReferencenum"
            label="公司税号"
            show-overflow-tooltip>
          </el-table-column>
           <el-table-column
            prop="tradeId"
            label="交易Id"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="cardId"
            label="ETC卡号"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="fee"
            label="交易费用"
            show-overflow-tooltip>
            <template slot-scope="scope">
               <span>{{scope.row.fee/100| rounding}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="exTime"
            label="交易时间"
            show-overflow-tooltip>
          </el-table-column>

           <el-table-column
            prop="aclTime"
            label="申请开票时间"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="applId"
            label="申请Id"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="status"
            label="状态"
            show-overflow-tooltip>
             <template slot-scope="scope">
              <span v-if="scope.row.status == 1" style="color: green">待开票</span>
              <span v-else-if="scope.row.status == 2" style="color: red">开票中</span>
              <span v-else-if="scope.row.status == 3" style="color: red">已开票</span>
            </template>
          </el-table-column>
           <el-table-column
            prop="interType"
            label="对接方式"
            show-overflow-tooltip>
             <template slot-scope="scope">
              <span v-if="scope.row.interType == 0">接口</span>
              <span v-if="scope.row.interType == 1">平台</span>
              <span v-if="scope.row.interType == 3">迁移数据</span>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- 分页 -->
      <div class="block">
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="current"
        :page-sizes="[6, 8, 10, 20, 50, 100]"
        :page-size="pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>
      </div>
    </div>
</template>
<script type="text/javascript">
import CsvExportor from 'csv-exportor'
import FileSaver from 'file-saver'
import XLSX from 'xlsx'
export default {
  data() {
    return {
      multipleSelection: [],
      formCondition: {
        status: ``,
        cardId: ``,
        tradeId: ``
      },
      formUserList: {
        'file': ``
      },
      tradeStatus: [{'label': `待开票`, 'value': `1`}, {'label': `开票中`, 'value': `2`}, {'label': `已开票`, 'value': `3`}],
      selfcarTrade: [],
      hightt: `0px`,
      current: 1,
      pagesize: 8,
      total: ``
    }
  },
  created() {
    this.heightt = tableHeight - 90 // eslint-disable-line
    this.loadData()
  },
  filters: {
    rounding(value) {
      return value.toFixed(2)
    }
  },
  methods: {
    firstLoadData() {
      this.current = 1
      this.pagesize = 8
      this.loadData()
    },
    async update() {
      var loading = null
      if (this.multipleSelection.length == 0) {
        loading = this.$loading({
          lock: true,
          text: `全量更新中,速度较慢，请您耐心等待...`,
          spinner: `el-icon-loading`,
          background: `rgba(0, 0, 0, 0.7)`
        })
      };
      const formData = new FormData()
      formData.append(`selfCarTradesStr`, JSON.stringify(this.multipleSelection))
      const response = await this.$http.post(`selfCar/updateTrades`, formData)
      if (this.multipleSelection.length == 0) {
        loading.close()
      };
      this.loadData()
      this.$message({
        type: `success`,
        message: `更新成功`
      })
    },
    // 列表展示
    async loadData() {
      const formData = new FormData()
      formData.append(`current`, this.current)
      formData.append(`size`, this.pagesize)
      for (var i in this.formCondition) {
        formData.append(i, this.formCondition[i])
      }
      const response = await this.$http.post(`selfCar/findTrades`, formData)
      if (response.data.code == 0) {
        this.selfcarTrade = response.data.data.records
        this.total = response.data.data.total
      }
    },
    importExcel(content) {
      const file = content.file
      // let file = file.files[0] // 使用传统的input方法需要加上这一步
      const filename = file.name
      if (!filename || typeof filename != `string`) {
        this.$message(`格式错误！请重新选择`)
        return
      }
      let a = filename.split(``).reverse().join(``)
      let types = a.substring(0, a.search(/\./)).split(``).reverse().join(``)

      const fileType = [`xlsx`, `xlc`, `xlm`, `xls`, `xlt`, `xlw`, `csv`].some((item) => { return item === types })
      if (!fileType) {
        this.$message(fileType + `格式错误！请重新选择xlsx格式`)
        return
      }
      this.file2Xce(file).then((tabJson) => {
        var tradeIds = ``
        var etcIds = ``
        if (tabJson && tabJson.length > 0) {
          this.xlsxJson = tabJson
          this.fileList = this.xlsxJson[0].sheet
          let n = `匹配的字段`
          var i = 0
          var j = 0
          this.fileList.forEach((item, index, arr) => {
            if (item[`etc卡号`] != null && item[`etc卡号`] != `` && typeof item[`etc卡号`] != `undefined`) {
              etcIds += item[`etc卡号`].trim() + `,`
              i++
            } else {
              etcIds += `#,`
            }
            if (item[`交易id`] != null && item[`交易id`] != `` && typeof item[`交易id`] != `undefined`) {
              tradeIds += item[`交易id`].trim() + `,`
              j++
            } else {
              tradeIds += `#,`
            }
          })
        }
        if (etcIds != `` && i > 0) {
          this.formCondition.cardId = etcIds.substring(0, etcIds.length - 1)
        }
        if (tradeIds != `` && j > 0) {
          this.formCondition.tradeId = tradeIds.substring(0, tradeIds.length - 1)
        }
      })
    },
    file2Xce(file) {
      return new Promise(function(resolve, reject) {
        const reader = new FileReader()
        reader.onload = function(e) {
          const data = e.target.result
          this.wb = XLSX.read(data, {
            type: `binary`
          })
          const result = []
          var are = (this.wb.Sheets.Sheet1)[`!ref`]
          var areRe = are.replace(`A1`, `A2`);
          (this.wb.Sheets.Sheet1)[`!ref`] = areRe
          this.wb.SheetNames.forEach((sheetName) => {
            result.push({
              sheetName: sheetName,
              sheet: XLSX.utils.sheet_to_json(this.wb.Sheets[sheetName])
            })
          })
          resolve(result)
        }
        // reader.readAsBinaryString(file.raw)
        reader.readAsBinaryString(file) // 传统input方法
      })
    },
    handleSelectionChange(value) {
      this.multipleSelection = value
    },
    // 下载模板
    DownloadTemplate() {
      var url = hostUrl + `noCar/templateDownload?fileName=6` // eslint-disable-line
      window.location.href = url
    },
    handleRemove(file, fileList) {
    },

    handlePreview(file) {
    },
    handleSuccess(a) {
      this.formUserList.file = a.raw
    },
    // 批量上传模板信息
    async batchUpload() {
      this.fullscreenLoading = true
      const formData = new FormData()
      formData.append(`file`, this.formUserList.file)
      const response = await this.$http.post(`selfCar/batchImportSelfcarTrades`, formData)
      var {data: { code, msg, data }} = response
      if (code == 0 && msg == `1`) {
        this.fullscreenLoading = false
        this.invoiceTable = response.data.data
        this.total = response.data.data.length
      } else {
        this.fullscreenLoading = false
        this.$message.error(`数据存在错误，请检查文件中数据`)
      }
    },
    // 分页方法
    handleSizeChange(val) {
      this.pagesize = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.current = val
      this.loadData()
    },
    async     exportExcel1() {
      const loading = this.$loading({
        lock: true,
        text: `系统正在努力接收中，过程大概需要几分钟的时间，请您耐心等待...`,
        spinner: `el-icon-loading`,
        background: `rgba(0, 0, 0, 0.7)`
      })
      let curr = this.current
      let pagesize1 = this.pagesize
      this.current = 1
      this.pagesize = this.total
      await this.loadData()
      // 设置当前日期
      let time = new Date()
      let year = time.getFullYear()
      let month = time.getMonth() + 1
      let day = time.getDate()
      let name = `自有车交易查询列表_` + year + `` + month + `` + day
      /* generate workbook object from table */
      //  .table要导出的是哪一个表格
      var wb = XLSX.utils.table_to_book(document.querySelector(`.table`), { raw: true })
      /* get binary string as output */
      var wbout = XLSX.write(wb, {
        bookType: `xlsx`,
        bookSST: true,
        type: `array`
      })
      try {
        //  name+'.xlsx'表示导出的excel表格名字
        FileSaver.saveAs(
          new Blob([wbout], { type: `application/octet-stream` }),
          name + `.xlsx`
        )
      } catch (e) {
      }
      this.current = curr
      this.pagesize = pagesize1
      this.loadData()
      loading.close()
      return wbout
    },
    async     exportExcel() {
      const loading = this.$loading({
        lock: true,
        text: `系统正在努力接收中，过程大概需要几分钟的时间，请您耐心等待...`,
        spinner: `el-icon-loading`,
        background: `rgba(0, 0, 0, 0.7)`
      })
      var recodes = []

      for (var j = 1; j <= this.total / 10000 + 1; j++) {
        const formData = new FormData()
        formData.append(`current`, j)
        formData.append(`size`, 10000)
        for (var i in this.formCondition) {
          formData.append(i, this.formCondition[i])
        }
        const response = await this.$http.post(`selfCar/findTrades`, formData)
        if (response.data.code == 0) {
          recodes = recodes.concat(response.data.data.records)
        }
      }

      // 设置当前日期
      let time = new Date()
      let year = time.getFullYear()
      let month = time.getMonth() + 1
      let day = time.getDate()
      let name = `自有车交易查询列表_` + year + `` + month + `` + day
      let cloums = [
        {'title': `企业编号`, 'key': `companyNum`},
        {'title': `公司名称`, 'key': `companyName`},
        {'title': `公司税号`, 'key': `companyReferencenum`},
        {'title': `交易Id`, 'key': `tradeId`},
        {'title': `etc卡号`, 'key': `cardId`},

        {'title': `交易费用`, 'key': `fee`},
        {'title': `交易时间`, 'key': `exTime`},
        {'title': `申请开票时间`, 'key': `aclTime`},
        {'title': `申请Id`, 'key': `applId`},
        {'title': `状态`, 'key': `status`}
      ]
      this.exportExcelComm(cloums, recodes, name, loading)
    },
    // 导出Excel
    exportExcelComm(columns, list, excelName, loading) {
      let tHeader = []
      let filterVal = []
      columns.forEach((item) => {
        tHeader.push(item.title)
        filterVal.push(item.key)
      })

      const data = this.formatJson(filterVal, list)
      data.unshift(tHeader)
      CsvExportor.downloadCsv(data, { tHeader }, excelName + `.csv`)
      loading.close()
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => {
        return filterVal.map((j) => {
          if (j == `status`) {
            if (v[j] == 1) {
              return `待开票`
            } else if (v[j] == 2) {
              return `开票中`
            } else if (v[j] == 3) {
              return `开票完成`
            }
          } else if (j == `fee`) {
            return v[j] / 100
          } else if (j == `companyReferencenum` || j == `cardId`) {
            return v[j] + `\t`
          } else {
            return v[j]
          }
        })
      })
    }
  }
}
</script>
<style>
.billWay_container {
  border: 1px solid #d9d9d9;
  border-radius: 10px;
}
.billWay_container .title {
  font-size: 5px;
  margin-bottom: 20px;
}
.billWay_container .top {
  padding-top: 20px;
  padding-left: 20px;
}
.billWay_container .text {
  display: inline-block;
  color: #000;
  font-size: 16px ;
  margin-left: 1%;
}
.billWay_container .input-demo {
  display: inline-block;
  width: 20%;
  margin-left: 1%;
}
.billWay_container .block {
  font-size: 5px;
  text-align: center;
  margin-top: 25px;
  margin-bottom: 25px;
}
.billWay_container .el-dialog {
  width: 60%;
}
.billWay_container .el-dialog__header, .el-dialog__body {
  padding: 0 20px;
}
.billWay_container .tou {
  font-size: 20px;
  height: 30px;
  line-height: 30px;
  padding-top: 15px;
}
.billWay_container .line {
  margin-top: 15px;
  margin-bottom: 15px;
  width: 100%;
  height: 2px;
  background-color: #d9d9d9;
}
.billWay_container .xinxi {
  text-align: center;
  margin: 15px auto;
  font-size: 18px;
}
</style>
