<template>
  <div class="list">
    <!-- 头部细节部分 -->
      <div class="title">
        <el-row>
          <el-col :span="24">
            <div class="top">
              <el-input  placeholder="运单编号" class="input-demo" v-model="waybillNum"></el-input>
              <el-input  placeholder="车牌号" class="input-demo" v-model="plateNum"></el-input>
              <el-input  placeholder="发票号码" class="input-demo" v-model="invoiceNum"></el-input>
               <el-input  placeholder="发票代码" class="input-demo" v-model="invoiceCode"></el-input>
            </div>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <div class="top">
              <el-date-picker style="margin-left:1%;" v-model="invoiceMakeTime" type="daterange" value-format="yyyy-MM-dd HH:mm:SS" range-separator="至" start-placeholder="开票时间始" end-placeholder="开票时间止"></el-date-picker>
               <el-date-picker v-model="calculateTime" type="daterange" value-format="yyyy-MM-dd HH:mm:SS" range-separator="至" start-placeholder="扣费时间始" end-placeholder="扣费时间止"></el-date-picker>


            </div>
          </el-col>
        </el-row>
          <el-row>
          <el-col :span="24">
            <div class="top">
            <label style="margin-left: 1%;">发票抬头:</label>
              <el-select v-model="taxPlayerCode" placeholder="请选择发票抬头">
                 <el-option
                  v-for="item in companyList"
                  :key="item.companyName"
                  :label="item.companyName"
                  :value="item.companyName">
                </el-option>
              </el-select>

              <el-button type="success" style="margin-left: 1%;" @click="firstLoadData">查询</el-button>
              <el-button type="success" style="margin-left: 1%;" @click="exportOut">导出</el-button>
