<template>
  <div class="already">
    <!-- 头部细节部分 -->
      <div class="title">
        <el-row>
          <el-col :span="24">
            <div class="top">
              <el-select style="width:170px" v-model="formList.companyName" filterable  placeholder="请选择公司名称">
                <el-option
                  v-for="item in companyList"
                  :key="item.companyName"
                  :label="item.companyName"
                  :value="item.companyName">
                </el-option>
              </el-select>
              <el-input  placeholder="请输入车牌号码" style="width:170px" class="input-demo" v-model="formList.carNum"></el-input>
              <el-date-picker v-model="formList.invoiceMakeTime" 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" v-loading.fullscreen.lock="fullscreenLoading">查询</el-button>
              <el-button type="success" style="margin-left: 1%;" @click="queryLook" v-loading.fullscreen.lock="fullscreenLoading">更新（取票）</el-button>
            <el-button type="primary"  @click="exportExcel">导出报表</el-button>
            </div>
          </el-col>
        </el-row>

      </div>
    <!-- 头部细节部分结束 -->
      <template>
        <el-table
        class="table"
          ref="multipleTable"
          :data="usertabletwo"
         :height="heightt"
          border
          tooltip-effect="dark">
           <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="buyerTaxpayerCode"
            label="购方税号"
            show-overflow-tooltip>
          </el-table-column>
           <el-table-column
            prop="plateNum"
            label="车牌号"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="cardId"
            label="ETC卡号"
            show-overflow-tooltip>
          </el-table-column>
           <el-table-column
            prop="tradeId"
            label="交易ID"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="sellerTaxpayerCode"
            label="销方税号"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="sellerName"
            label="销方名称"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="enStation"
            label="入口收费站"
             width="120"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="exStation"
            label="出口收费站"
             width="120"
            show-overflow-tooltip>
          </el-table-column>
           <el-table-column
            prop="invoiceNum"
            label="发票号码"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="invoiceCode"
            label="发票代码"
            show-overflow-tooltip>
          </el-table-column>



          <el-table-column
            prop="invoiceMakeTime"
            label="开票时间"
            show-overflow-tooltip>
          </el-table-column>

          <el-table-column
            label="交易金额(元)"
            width="120"
            show-overflow-tooltip>
            <template slot-scope="scope" show-overflow-tooltip>
                <span>{{scope.row.fee / 100}}</span>
            </template>
          </el-table-column>
           <el-table-column
            label="价税合计(元)"
             width="120"
            show-overflow-tooltip>
            <template slot-scope="scope" show-overflow-tooltip>
                <span>{{scope.row.totalAmount / 100}}</span>
            </template>
          </el-table-column>
           <el-table-column
            label="税额(元)"
            show-overflow-tooltip>
            <template slot-scope="scope" show-overflow-tooltip>
                <span>{{scope.row.totalTaxAmount / 100}}</span>
            </template>
          </el-table-column>
         <el-table-column
            prop="amount"
            label="金额"
            show-overflow-tooltip>
            <template slot-scope="scope">
               <span>{{scope.row.fee/100| rounding}}</span>
            </template>
          </el-table-column>
           <el-table-column
            prop="taxRate"
            label="税率"
            show-overflow-tooltip>
            <template slot-scope="scope">
               <span>{{scope.row.taxRate| rounding}}</span>
            </template>
          </el-table-column>

          <el-table-column
            prop="invoiceHtmlUrl"
            label="预览地址"
            show-overflow-tooltip>
            <template slot-scope="scope">
               <a :href="scope.row.invoiceHtmlUrl" target="_blank">{{scope.row.invoiceHtmlUrl}}</a>
            </template>
          </el-table-column>
          <el-table-column
            prop="invoiceUrl"
            label="下载地址"
            show-overflow-tooltip>
            <template slot-scope="scope">
               <a :href="scope.row.invoiceUrl" target="_blank">{{scope.row.invoiceUrl}}</a>
            </template>
          </el-table-column>
           <el-table-column
            prop="tradeStatus"
            label="状态"
            show-overflow-tooltip>
             <template slot-scope="scope">
              <span v-if="scope.row.tradeStatus == 1" style="color: green">待开票</span>
              <span v-else-if="scope.row.tradeStatus == 2" style="color: red">开票中</span>
              <span v-else-if="scope.row.tradeStatus == 3" style="color: red">已开票</span>
            </template>
          </el-table-column>
           <el-table-column
            prop="calculateTime"
            label="计费时间"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            label="操作"
            width="80">
            <template slot-scope="scope" show-overflow-tooltip>
              <span style="cursor:pointer;" @click="checkLook(scope.row.invoiceUrl)">下载</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>
