<template>
    <div
        id="invoice_summary_djz"
        v-loading="loading"
        element-loading-text="拼命加载中......请稍等"
    >
        <el-form label-position="top" style="width: 100%">
            <el-row :gutter="20">
                <el-col :span="8">
                    <el-form-item label="客户名称：">
                        <el-input
                            v-model="search.customerName"
                            placeholder="请输入"
                        ></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="2">
                    <el-form-item label="统计维度：">
                        <el-select
                            v-model="search.timeFlag"
                            placeholder="请选择"
                        >
                            <el-option
                                v-for="item in timeFlagOptions"
                                :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-date-picker
                            v-model="search.statisticsDate"
                            :type="dateType"
                            :clearable="false"
                            range-separator="-"
                            placeholder="选择日期"
                            style="width: 100%"
                        >
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item>
                        <span slot="label">
                            <span>&nbsp;&nbsp;</span>
                        </span>
                        <el-button
                            @click="handleSearch"
                            type="primary"
                            icon="el-icon-search"
                        >
                            搜索
                        </el-button>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div style="margin-bottom: 10px">
            <el-button
                type="primary"
                icon="el-icon-document"
                @click="handleExportExcel"
            >
                导出EXCEL文件（表格当前页面）</el-button
            >
        </div>
        <div style="background-color: #909399; padding: 10px 10px">
            <span style="color: white">使用提示：非实时数据，每天凌晨更新</span>
        </div>
        <br />
        <el-table
            id="searchResultTable"
            ref="multipleTable"
            :data="search.resultList"
            border
            stripe
            style="width: 100%"
            @selection-change="handleSearchResultCheckChange"
            :height="tableHeight"
        >
            <!-- <el-table-column
                type="selection"
                align="center"
                width="55"
            ></el-table-column> -->
            <el-table-column
                type="index"
                :index="pageIndex"
                align="center"
                label="序号"
                width="50"
            ></el-table-column>
            <el-table-column
                prop="entName"
                label="企业名称"
                width="240"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="entTaxOfficeName"
                label="所属税局"
                width="280"
                :formatter="fmtInvoiceCategory"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="invoiceCategory"
                label="发票种类"
                width="140"
                :formatter="fmtInvoiceCategory"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="beginningQuantity"
                label="期初库存份数"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="purchaseQuantity"
                label="购进发票份数"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="returnQuantity"
                label="退回发票份数"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="finalQuantity"
                label="期末库存份数"
                width="120"
                align="center"
                sortable
            ></el-table-column>
            <el-table-column
                prop="blueInvoiceCnt"
                label="正数发票份数"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="redInvoiceCnt"
                label="负数发票份数"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="blueInvalidCnt"
                label="正数废票份数"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="redInvalidCnt"
                label="负数废票份数"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="statisticsDate"
                label="统计维度日期"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="lastUpdateTime"
                label="更新时间"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="realInvoiceAmt"
                label="实际销项金额"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="realInvoiceTaxes"
                label="实际销项税额"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>

            <el-table-column
                prop="blueInvoiceAmt"
                label="销项正数金额"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="blueInvoiceTaxes"
                label="销项正数税额"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="blueInvalidAmt"
                label="销项正废金额"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="blueInvalidTaxes"
                label="销项正废税额"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="redInvoiceAmt"
                label="销项负数金额"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="redInvoiceTaxes"
                label="销项负数税额"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="redInvalidAmt"
                label="销项负废金额"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="redInvalidTaxes"
                label="销项负废税额"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="entTaxId"
                label="纳税人识别号"
                width="180"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="deviceType"
                label="税盘类型"
                width="100"
                :formatter="fmtDeviceType"
                show-overflow-tooltip
                sortable
            ></el-table-column>
            <el-table-column
                prop="taxDiscId"
                label="税盘号"
                width="120"
                show-overflow-tooltip
                sortable
            ></el-table-column>
        </el-table>
        <br />
        <el-row type="flex" :gutter="20">
            <el-col :span="12"></el-col>
            <el-col :span="12">
                <div style="text-align: right">
                    <el-pagination
                        layout="total, sizes, prev, pager, next"
                        :current-page="search.resultPagination.currentPage"
                        :page-sizes="search.resultPagination.pageSizes"
                        :page-size="search.resultPagination.pageSize"
                        :total="search.resultPagination.total"
                        @size-change="handleSearchResultSizeChange"
                        @current-change="handleSearchResultCurrentChange"
                    ></el-pagination>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import { djzEntInvoiceSummary } from "@/api/rpt";
import DateHelper from "@/utils/date";
import FileSaver from "file-saver";
import XLSX from "xlsx";

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

// 设备类型列表
const deviceTypeOptions = [
    {
        value: 1,
        label: "证书",
    },
    {
        value: 2,
        label: "税控盘",
    },
    {
        value: 3,
        label: "金税盘",
    },
    {
        value: 4,
        label: "税控ukey",
    },
    {
        value: 5,
        label: "税控服务器",
    },
];

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

