<template>
    <div class="invoice_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-button style="margin-left: 555px;" @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.companyNum"></el-input>
                <el-input  placeholder="etc卡号" class="input-demo" v-model="formCondition.cardId"></el-input>
                <el-input  placeholder="交易id" class="input-demo" v-model="formCondition.tradeId"></el-input>
                <el-button type="success" style="margin-left: 1%;" @click="loadData">查询</el-button>
                <el-button type="primary" style="margin-left: 1%;" @click="exportExcel">导出报表</el-button>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
      <!-- 表格部分 -->
        <template>
        <el-table
          class="table"
          v-loading="loading"
          ref="multipleTable"
          :data="invoiceTable"
          :height="heightt"
          border
          tooltip-effect="dark">
          <el-table-column
            label="ETC卡号"
            prop="cardId"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="applyId"
            label="申请id"
            show-overflow-tooltip>
          </el-table-column>
           <el-table-column
            prop="tradeCount"
            label="交易数量"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="invoiceCount"
            label="发票数量"
            show-overflow-tooltip>
          </el-table-column>
           <!-- <el-table-column
            prop="invoiceAmount"
            label="发票金额"
            show-overflow-tooltip>
          </el-table-column> -->
          <el-table-column
            prop="invoiceAmount"
            label="发票金额"
            width="100"
            show-overflow-tooltip>
             <template slot-scope="scope">
               <span>{{scope.row.invoiceAmount/100| rounding}}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="taxAmount"
            label="发票税额"
            show-overflow-tooltip>
          </el-table-column> -->
           <el-table-column
            prop="taxAmount"
            label="发票税额"
            width="100"
            show-overflow-tooltip>
             <template slot-scope="scope">
               <span>{{scope.row.taxAmount/100| rounding}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="invoicedCount"
            label="已开发票数量"
            show-overflow-tooltip>
          </el-table-column>
          <!-- <el-table-column
            prop="invoicedAmount"
            label="已开发票金额"
            width="100"
            show-overflow-tooltip>
          </el-table-column> -->
          <el-table-column
            prop="invoicedAmount"
            label="已开发票金额"
            width="100"
            show-overflow-tooltip>
             <template slot-scope="scope">
               <span>{{scope.row.invoicedAmount/100| rounding}}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="applyStatus"
            label="申请状态"
            width="100"
            show-overflow-tooltip>
          </el-table-column> -->
           <el-table-column
            prop="applyStatus"
            label="申请状态"
            show-overflow-tooltip>
             <template slot-scope="scope">
              <span v-if="scope.row.applyStatus == 1" style="color: green">申请中</span>
              <span v-else-if="scope.row.applyStatus == 2" style="color: red">开票中</span>
              <span v-else-if="scope.row.applyStatus == 3" style="color: red">开票完成</span>
            </template>
          </el-table-column>
        </el-table>
      </template>
    </div>
</template>
<script type="text/javascript">
import FileSaver from 'file-saver'
import CsvExportor from 'csv-exportor'
import XLSX from 'xlsx'
export default {
  data() {
    return {
      formCondition: {
        companyNum: ``,
        cardId: ``,
        tradeId: ``
      },
      invoiceTable: [],
      hightt: `0px`
    }
  },
  created() {
    this.heightt = tableHeight - 50 // eslint-disable-line
  },
  filters: {
    rounding(value) {
      return value.toFixed(2)
    }
  },
  methods: {
    firstLoadData() {
    },
    // 列表展示
    async loadData() {
      const formData = new FormData()
      for (var i in this.formCondition) {
        formData.append(i, this.formCondition[i])
      }
      const response = await this.$http.post(`selfCarService/getApplyQueryByTradeIds`, formData);
      if (response.data.code === 0) {
        this.invoiceTable = response.data.data.result;
      } else {
        this.$message({
          type: `error`,
          message: `查询结果:` + response.data.msg
        });
      }
    },
    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(`格式错误！请重新选择`)
        return;
      }
      this.file2Xce(file).then((tabJson) => {
        var companyNums = ``;
        var etcIds = ``;
        var tradeIds = ``;
        if (tabJson && tabJson.length > 0) {
          this.xlsxJson = tabJson;
          this.fileList = this.xlsxJson[0].sheet;
          let n = `匹配的字段`;
          var k = 0;
          var i = 0;
          var j = 0;
          this.fileList.forEach((item, index, arr) => {
            if (item[`公司编码`] !== null && item[`公司编码`] !== `` && typeof item[`公司编码`] !== `undefined`) {
              companyNums += item[`公司编码`].trim() + `,`;
              k++;
            } else {
              companyNums += `#,`;
            }

            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 (companyNums !== `` && k > 0) {
          this.formCondition.companyNum = companyNums.substring(0, companyNums.length - 1);
        }
        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方法
      });
    },
    // 下载模板
    DownloadTemplate() {
      var url = hostUrl + `noCar/templateDownload?fileName=8`; // eslint-disable-line
      window.location.href = url;
    },
    exportExcel() {
      const loading = this.$loading({
        lock: true,
        text: `系统正在努力接收中，过程大概需要几分钟的时间，请您耐心等待...`,
        spinner: `el-icon-loading`,
        background: `rgba(0, 0, 0, 0.7)`
      });
      // 设置当前日期
      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) {
      }
      loading.close();
      return wbout;
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => {
        return filterVal.map((j) => {
          if (j === `tradeStatus`) {
            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 === `totalAmount`) {
            return v[j] / 100
          } else if (j === `totalTaxAmount`) {
            return v[j] / 100
          } else if (j === `amount`) {
            return v[j] / 100
          } else if (j === `sellerTaxpayerCode` || j === `cardId` || j === `invoiceCode` || j === `invoiceNum`) {
            return v[j] + `\t`
          } else {
            return v[j]
          }
        })
      })
    }
  }
}
</script>
<style>
.invoice_container {
  border: 1px solid #d9d9d9;
  border-radius: 10px;
}
.invoice_container .title {
  font-size: 5px;
  margin-bottom: 20px;
}
.invoice_container .top {
  padding-top: 20px;
  padding-left: 20px;
}
.invoice_container .text {
  display: inline-block;
  color: #000;
  font-size: 16px ;
  margin-left: 1%;
}
.invoice_container .input-demo {
  display: inline-block;
  width: 15%;
  margin-left: 1%;
}
.invoice_container .block {
  font-size: 5px;
  text-align: center;
  margin-top: 25px;
  margin-bottom: 25px;
}
.invoice_container .el-dialog {
  width: 60%;
}
.invoice_container .el-dialog__header, .el-dialog__body {
  padding: 0 20px;
}
.invoice_container .tou {
  font-size: 20px;
  height: 30px;
  line-height: 30px;
  padding-top: 15px;
}
.invoice_container .line {
  margin-top: 15px;
  margin-bottom: 15px;
  width: 100%;
  height: 2px;
  background-color: #d9d9d9;
}
.invoice_container .xinxi {
  text-align: center;
  margin: 15px auto;
  font-size: 18px;
}
</style>
