<template>
    <div id="invoice_summary" v-loading="loading" element-loading-text="拼命加载中......请稍等">
        <el-container>
            <el-form ref="form" style="width: 100%;">
                <el-row :gutter="30">
                    <el-col :span="16">
                        <el-row :gutter="10">
                            <el-col :span="8">
                                <el-form-item>
                                    <el-select
                                        v-model="search.invoiceCategory"
                                        placeholder="请选择发票种类"
                                        clearable
                                        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="8">
                                <el-form-item>
                                    <el-select
                                        v-model="search.invoiceDevice"
                                        value-key="deviceKey"
                                        placeholder="请选择开票设备"
                                        style="width: 100%;"
                                    >
                                        <el-option
                                            v-for="item in devices"
                                            :key="item.deviceKey"
                                            :label="item.deviceLabel"
                                            :value="item"
                                        ></el-option>
                                    </el-select>
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item>
                                    <el-date-picker
                                        v-model="search.dateRange"
                                        type="daterange"
                                        unlink-panels
                                        range-separator="-"
                                        start-placeholder="开始日期"
                                        end-placeholder="结束日期"
                                        style="width: 100%;"
                                    ></el-date-picker>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-col>
                    <el-col :span="8">
                        <div>
                            <el-button @click="handleSearch" type="primary" icon="el-icon-search">搜索</el-button>
                            <el-button @click="handleResetSearch">重置</el-button>
                        </div>
                    </el-col>
                </el-row>
            </el-form>
        </el-container>
        <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 label="期初库存份数" align="center"></el-table-column>
                    <el-table-column label="购进发票份数" align="center"></el-table-column>
                    <el-table-column label="退回发票份数" align="center"></el-table-column>
                    <el-table-column 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="空白废票份数"></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 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>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>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>0</span>&#9;&#9;&#9;&#9;&#9;期末库存份数&nbsp;<span>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>
</template>

<script>
import FileSaver from "file-saver";
import XLSX from "xlsx";

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

import { InvoiceReports } from "@/api/invoice_ext";

import { GetLocalDevices, GetLocalDevice } from "@/api/ent_device";

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

// 发票类别列表
const invoiceCategoryOptions = [
    {
        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;
}

export default {
    name: "invoice_summary",
    data() {
        return {
            loading: false,
            invoiceCategoryOptions: invoiceCategoryOptions,
            devices: GetLocalDevices(),
            print: {
                fileName: "",
                title: "",
                searchMonth: "", // 查询开始时间
                searchMonthEnd: "", // 查询结束时间
            },
            search: {
                invoiceCategory: "",
                invoiceDevice: GetLocalDevice(
                    JSON.parse(cache.getSession("company")).defaultInvoiceDevice
                ),
                dateRange: [
                    DateHelper.LocalCurrentMonthStart(),
                    DateHelper.LocalCurrentMonthEnd(),
                ],
                resultInvoiceReportsList: [], // 发票报告查询结果列表
                resultTaxRateReportsList: [], // 税率报告查询结果列表
            },
            tableHead: [],
        };
    },
    created() {
        this.callInvoiceReports();
    },
    methods: {
        pageIndex(index) {
            return index + 1;
        },
        fmtAmount(row, column, cellValue) {
            return cellValue == null ||
                cellValue === undefined ||
                cellValue === ""
                ? "0.00"
                : cellValue;
        },
        handleSearch() {
            this.callInvoiceReports();
        },
        handleResetSearch() {
            this.search.invoiceCategory = "";
            this.search.dateRange = [
                DateHelper.LocalCurrentMonthStart(),
                DateHelper.LocalCurrentMonthEnd(),
            ];
        },
        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_totalFapiaoCnt").html(invoiceReports.totalFapiaoCnt);
            }

            // 清空税率统计表格；
            $("#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;
        },
        callInvoiceReports() {
            let beginTime = "";
            let endTime = "";
            if (this.search.dateRange instanceof Array) {
                beginTime = this.search.dateRange[0];
                endTime = this.search.dateRange[1];
                beginTime = this.dateFormat(new Date(beginTime), "yyyy-MM-dd");
                endTime = this.dateFormat(new Date(endTime), "yyyy-MM-dd");
            }
            this.loading = true;
            let _this = this;
            InvoiceReports({
                invoiceCategory: this.search.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 (
                        this.search.invoiceCategory == null ||
                        this.search.invoiceCategory == ""
                    ) {
                        _this.print.fileName = "增值税发票汇总表";
                        _this.print.title = "增值税发票汇总表";
                    } else {
                        _this.print.fileName =
                            "增值税发票汇总表-" +
                            GetInvoiceCategoryLabel(
                                this.search.invoiceCategory
                            );
                        _this.print.title =
                            GetInvoiceCategoryLabel(
                                this.search.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;
                })
                .catch((err) => {
                    _this.loading = false;
                    _this.$message.error(err);
                });
        },
        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;
        },
    },
};
</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 */
}
.print-table {
    width: 100%;
    font-size: 14px;
    text-align: center;
    border-top: 1px solid #999;
    border-left: 1px solid #999;
    border-spacing: 0; /*去掉单元格间隙*/
}

.print-table td {
    padding: 10px 30px;
    border-bottom: 1px solid #999;
    border-right: 1px solid #999;
}
</style>