import FileSaver from "file-saver";
import XLSX from "xlsx";
export default{
  data() {
    return {
      fullscreenLoading: false,
      usertabletwo: [],
      roleId: '',
       hightt:'0px',
      // codeNumber: '',
      formList: {
        "companyName": "",
        "customerName": "",
        "carNum": "",
        "startTime": "",
        "endTime": "",
        "invoiceMakeTime":""
      },
      current: 1,
      pagesize: 8,
      total:'',
      companyList:[]

    }
  },
  created() {
    this.heightt = tableHeight+20;
    this.formList.customerName = sessionStorage.getItem('userName');
    this.initCompanyList();
  },
  methods: {
     firstLoadData(){
            this.current = 1;
            this.pagesize = 8;
            this.loadData();
          },

           // 列表展示
          async loadData() {
            const formData = new FormData();
            formData.append('current', this.current);
            formData.append('size', this.pagesize);
            formData.append('customerName', this.formList.customerName);
            formData.append('companyName', this.formList.companyName);
            formData.append('plateNum', this.formList.carNum);
            formData.append('invoiceMakeTime', this.formList.invoiceMakeTime);
            const response = await this.$http.post('selfCar/findSelfCarInvoices', formData);
            if (response.data.code === 0) {
              this.usertabletwo = response.data.data.records;
              this.total = response.data.data.total;
            }
          },
    // 查询已开发票数据
    async queryLook() {

       if(this.formList.invoiceMakeTime !=null && this.formList.invoiceMakeTime !=''){

         this.formList.startTime = this.formList.invoiceMakeTime[0];
         this.formList.endTime = this.formList.invoiceMakeTime[1];
       }
       const loading = this.$loading({
                             lock: true,
                             text: '系统正在努力接收中，过程大概需要几分钟的时间，请您耐心等待...',
                             spinner: 'el-icon-loading',
                             background: 'rgba(0, 0, 0, 0.7)'
                           });
      const response = await this.$http.post(`/selfCar/findSelfcarInvoiceByTime`, this.formList);
      var {data: { code, msg, data }} = response;
      if(code === 0) {
         this.$message({
          type: 'success',
          message: '更新成功'
        });
      }else{
        this.$message.error(msg);
      }
      loading.close();
    },
    async initCompanyList(){
            const response = await this.$http.post(`lowerService/customeRecQueryList`, {"customerName":sessionStorage.getItem('userName')});
            if (response.data.code === 0) {
              this.companyList = response.data.data;
            }
            if(this.companyList == null || typeof this.companyList == 'undefined' || this.companyList =='' || this.companyList.length==0){
                                                  this.companyList = [{'companyName':'.'}];
                                                }
            this.formList.companyName = this.companyList[0]['companyName'];
            this.loadData();
    },
    // 展示发票全部信息
    checkLook(user) {
      window.location.href= user;
    },
 // 分页方法
          handleSizeChange(val) {
            this.pagesize = val;
            this.loadData();
          },
          handleCurrentChange(val) {
            this.current = val;
              this.loadData();
          },
          formartNum(wb){
            var sheet = wb['Sheets']['Sheet1'];
            var replaceTemp = [];
            for(var i in sheet){
              if(sheet[i]['v'] == '税额(元)'||sheet[i]['v'] == '价税合计(元)'||sheet[i]['v'] == '交易金额(元)'){
                replaceTemp.push(i.replace(/[0-9]/g,''));
                continue;
              }
              if(replaceTemp.includes(i.replace(/[0-9]/g,''))){
                sheet[i]['t']='n';
              }
            }
          },
       async     exportExcel() {
       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 });
      this.formartNum(wb);
      /* 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) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
       this.current = curr;
      this.pagesize = pagesize1;
      this.loadData();
      loading.close();
      return wbout;
    },
  }
};
</script>

<style>
.already {
  border: 1px solid #d9d9d9;
  border-radius: 10px;
}
.already .title {
  font-size: 5px;
  margin-bottom: 20px;
  margin-top: 20px;
}
.already .top {
  padding-top: 20px;
  padding-left: 20px;
}

.already .input-demo {
  display: inline-block;
  width: 20%;
  margin-left: 1%;
}
.already {
  border: 1px solid #d9d9d9;
  border-radius: 10px;
}
.already .title {
  font-size: 5px;
  margin-bottom: 20px;
}
.already .top {
  padding-top: 20px;
  padding-left: 20px;
}
.already .text {
  display: inline-block;
  color: #000;
  font-size: 16px ;
  margin-left: 1%;
}
.already .input-demo {
  display: inline-block;
  width: 20%;
  margin-left: 1%;
}
.already .block {
  font-size: 5px;
  text-align: center;
  margin-top: 25px;
  margin-bottom: 25px;
}
.already .el-dialog {
  width: 60%;
}
.already .el-dialog__header, .el-dialog__body {
  padding: 0 20px;
}
.already .tou {
  font-size: 20px;
  height: 30px;
  line-height: 30px;
  padding-top: 15px;
}
.already .line {
  margin-top: 15px;
  margin-bottom: 15px;
  width: 100%;
  height: 2px;
  background-color: #d9d9d9;
}
.already .xinxi {
  text-align: center;
  margin: 15px auto;
  font-size: 18px;
}
</style>
