<template>
  <div
    id="invoice_info_inquiry"
    v-loading="loading"
    :element-loading-text="loadText"
  >
    <el-card>
      <el-form label-position="top" style="width: 100%">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="发票种类：">
              <el-select
                v-model="invoiceExport.invoiceCategory"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in invoiceCategoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="统计日期：">
              <el-row :gutter="5">
                <el-col :span="8">
                  <el-select
                    v-model="invoiceExport.timeFlag"
                    placeholder="请选择"
                  >
                    <el-option
                      v-for="item in timeFlagOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    >
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="16">
                  <quarter-date-picker
                    v-show="selectedQuarter"
                    :getValue="getQuarter"
                  ></quarter-date-picker>
                  <el-date-picker
                    v-show="!selectedQuarter"
                    v-model="invoiceExport.dateMonthAndYear"
                    :type="dateType"
                    :clearable="false"
                    style="width: 100%"
                  ></el-date-picker>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="查询选项：">
              <el-select
                v-model="invoiceExport.invoiceSelectOption"
                placeholder="请选择"
                style="width: 100%"
                @change="handleInvoiceSelectOptionChange"
              >
                <el-option
                  v-for="item in invoiceSelectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <span slot="label" style="color: #909399">
                <span>&nbsp;&nbsp;</span>
              </span>
              <el-button
                @click="handleStartInvoiceExport"
                type="primary"
                icon="el-icon-arrow-right"
                >开始查询</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <br />
    <el-card>
      <div
        v-if="noData"
        style="height: 245px; text-align: center; margin-top: 245px"
      >
        <span>暂无数据</span>
      </div>
      <div v-else-if="invoiceExport.invoiceSelectOption == 1">
        <div>
          <el-button
            type="primary"
            icon="el-icon-document"
            @click="handleExportWord"
            >导出WORD文件</el-button
          >
          <!-- <el-button
              type="primary"
              icon="el-icon-document"
              @click="handleExportExcel"
              >导出EXCEL文件</el-button
          > -->
        </div>
        <br />
        <el-card class="box-card">
          <div slot="header">
            <span>发票统计</span>
          </div>
          <el-container>
            <el-table
              id="exportTable1"
              :data="search.resultInvoiceReportsList"
              border
              stripe
              style="width: 100%"
            >
              <el-table-column
                prop="begin_quantity"
                label="期初库存份数"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="purchase_quantity"
                label="购进发票份数"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="return_quantity"
                label="退回发票份数"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="final_quantity"
                label="期末库存份数"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="blueInvoiceCnt"
                label="正数发票份数"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="redInvoiceCnt"
                label="负数发票份数"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="blueInvalidCnt"
                label="正数废票份数"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="redInvalidCnt"
                label="负数废票份数"
                align="center"
              ></el-table-column>
              <el-table-column
                prop="blankInvalidCnt"
                label="空白废票份数"
                align="center"
              ></el-table-column>
              <!-- <el-table-column prop="totalFapiaoCnt" label="合计发票份数"></el-table-column> -->
            </el-table>
          </el-container>
        </el-card>
        <br />
        <el-card class="box-card">
          <div slot="header">
            <span>税率统计</span>
          </div>
          <el-container>
            <el-table
              id="exportTable2"
              :data="search.resultTaxRateReportsList"
              border
              stripe
              style="width: 100%"
            >
              <el-table-column
                type="index"
                :index="pageIndex"
                align="center"
                label="序号"
                width="100"
              ></el-table-column>
              <el-table-column
                :prop="row.key"
                :label="row.label"
                v-bind:key="index"
                v-for="(row, index) in tableHead"
                :formatter="fmtAmount"
                align="center"
              ></el-table-column>
            </el-table>
          </el-container>
        </el-card>
      </div>
      <div v-else style="width: 272mm; margin: 0 auto">
        <div style="text-align: right">
          <el-button
            v-on:click="invoiceListExport()"
            type="primary"
            icon="el-icon-printer"
            >导出</el-button
          >
        </div>
        <div
          id="listInfoPrint"
          style="
            display: flex;
            flex: 1;
            font-size: 16px;
            flex-direction: column;
          "
        >
          <div
            style="display: flex; justify-content: center; align-items: center"
          >
            <h1>{{ printFPQSHZD.title }}</h1>
          </div>
          <div
            style="
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: flex-start;
            "
          >
            <span>制表日期：{{ printFPQSHZD.createDate }}</span>
            <span>{{ printFPQSHZD.qdName }}</span>
            <span>纳税人登记号：{{ printFPQSHZD.entTaxId }}</span>
            <span>企业名称：{{ printFPQSHZD.entName }}</span>
            <span>地址电话：{{ printFPQSHZD.entDZDH }}</span>
            <span>金额单位：元</span>
          </div>
          <div style="display: flex; justify-content: center; margin-top: 5px">
            <el-table
              :data="invoiceExport.resultList"
              border
              style="border: 1px solid #868686; font-size: 14px; color: black"
              :header-cell-style="tableHeaderStyle"
            >
              <el-table-column
                type="index"
                :index="pageIndex"
                align="center"
                label="序号"
                width="50"
                :key="0"
              ></el-table-column>
              <el-table-column
                prop="invoiceCategory"
                label="发票种类"
                width="150"
                align="center"
                :formatter="fmtInvoiceCategory"
              ></el-table-column>
              <el-table-column
                prop="invoiceCode"
                label="发票代码"
                width="130"
                align="center"
                :key="1"
              ></el-table-column>
              <el-table-column
                prop="invoiceNumber"
                label="发票号码"
                width="120"
                align="center"
                :key="2"
              ></el-table-column>
              <el-table-column
                prop="invoiceDate"
                label="开票日期"
                width="100"
                align="center"
                :key="3"
              ></el-table-column>
              <el-table-column
                prop="customerEntTaxId"
                label="购方税号"
                align="center"
                width="170"
                :key="4"
              ></el-table-column>
              <el-table-column
                prop="totalAmount"
                label="合计金额"
                align="center"
                width="120"
                header-align="center"
                :key="5"
                :formatter="fmtToDecimal2"
              ></el-table-column>
              <el-table-column
                prop="totalTaxes"
                label="合计税额"
                align="center"
                width="120"
                header-align="center"
                :key="6"
                :formatter="fmtToDecimal2"
              ></el-table-column>
            </el-table>
          </div>
          <div style="width: 100%; margin-top: 10px; margin-bottom: 50px">
            <div class="Row">
              <div class="Column">填表人：</div>
              <div class="Column">抽样员：</div>
              <div class="Column">录入员：</div>
              <div class="Column">复核员：</div>
              <div class="Column">审计员：</div>
            </div>
          </div>
        </div>
      </div>
    </el-card>

    <div id="word_export" style="width: 100%" v-show="false">
      <h2 id="title" style="text-align: center">增值税发票汇总表</h2>
      <span style="font-size: 14px">
        制表日期：
        <span id="zbsj"></span>
        <br />所属期间：
        <span id="ssqj"></span>
        <br />纳税人登记号：
        <span id="nsrdjh"></span>
        <br />企业名称：
        <span id="qymc"></span>
        <br />地址电话：
        <span id="dzdh"></span>
      </span>
      <br />
      <span
        >---------------------------------------------------------------------</span
      >
      <br />
      <span style="font-size: 14px">★ 发票领用存情况 ★</span>
      <div style="width: 100%">
        <pre
          style="font-size: 14px"
        >期初库存份数&nbsp;<span id="word_begin_quantity">0</span>&#9;&#9;正数发票份数&nbsp;<span
            id="word_blueInvoiceCnt">0</span>&#9;&#9;负数发票份数&nbsp;<span id="word_redInvoiceCnt">0</span>&#9;&#9;</pre>
        <pre
          style="font-size: 14px"
        >购进发票份数&nbsp;<span id="word_purchase_quantity">0</span>&#9;&#9;正数废票份数&nbsp;<span
            id="word_blueInvalidCnt">0</span>&#9;&#9;负数废票份数&nbsp;<span id="word_redInvalidCnt">0</span>&#9;&#9;</pre>
        <pre style="font-size: 14px">