<!--              <el-button type="success" style="margin-left: 1%;" @click="packDownload"-->
<!--                         v-loading.fullscreen.lock="fullscreenLoading">打包下载-->
<!--              </el-button>-->
            </div>
          </el-col>
        </el-row>
      </div>
    <!-- 头部细节部分结束 -->
     <!-- 表格部分 -->
      <template>
        <div class="tou">统计列表</div>
        <el-table
            v-loading="loading"
            ref="multipleTabletwo"
            :data="allmeterList"
            border
            tooltip-effect="dark"
            style="margin-bottom: 20px;">
            <el-table-column
              label="总金额(元)"
              show-overflow-tooltip>
              <template slot-scope="scope" show-overflow-tooltip>
                  <span>{{scope.row.fee / 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="feeCount"
              label="计费条数"
              show-overflow-tooltip>
            </el-table-column>
          </el-table>
      </template>

      <template >
        <div class="tou">运单发票列表</div>
        <el-table
         class="table"
          v-loading="loading"
          ref="multipleTable"
          :data="usertable"
          :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="waybillNum"
            label="运单编号"
            show-overflow-tooltip>
          </el-table-column>
           <el-table-column
            prop="plateNum"
            label="车牌号"
            show-overflow-tooltip>
          </el-table-column>

          <el-table-column
            prop="exTime"
            label="交易时间"
            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="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
            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="invoiceCode"
            label="发票代码"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="invoiceNum"
            label="发票号码"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="transactionId"
            label="交易ID"
            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.amount/100| rounding}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="taxRate"
            label="税率"
            show-overflow-tooltip>
          </el-table-column>

          <el-table-column
            prop="invoiceHtmlUrl"
            label="预览地址"
            show-overflow-tooltip>
          </el-table-column>
          <el-table-column
            prop="invoiceUrl"
            label="下载地址"
            show-overflow-tooltip>
          </el-table-column>
           <el-table-column
            prop="billStatus"
            label="运单状态"
            show-overflow-tooltip>
             <template slot-scope="scope">
              <span v-if="scope.row.billStatus == 1" style="color: green">未结束</span>
              <span v-else-if="scope.row.billStatus == 2" style="color: green">开票中</span>
              <span v-else-if="scope.row.billStatus == 3" style="color: green">开票完成</span>
              <span v-else-if="scope.row.billStatus == 4" 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;color:blue" @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]"
        :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 {
      loading: false,
      fullscreenLoading: false,
      addList: false,
       heightt:'0px',
      current: 1,
      pagesize: 8,
      total: 0,
      usertable: [],
      companyList: [],
      waybillNum: "",
      taxPlayerCode: "",
      plateNum: "",
      invoiceNum: "",
      invoiceCode: "",
      invoiceMakeTime:'',
      calculateTime:'',
      endTime: "",
      batchNumber: '',
      invoiceUrl: '',
      allmeterList:[],
      formUserList: {
        "userName":"",
        "roleId":"",
        "userId":""
      },
      packDownloadDisabled: false,
    }
  },
  created() {
    this.heightt = tableHeight*0.5+150;
    console.log(this.heightt)
    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('waybillNum', this.waybillNum);
        formData.append('plateNum', this.plateNum);
        formData.append('companyName', this.taxPlayerCode);
        formData.append('customerName', sessionStorage.getItem('userName'));
        formData.append('invoiceNum', this.invoiceNum);
        formData.append('invoiceCode', this.invoiceCode);
        formData.append('invoiceMakeTime', this.invoiceMakeTime);
        formData.append('interType', 5);
        formData.append('calculateTime', this.calculateTime);
        const response = await this.$http.post(`noCar/findNocarInvoices`, formData);
        if (response.data.code === 0) {
          this.loading = false;
          this.usertable = response.data.data.records;
          this.total = response.data.data.total;
          this.loadAllMeter();
        };
    },
    //打包下载
    async packDownload() {
      this.fullscreenLoading = true;
      var url = `http://invoice.back.jkcredit.com/package/download?&userId=${this.formUserList.userId}
      &startTime=${this.startTime}&endTime=${this.endTime}&waybillNum=${this.waybillNum}&plateNum=${this.plateNum}
      &invoiceNum=${this.invoiceNum}&taxpayerCode=${this.taxPlayerCode}&batchNumber=${this.batchNumber}`;
      window.location.href = url;
      this.packDownloadDisabled = true;
      this.$message({type: 'info', message: '正在下载，请稍等，请勿重复下载。'});
      this.fullscreenLoading = false;
      // console.log(this.formList.nums);
    } ,
    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.taxPlayerCode = this.companyList[0]['companyName'];
            this.loadData();
    },
    // 查询发票统计
    async loadAllMeter() {
       const formData = new FormData();
        formData.append('waybillNum', this.waybillNum);
        formData.append('plateNum', this.plateNum);
        formData.append('companyName', this.taxPlayerCode);
        formData.append('invoiceNum', this.invoiceNum);
        formData.append('customerName', sessionStorage.getItem('userName'));
        formData.append('invoiceCode', this.invoiceCode);
        formData.append('batchNumber', this.batchNumber);
          formData.append('invoiceMakeTime', this.invoiceMakeTime);
        formData.append('calculateTime', this.calculateTime);
        const response = await this.$http.post(`noCar/findNocarInvoicesStatic`, formData);
        if (response.data.code === 0) {
          this.loading = false;
          var allmeter = response.data.data;
          this.allmeterList = [];
          this.allmeterList.push(allmeter);
          console.log(this.allmeterList)
        };
    },
    // 展示发票全部信息
    checkLook(user) {
      window.location.href= user;
    },
    formartNum(wb){
            var sheet = wb['Sheets']['Sheet1'];
            var replaceTemp = [];
            debugger;
            for(var i in sheet){
              if(sheet[i]['v'] == '税额(元)' || 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();
            //console.log(time);
            let year = time.getFullYear();
            let month = time.getMonth() + 1;
            let day = time.getDate();
            let name = "运单发票列表_"+year + "" + month + "" + day;
            // console.log(name)
            /* 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;
    },
    async  exportOut() {
       const loading = this.$loading({
                               lock: true,
                               text: '系统正在努力接收中，过程大概需要几分钟的时间，请您耐心等待...',
                               spinner: 'el-icon-loading',
                               background: 'rgba(0, 0, 0, 0.7)'
                             });
            const formData = new FormData();
        formData.append('current', 1);
        formData.append('size', this.total);
        formData.append('waybillNum', this.waybillNum);
        formData.append('plateNum', this.plateNum);
        formData.append('companyName', this.taxPlayerCode);
        formData.append('customerName', sessionStorage.getItem('userName'));
        formData.append('invoiceNum', this.invoiceNum);
        formData.append('invoiceCode', this.invoiceCode);
        formData.append('invoiceMakeTime', this.invoiceMakeTime);
        formData.append('interType', 5);
        formData.append('calculateTime', this.calculateTime);
        const response = await this.$http.post(`noCar/findNocarInvoices`, formData);
            if (response.data.code === 0) {
               // 设置当前日期
                    let time = new Date();
                    //console.log(time);
                    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":"waybillNum"},
                      {"title":"购方税号","key":"buyerTaxpayerCode"},
                      {"title":"车牌号码","key":"plateNum"},
                      {"title":"运单开始时间","key":"waybillStartTime"},
                      {"title":"运单结束时间","key":"waybillEndTime"},
                      {"title":"销方税号","key":"sellerTaxpayerCode"},
                      {"title":"销方名称","key":"sellerName"},
                      {"title":"入口收费站","key":"enStation"},
                      {"title":"出口收费站","key":"exStation"},
                      {"title":"发票代码","key":"invoiceCode"},
                      {"title":"发票号码","key":"invoiceNum"},
                      {"title":"交易Id","key":"transactionId"},
                      {"title":"开票时间","key":"invoiceMakeTime"},      
                      {"title":"交易时间","key":"exTime"},
                      {"title":"交易金额(元)","key":"fee"},
                      {"title":"价税合计(元)","key":"totalAmount"},
                      {"title":"税额(元)","key":"totalTaxAmount"},
                      {"title":"金额(元)","key":"amount"},
                      {"title":"税率","key":"taxRate"},
                      {"title":"扣费时间","key":"calculateTime"},
                      {"title":"运单状态","key":"billStatus"},
                      {"title":"预览地址","key":"invoiceHtmlUrl"},
                      {"title":"下载地址","key":"invoiceUrl"}  
                         
                    ];
                    debugger;
                    await this.exportExcelComm(cloums,response.data.data.records,name,loading);
            }
          },
          formatJson (filterVal, jsonData) {
            return jsonData.map(v => filterVal.map(j => {
             if(j == 'billStatus'){
                 if(v[j] == 1){
                   return "未结束";
                 } else if(v[j] == -2){
                   return "上传失败";
                 }else if(v[j] == -3){
                   return "指令结束上传失败";
                 }else if(v[j] == 2){
                   return "开票中";
                 }else if(v[j] == 3){
                   return "开票完成";
                 }else {
                   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{
                  return v[j];
              }
              
              }));
          },
          // 导出Excel
          exportExcelComm(columns,list,excelName,loading){
                  require.ensure([], () => {
                      const { export_json_to_excel } = require('@/vendor/Export2Excel');
                      let tHeader = []
                      let filterVal = []
                      columns.forEach(item =>{
                          tHeader.push(item.title)
                          filterVal.push(item.key)
                      })
                      const data = this.formatJson(filterVal, list);
                      debugger;
                      export_json_to_excel(tHeader, data, excelName);
                      loading.close();
                  })
            },
    // 分页方法
    handleSizeChange(val) {
      this.pagesize = val;
     this.loadData();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.current = val;
      this.loadData();
      console.log(`当前页: ${val}`);
    },

  }
};
</script>

<style>
.list {
  border: 1px solid #d9d9d9;
  border-radius: 10px;
  overflow-y: scroll;
  height:100%;
}
.list .title {
  font-size: 5px;
  margin-bottom: 20px;
}

.list .top {
  padding-top: 20px;
  padding-left: 20px;
}

.list .block {
  font-size: 5px;
  text-align: center;
  margin-top: 15px;
  margin-bottom: 20px;
}
.list .input-demo {
  display: inline-block;
  width: 20%;
  margin-left: 1%;
}
.list .tou {
  text-align: center;
  margin-bottom: 10px;
  font-size: 20px;
  height: 20px;
  line-height: 20px;
  padding-top: 5px;
}
.list .line {
  margin-top: 15px;
  margin-bottom: 15px;
  width: 100%;
  height: 2px;
  background-color: #d9d9d9;
}
</style>