export default {
    name: "invoice_summary_djz",
    data() {
        return {
            loading: false,
            timeFlagOptions: timeFlagOptions,
            search: {
                customerName: "", // 客户名称
                timeFlag: timeFlagOptions[0].value, // 统计维度标识,默认统计维度：天
                statisticsDate: DateHelper.Yesterday(), // 默认昨天；
                resultList: [],
                resultMultipleSelection: [],
                resultPagination: {
                    currentPage: 1,
                    pageSizes: [10, 30, 50, 100],
                    pageSize: 10,
                    total: 0,
                },
            },
            tableHeight: "",
        };
    },
    created() {
        this.tableHeight = window.innerHeight - 250;
        this.callDJZEntInvoiceSummary(
            this.search.resultPagination.currentPage,
            this.search.resultPagination.pageSize
        );
    },
    mounted() {
        this.tableHeight = window.innerHeight - 250;
        window.onresize = () => {
            return (() => {
                this.tableHeight = window.innerHeight - 250;
            })();
        };
    },
    computed: {
        dateType: function () {
            if (this.search.timeFlag === 1) {
                return "date";
            } else if (this.search.timeFlag === 2) {
                return "month";
            } else if (this.search.timeFlag === 3) {
                // return "month";
            } else if (this.search.timeFlag === 4) {
                return "year";
            } else {
                return "date";
            }
        },
    },
    methods: {
        pageIndex(index) {
            let currentPage = this.search.resultPagination.currentPage; //当前页码，具体看组件取值
            let pageSize = this.search.resultPagination.pageSize; //每页条数，具体是组件取值
            return index + 1 + (currentPage - 1) * pageSize;
        },
        fmtInvoiceCategory(row, column, cellValue) {
            let result = cellValue;
            for (const item of invoiceCategoryOptions) {
                if (item.value == cellValue) {
                    result = item.label;
                    break;
                }
            }
            return result;
        },
        fmtDeviceType(row, column, cellValue) {
            let result = cellValue;
            for (const item of deviceTypeOptions) {
                if (item.value == cellValue) {
                    result = item.label;
                    break;
                }
            }
            return result;
        },
        handleSearch() {
            this.callDJZEntInvoiceSummary(
                1,
                this.search.resultPagination.pageSize
            );
        },
        handleSearchResultCheckChange(val) {
            this.search.resultMultipleSelection = val;
            console.log("选中数据：");
            console.log(this.search.resultMultipleSelection);
        },
        handleSearchResultSizeChange(val) {
            this.callDJZEntInvoiceSummary(1, val);
        },
        handleSearchResultCurrentChange(val) {
            this.callDJZEntInvoiceSummary(
                val,
                this.search.resultPagination.pageSize
            );
        },
        callDJZEntInvoiceSummary(pageNum = 1, pageSize = 10) {
            // 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");
            // }

            if (!this.search.statisticsDate) {
                this.$message.error("统计日期为必选项，请检查后重试！");
                return false;
            }

            let statisticsDateTemp = this.search.statisticsDate;
            if (this.search.timeFlag === 1) {
                statisticsDateTemp = this.dateFormat(
                    new Date(statisticsDateTemp),
                    "yyyy-MM-dd"
                );
            } else if (this.search.timeFlag === 2) {
                statisticsDateTemp = this.dateFormat(
                    new Date(statisticsDateTemp),
                    "yyyy-MM"
                );
            } else if (this.search.timeFlag === 3) {
                // return "month";
            } else if (this.search.timeFlag === 4) {
                statisticsDateTemp = this.dateFormat(
                    new Date(statisticsDateTemp),
                    "yyyy"
                );
            }

            this.loading = true;
            let _this = this;
            djzEntInvoiceSummary({
                entName: this.search.customerName,
                timeFlag: this.search.timeFlag,
                statisticsDate: statisticsDateTemp,
                pageNum: pageNum,
                pageSize: pageSize,
            })
                .then((val) => {
                    _this.search.resultPagination.total = val.data.total;
                    _this.search.resultPagination.pageSize = val.data.size;
                    _this.search.resultPagination.currentPage =
                        val.data.current;
                    _this.search.resultList = val.data.records;
                    _this.loading = false;
                })
                .catch((err) => {
                    _this.$message.error(err);
                    _this.loading = false;
                });
        },
        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;
        },
        // 导出excel
        handleExportExcel() {
            const wb = XLSX.utils.book_new();

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

            XLSX.utils.book_append_sheet(
                wb,
                tempwb.Sheets[tempwb.SheetNames[0]],
                "客户发票汇总统计"
            );

            /* 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;
        },
    },
};
</script>

<style scoped>
</style>