退回发票份数&nbsp;<span id="word_return_quantity">0</span>&#9;&#9;期末库存份数&nbsp;<span id="word_final_quantity">0</span>&#9;&#9;空白废票份数&nbsp;<span
            id="word_blankInvalidCnt">0</span>&#9;&#9;</pre>
      </div>
      <span
        >---------------------------------------------------------------------</span
      >
      <br />
      <span style="font-size: 14px">★ 销货情况 ★</span>
      <br />
      <span style="font-size: 14px">金额单位：元</span>
      <br />
      <table
        id="word_export_sltj"
        border="1"
        cellspacing="0"
        cellpadding="6"
        style="width: 98%; text-align: center; font-size: 14px"
      ></table>
    </div>
    <div id="word_export_invoice_list" style="width: 100%" v-show="false">
      <h2 id="invoice_list_title" style="text-align: center">
        {{ printFPQSHZD.title }}
      </h2>
      <span>制表日期：{{ printFPQSHZD.createDate }}</span>
      <br />
      <span>{{ printFPQSHZD.qdName }}</span>
      <br />
      <span>纳税人登记号：{{ printFPQSHZD.entTaxId }}</span>
      <br />
      <span>企业名称：{{ printFPQSHZD.entName }}</span>
      <br />
      <span>地址电话：{{ printFPQSHZD.entDZDH }}</span>
      <br />
      <span>金额单位：元</span>
      <br />
      <table
        id="invoice_list"
        border="1"
        cellspacing="0"
        cellpadding="6"
        style="width: 98%; text-align: center; font-size: 14px"
      ></table>
    </div>
  </div>
</template>

<script>
import { invoiceQuery } from "@/api/invoice";
import { InvoiceReports } from "@/api/invoice_ext";
import { GetLocalDevices, GetLocalDevice } from "@/api/ent_device";
import {
  invoiceExportCommit,
  invoiceExportRecordStatus,
} from "@/api/invoice_export";

import FileSaver from "file-saver";
import XLSX from "xlsx";

import $ from "jquery";

require("@/assets/js/jquery.wordexport");

import DateHelper from "@/utils/date";
import cache from "@/utils/cache";

import QuarterDatePicker from "@/components/QuarterDatePicker";

import SKServer from "@/api/skserver";
import html2canvas from "html2canvas";
import JsPDF from "jspdf";
import { AxiosRequestData } from "@/data/axios_request";

// 发票种类列表
const invoiceCategoryOptions = [
  {
    value: 1,
    label: "增值税普通电子发票",
  },
  {
    value: 2,
    label: "增值税电子专用发票",
  },
  {
    value: 3,
    label: "增值税普通纸质发票",
  },
  {
    value: 4,
    label: "增值税专用纸质发票",
  },
];

// 发票查询选项列表
const invoiceSelectOptions = [
  {
    value: 1,
    label: "发票汇总统计",
  },
  {
    value: 2,
    label: "正数发票清单",
  },
  {
    value: 3,
    label: "负数发票清单",
  },
  {
    value: 4,
    label: "正数发票废票清单",
  },
  {
    value: 5,
    label: "负数发票废票清单",
  },
  {
    value: 6,
    label: "空白作废发票清单",
  },
];

// 统计维度
const timeFlagOptions = [
  // {
  //     value: 1,
  //     label: "按日统计",
  // },
  {
    value: 2,
    label: "按月统计",
  },
  {
    value: 3,
    label: "按季度统计",
  },
  {
    value: 4,
    label: "按年统计",
  },
];

/**
 * 获取发票种类文本；
 * @param {Number} intKey 发票类别的数字标识
 */
function GetInvoiceCategoryLabel(intKey) {
  let result = intKey;
  for (const item of invoiceCategoryOptions) {
    if (item.value === intKey) {
      result = item.label;
      break;
    }
  }
  return result;
}

/**
 * 获取发票查询选项列表文本；
 * @param {Number} intKey 查询选项的数字标识
 */
function GetInvoiceSelectOptionLabel(intKey) {
  let result = intKey;
  for (const item of invoiceSelectOptions) {
    if (item.value === intKey) {
      result = item.label;
      break;
    }
  }
  return result;
}

export default {
  name: "invoice_info_inquiry",
  components: {
    "quarter-date-picker": QuarterDatePicker,
  },
  data() {
    return {
      loading: false,
      invoiceCategoryOptions: invoiceCategoryOptions,
      invoiceSelectOptions: invoiceSelectOptions,
      timeFlagOptions: timeFlagOptions,
      invoiceExport: {
        invoiceCategory: "",
        timeFlag: timeFlagOptions[0].value, // 统计维度标识,默认统计维度：月
        dateMonthAndYear: "",
        dateQuarter: "", // 季度绑定值；
        invoiceSelectOption: "",
        resultList: [], // 其它查询结果列表
      },
      search: {
        invoiceDevice: GetLocalDevice(
          JSON.parse(cache.getSession("company")).defaultInvoiceDevice
        ),
        resultInvoiceReportsList: [], // 发票报告查询结果列表
        resultTaxRateReportsList: [], // 税率报告查询结果列表
      },
      print: {
        // 汇总统计的打印信息
        fileName: "",
        title: "",
        searchMonth: "", // 查询开始时间
        searchMonthEnd: "", // 查询结束时间
      },
      printFPQSHZD: {
        entName: "",
        entTaxId: "",
        entDZDH: "",
        createDate: "",
        title: "", // 标题
        qdName: "", // 清单名称
        printObj: {
          id: "print-region", // 这里是要打印元素的ID
        },
      },
      beginDateTime: "",
      endDateTime: "",
      recordId: "",
      timer: null,
      loadText: "加载中，请稍等！",
    };
  },
  created() {
    // 设置打印信息
    let company = JSON.parse(cache.getSession("company"));
    this.printFPQSHZD.entTaxId = company.entTaxId;
    this.printFPQSHZD.entName = company.entName;
    this.printFPQSHZD.entDZDH = company.entAddress + " " + company.entPhone;
    this.printFPQSHZD.createDate = this.dateFormat(
      new Date(),
      "yyyy年MM月dd日"
    );
  },
  computed: {
    noData() {
      if (
        this.invoiceExport.invoiceSelectOption == null ||
        this.invoiceExport.invoiceSelectOption == ""
      ) {
        return true;
      } else if (
        this.invoiceExport.invoiceSelectOption == 1 &&
        this.search.resultInvoiceReportsList.length == 0
      ) {
        return true;
      } else if (
        this.invoiceExport.invoiceSelectOption != 1 &&
        this.invoiceExport.resultList.length == 0
      ) {
        return true;
      }

      return false;
    },
    dateType: function () {
      if (this.invoiceExport.timeFlag === 1) {
        return "date";
      } else if (this.invoiceExport.timeFlag === 2) {
        return "month";
      } else if (this.invoiceExport.timeFlag === 3) {
        return "quarter";
      } else if (this.invoiceExport.timeFlag === 4) {
        return "year";
      } else {
        return "date";
      }
    },
    selectedQuarter: function () {
      return this.invoiceExport.timeFlag === 3;
    },
  },
  methods: {
    pageIndex(index) {
      return index + 1;
    },
    fmtInvoiceCategory(row, column, cellValue) {
      return GetInvoiceCategoryLabel(cellValue);
    },
    fmtToDecimal2(row, column, cellValue) {
      var f = parseFloat(cellValue);
      if (isNaN(f)) {
        return false;
      }
      var f = Math.round(cellValue * 100) / 100;
      var s = f.toString();
      var rs = s.indexOf(".");
      if (rs < 0) {
        rs = s.length;
        s += ".";
      }
      while (s.length <= rs + 2) {
        s += "0";
      }
      return s;
    },
    fmtAmount(row, column, cellValue) {
      if (cellValue == null || cellValue === undefined || cellValue === "") {
        return "0.00";
      } else if (cellValue === 0 || cellValue === "0") {
        return "0.00";
      } else {
        return cellValue;
      }
    },
    // 获取选择的季度信息
    getQuarter(beginDate, endDate) {
      this.invoiceExport.dateQuarter = [beginDate, endDate];
    },

    // 开始发票导出
    handleStartInvoiceExport() {
      // 验证发票种类输入
      let invoiceCategory = this.invoiceExport.invoiceCategory;
      if (
        invoiceCategory === null ||
        invoiceCategory === "" ||
        invoiceCategory === undefined
      ) {
        this.$message.error("请选择导出发票明细时使用发票种类！");
        return false;
      }

      // 验证发票查询选项
      let invoiceSelectOption = this.invoiceExport.invoiceSelectOption;
      if (
        invoiceSelectOption === null ||
        invoiceSelectOption === "" ||
        invoiceSelectOption === undefined
      ) {
        this.$message.error("请选择导出发票查询选项！");
        return false;
      }

      let dateBeginObj = null;
      let dateEndObj = null;
      if (this.invoiceExport.timeFlag === 3) {
        // 选择统计维度为：季度
        let inputDate = this.invoiceExport.dateQuarter;
        if (inputDate === null || inputDate === "" || inputDate === undefined) {
          this.$message.error("请选择导出发票统计季度！");
          return false;
        }

        if (inputDate instanceof Array) {
          dateBeginObj = inputDate[0];
          dateEndObj = inputDate[1];
        } else {
          this.$message.error("导出发票统计季度错误！");
          return false;
        }
      } else if (this.invoiceExport.timeFlag === 2) {
        // 选择统计维度为：月份
        let inputDate = this.invoiceExport.dateMonthAndYear;
        if (inputDate === null || inputDate === "" || inputDate === undefined) {
          this.$message.error("请选择导出发票统计月份！");
          return false;
        }

        dateBeginObj = new Date(inputDate);
        dateEndObj = new Date(
          dateBeginObj.getFullYear(),
          dateBeginObj.getMonth() + 1,
          0
        );
      } else if (this.invoiceExport.timeFlag === 4) {
        // 选择统计维度为：年
        let inputDate = this.invoiceExport.dateMonthAndYear;
        if (inputDate === null || inputDate === "" || inputDate === undefined) {
          this.$message.error("请选择导出发票统计年份！");
          return false;
        }

        dateBeginObj = new Date(inputDate);
        dateBeginObj.setMonth(0);
        dateBeginObj.setDate(1);
        dateEndObj = new Date();
        dateEndObj.setFullYear(inputDate.getFullYear() + 1);
        dateEndObj.setMonth(0);
        dateEndObj.setDate(0);
      } else {
        this.$message.error("导出发票统计日期维度选择错误！");
        return false;
      }

      let beginTime = this.dateFormat(dateBeginObj, "yyyy-MM-dd HH:mm:ss");
      let endTime = this.dateFormat(
        new Date(
          dateEndObj.getFullYear(),
          dateEndObj.getMonth(),
          dateEndObj.getDate(),
          "23",
          "59",
          "59"
        ),
        "yyyy-MM-dd HH:mm:ss"
      );
      this.beginDateTime = beginTime;
      this.endDateTime = endTime;
      let invoiceState = "";
      if (invoiceSelectOption == 2) {
        // 正数发票清单 = 正数开具成功
        invoiceState = 3;
      } else if (invoiceSelectOption == 3) {
        // 负数发票清单 = 负数开具成功
        invoiceState = 4;
      } else if (invoiceSelectOption == 4) {
        // 正数发票废票清单 = 正数已作废
        invoiceState = 5;
      } else if (invoiceSelectOption == 5) {
        // 负数发票废票清单 = 负数已作废
        invoiceState = 6;
      } else if (invoiceSelectOption == 6) {
        // 空白作废发票清单 = 空白作废发票
        invoiceState = 7;
      }
      let _this = this;
      let funcInvoiceQuery = function () {
        _this.loading = true;
        invoiceQuery({
          invoiceCategory: invoiceCategory,
          status: invoiceState,
          deviceType: _this.search.invoiceDevice.deviceType,
          taxDiscId: _this.search.invoiceDevice.taxDiscId,
          invoiceDateBegin: beginTime,
          invoiceDateEnd: endTime,
          pageNum: 1,
          pageSize: 20000,
        })
          .then((val) => {
            // 设置打印信息
            let titleTemp = GetInvoiceCategoryLabel(invoiceCategory);
            let qdNameTemp = GetInvoiceSelectOptionLabel(invoiceSelectOption);
            let qdDateBegin = _this.dateFormat(
              new Date(beginTime),
              "yyyy年MM月dd日"
            );
            let qdDateEnd = _this.dateFormat(
              new Date(endTime),
              "yyyy年MM月dd日"
            );

            _this.printFPQSHZD.title = `${titleTemp}明细表`;
            _this.printFPQSHZD.qdName = `${qdNameTemp}（${qdDateBegin} - ${qdDateEnd}）`;

            _this.invoiceExport.resultList = val.data.records;
            _this.loading = false;
          })
          .catch((err) => {
            _this.$message.error(err);
            _this.loading = false;
          });
      };

      let funcInvoiceReports = function () {
        _this.loading = true;

        InvoiceReports({
          invoiceCategory: invoiceCategory,
          deviceType: _this.search.invoiceDevice.deviceType,
          taxDiscId: _this.search.invoiceDevice.taxDiscId,
          invoiceDateBegin: beginTime,
          invoiceDateEnd: endTime,
        })
          .then((val) => {
            _this.loading = false;
            // 记录查询数据月份；导出数据时使用；
            _this.print.searchMonth = beginTime;
            _this.print.searchMonthEnd = endTime;
            // 记录查询结果的发票种类名称
            if (invoiceCategory == null || invoiceCategory == "") {
              _this.print.fileName = "增值税发票汇总表";
              _this.print.title = "增值税发票汇总表";
            } else {
              _this.print.fileName =
                "增值税发票汇总表-" + GetInvoiceCategoryLabel(invoiceCategory);
              _this.print.title =
                GetInvoiceCategoryLabel(invoiceCategory) + "汇总表";
            }

            _this.tableHead = val.data.reportsHeaders;
            _this.search.resultInvoiceReportsList = [
              {
                totalFapiaoCnt: val.data.totalFapiaoCnt,
                blueInvoiceCnt: val.data.blueInvoiceCnt,
                blueInvalidCnt: val.data.blueInvalidCnt,
                redInvoiceCnt: val.data.redInvoiceCnt,
                redInvalidCnt: val.data.redInvalidCnt,
                blankInvalidCnt: val.data.blankInvalidCnt,
              },
            ];
            _this.search.resultTaxRateReportsList = val.data.reportsData;

            let beginTime2 = _this.dateFormat(
              new Date(beginTime),
              "yyyy-MM-dd"
            );
            let endTime2 = _this.dateFormat(new Date(endTime), "yyyy-MM-dd");
            return SKServer.getInvoiceStati(beginTime2, endTime2);
          })
          .then((val) => {
            if (val.data) {
              for (const item of val.data) {
                if (item.invoice_type_code == invoiceCategory) {
                  let temp = JSON.parse(
                    JSON.stringify(_this.search.resultInvoiceReportsList)
                  );

                  temp[0].begin_quantity = item.begin_quantity;
                  temp[0].purchase_quantity = item.purchase_quantity;
                  temp[0].final_quantity = item.final_quantity;
                  temp[0].return_quantity = item.return_quantity;

                  _this.search.resultInvoiceReportsList = temp;

                  break;
                }
              }
            }
          })
          .catch((err) => {
            _this.loading = false;
            _this.$message.error(err);
          });
      };

      if (invoiceSelectOption == 1) {
        funcInvoiceReports();
      } else {
        funcInvoiceQuery();
      }
    },
    handleExportWord() {
      if (this.print.searchMonth == null || this.print.searchMonth == "") {
        this.$message.error("无查询数据，无法导出发票汇总统计！");
        return false;
      }
      let titleTemp = `${this.print.title}`;
      let zbsjTemp = this.dateFormat(new Date(), "yyyy年MM月dd日");
      let ssqjBeginTemp = this.dateFormat(
        new Date(this.print.searchMonth),
        "yyyy年MM月dd日"
      );
      let ssqjBeginEnd = this.dateFormat(
        new Date(this.print.searchMonthEnd),
        "yyyy年MM月dd日"
      );
      let company = JSON.parse(cache.getSession("company"));
      let entTaxId = company.entTaxId;
      let entName = company.entName;
      let dzdhTemp = company.entAddress + " " + company.entPhone;
      $("#title").html(titleTemp);
      $("#zbsj").html(zbsjTemp);
      $("#ssqj").html(ssqjBeginTemp + " - " + ssqjBeginEnd);
      $("#nsrdjh").html(entTaxId);
      $("#qymc").html(entName);
      $("#dzdh").html(dzdhTemp);

      // 设置发票统计数据
      if (this.search.resultInvoiceReportsList) {
        let invoiceReports = this.search.resultInvoiceReportsList[0];
        $("#word_blueInvoiceCnt").html(invoiceReports.blueInvoiceCnt);
        $("#word_blueInvalidCnt").html(invoiceReports.blueInvalidCnt);
        $("#word_blankInvalidCnt").html(invoiceReports.blankInvalidCnt);
        $("#word_redInvoiceCnt").html(invoiceReports.redInvoiceCnt);
        $("#word_redInvalidCnt").html(invoiceReports.redInvalidCnt);
        $("#word_blankInvalidCnt").html(invoiceReports.blankInvalidCnt);

        // 期初库存份数
        $("#word_begin_quantity").html(invoiceReports.begin_quantity);
        // 期末库存份数
        $("#word_final_quantity").html(invoiceReports.final_quantity);
        // 购进发票份数
        $("#word_purchase_quantity").html(invoiceReports.purchase_quantity);
        // 退回发票份数
        $("#word_return_quantity").html(invoiceReports.return_quantity);
      }

      // 清空税率统计表格；
      $("#word_export_sltj").empty();

      let header_list = this.tableHead;
      let colWidth = 90 / header_list.length; // 序号列使用10%
      let header_tds = `<td style="width:10%">序号</td>`;
      for (const item of header_list) {
        header_tds += `<td style="width:${colWidth}%">${item.label}</td>`;
      }
      let header_tr = `<tr>${header_tds}</tr>`;
      // 添加表头
      $("#word_export_sltj").append(header_tr);

      let data_list = this.search.resultTaxRateReportsList;
      for (let index = 0; index < data_list.length; index++) {
        let row_tds = `<td>${index + 1}</td>`;
        const element = data_list[index];
        for (const item of header_list) {
          let valTemp = element.hasOwnProperty(item.key)
            ? element[item.key]
            : "0";
          row_tds += `<td>${valTemp}</td>`;
        }
        let row_tr = `<tr>${row_tds}</tr>`;
        // 添加数据行
        $("#word_export_sltj").append(row_tr);
      }
      let _this = this;
      setTimeout(function () {
        $("#word_export").wordExport(_this.print.fileName);
      }, 300);
    },
    handleExportExcel() {
      let tables = [
        { id: "#exportTable1", sheetName: "发票统计" },
        { id: "#exportTable2", sheetName: "税率统计" },
      ];

      const wb = XLSX.utils.book_new();
      for (const item of tables) {
        let tableId = item.id;
        let sheetName = item.sheetName;

        // 转换成excel时，使用原始格式
        let xlsxParam = { raw: true };
        /* generate workbook object from table */
        let tempwb = XLSX.utils.table_to_book(
          document.querySelector(tableId),
          xlsxParam
        );

        XLSX.utils.book_append_sheet(
          wb,
          tempwb.Sheets[tempwb.SheetNames[0]],
          sheetName
        );
      }

      /* get binary string as output */
      let wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          "发票汇总统计.xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") {
          console.log(e, wbout);
        }
      }
      return wbout;
    },
    handleInvoiceSelectOptionChange() {
      // 清空已查询数据；
      this.invoiceExport.resultList = [];
      this.search.resultInvoiceReportsList = [];
      this.search.resultTaxRateReportsList = [];
    },
    dateFormat(date, fmt) {
      // 小时只支持24小时制
      var o = {
        "M+": date.getMonth() + 1, // 月份
        "d+": date.getDate(), // 日
        "H+": date.getHours(), // 24小时,
        "m+": date.getMinutes(), // 分
        "s+": date.getSeconds(), // 秒
        "q+": Math.floor((date.getMonth() + 3) / 3), // 季度
        S: date.getMilliseconds(), // 毫秒
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(
          RegExp.$1,
          (date.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
        }
      }
      return fmt;
    },
    // 明细表导出
    async invoiceListExport() {
      this.loadText = "文件生成中，请稍等！";
      let exportType = null;
      if (this.invoiceExport.invoiceSelectOption === 2) {
        exportType = 3;
      }
      if (this.invoiceExport.invoiceSelectOption === 3) {
        exportType = 4;
      }
      if (this.invoiceExport.invoiceSelectOption === 4) {
        exportType = 5;
      }
      if (this.invoiceExport.invoiceSelectOption === 5) {
        exportType = 6;
      }
      if (this.invoiceExport.invoiceSelectOption === 6) {
        exportType = 7;
      }
      this.loading = true;
      let res = await invoiceExportCommit({
        exportType: exportType,
        invoiceCategory: this.invoiceExport.invoiceCategory,
        beginDate: this.beginDateTime,
        endDate: this.endDateTime,
      });
      if (res) {
        this.recordId = res.data.recordId;
        let _this = this;
        _this.timer = setTimeout(function () {
          _this.getExportInfo();
        }, 10000);
      } else {
        this.loading = false;
        this.loadText = "加载中，请稍等！";
        this.$message.error(res.msg);
      }
    },
    // 获取导出的状态
    async getExportInfo() {
      let res = await invoiceExportRecordStatus(this.recordId);
      if (res) {
        if (res.code === 0) {
          let status = 1;
          if (res.data.status === 2) {
            this.loading = false;
            this.loadText = "加载中，请稍等！";
            console.log("下载信息");
            status = 2;
            if (res.data.fileUrl) {
              window.open(res.data.fileUrl); // 新标签打开生成的pdf
            }
            clearInterval(this.timer);
          }
        } else {
          this.loading = false;
          this.loadText = "加载中，请稍等！";
          this.$message.error(res.msg);
        }
      } else {
        this.loading = false;
        this.loadText = "加载中，请稍等！";
        this.$message.error(res.msg);
      }
    },
    tableHeaderStyle({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return "color: black; font-weight: 270";
      }
    },
  },
};
</script>

<style scoped>
.Row {
  display: table;
  width: 100%; /*Optional*/
  table-layout: fixed; /*Optional*/
  /* border-spacing: 10px; Optional */
}

.Column {
  display: table-cell;
  /* background-color: red; Optional */
}
</style>
