<template>
    <div
        id="invoice_recovery"
        v-loading="loading"
        element-loading-text="拼命加载中......请稍等"
    >
        <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="recovery.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="3">
                        <el-form-item label="起始日期：">
                            <el-date-picker
                                v-model="recovery.beginDate"
                                type="date"
                                placeholder="选择日期"
                                style="width: 100%"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="结束日期：">
                            <el-date-picker
                                v-model="recovery.endDate"
                                type="date"
                                placeholder="选择日期"
                                style="width: 100%"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item>
                            <span slot="label" style="color: #909399">
                                <i class="el-icon-info"></i>
                                <span
                                    >&nbsp;&nbsp;选择时间越长，发票修复耗时越久！</span
                                >
                            </span>
                            <el-button
                                @click="handleInvoiceRecovery"
                                type="primary"
                                icon="el-icon-arrow-right"
                                >发票修复</el-button
                            >
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-card>
        <br />
        <el-card>
            <div slot="header">
                <span>发票修复历史</span>
            </div>
            <el-form label-position="top" style="width: 100%">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-form-item label="开票设备：">
                            <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="3">
                        <el-form-item label="起始日期：">
                            <el-date-picker
                                v-model="search.beginDate"
                                type="date"
                                placeholder="选择日期"
                                style="width: 100%"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="3">
                        <el-form-item label="结束日期：">
                            <el-date-picker
                                v-model="search.endDate"
                                type="date"
                                placeholder="选择日期"
                                style="width: 100%"
                            >
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item>
                            <span slot="label">&nbsp;</span>
                            <el-button
                                @click="handleSearch"
                                type="primary"
                                icon="el-icon-search"
                                >搜索</el-button
                            >
                            <el-button @click="handleResetSearch"
                                >重置</el-button
                            >
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <el-container>
                <el-table
                    :data="search.resultList"
                    border
                    stripe
                    height="550px"
                    style="width: 100%"
                >
                    <el-table-column
                        type="index"
                        :index="pageIndex"
                        align="center"
                        label="序号"
                        width="50"
                    ></el-table-column>
                    <el-table-column
                        prop="beginDate"
                        label="同步数据的起始时间"
                        width="160"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                        prop="endDate"
                        label="同步数据的截止时间"
                        width="160"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                        prop="totalCnt"
                        label="记录总数"
                    ></el-table-column>
                    <el-table-column
                        prop="handleCnt"
                        label="处理成功数量"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                        prop="statusMemo"
                        label="状态"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                        prop="statusChangeTime"
                        label="状态改变时间"
                        width="160"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                        prop="createTime"
                        label="创建时间"
                        width="160"
                        show-overflow-tooltip
                    ></el-table-column>
                    <el-table-column
                        label="操作"
                        width="180"
                        align="center"
                        fixed="right"
                    >
                        <template slot-scope="scope">
                            <el-button
                                @click="
                                    handleShowRecoveryRecordsDetails(scope.row)
                                "
                                type="primary"
                                >查看详情</el-button
                            >
                        </template>
                    </el-table-column>
                </el-table>
            </el-container>
            <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>
        </el-card>
        <el-dialog
            title="发票修复详情"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="300mm"
            top="10vh"
            :visible.sync="recoveryRecordsDetails.dialogVisible"
            @opened="handleRecoveryRecordsDetailsDialogOpened"
            @closed="handleRecoveryRecordsDetailsDialogClosed"
        >
            <div
                v-loading="recoveryRecordsDetails.loading"
                element-loading-text="拼命加载中......请稍等"
            >
                <el-form style="width: 100%">
                    <el-row :gutter="10">
                        <el-col :span="6">
                            <el-form-item>
                                <el-select
                                    v-model="
                                        recoveryRecordsDetails.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="6">
                            <el-form-item>
                                <el-input
                                    v-model="
                                        recoveryRecordsDetails.search
                                            .invoiceCode
                                    "
                                    clearable
                                    placeholder="请输入..."
                                >
                                    <template slot="prepend">发票代码</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item>
                                <el-input
                                    v-model="
                                        recoveryRecordsDetails.search
                                            .invoiceNumber
                                    "
                                    clearable
                                    placeholder="请输入..."
                                >
                                    <template slot="prepend">发票号码</template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-button
                                @click="handleRecoveryRecordsDetailsSearch"
                                type="primary"
                                icon="el-icon-search"
                                >搜索</el-button
                            >
                        </el-col>
                    </el-row>
                </el-form>
                <br />
                <div>
                    <el-table
                        :data="recoveryRecordsDetails.search.resultList"
                        height="550px"
                        border
                        stripe
                        style="width: 100%"
                    >
                        <el-table-column
                            type="index"
                            :index="pageIndex"
                            align="center"
                            label="序号"
                            width="50"
                        ></el-table-column>
                        <el-table-column
                            prop="invoiceCategory"
                            label="发票种类"
                            show-overflow-tooltip
                            :formatter="fmtInvoiceCategory"
                        ></el-table-column>
                        <el-table-column
                            prop="invoiceType"
                            label="发票类型"
                            show-overflow-tooltip
                            :formatter="fmtInvoiceType"
                        ></el-table-column>
                        <el-table-column
                            prop="invoiceCode"
                            label="发票代码"
                            show-overflow-tooltip
                        ></el-table-column>
                        <el-table-column
                            prop="invoiceNumber"
                            label="发票号码"
                            show-overflow-tooltip
                        ></el-table-column>
                        <el-table-column
                            prop="invoiceDate"
                            label="开票日期"
                            show-overflow-tooltip
                        ></el-table-column>
                    </el-table>
                </div>
                <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="
                                    recoveryRecordsDetails.search
                                        .resultPagination.currentPage
                                "
                                :page-sizes="
                                    recoveryRecordsDetails.search
                                        .resultPagination.pageSizes
                                "
                                :page-size="
                                    recoveryRecordsDetails.search
                                        .resultPagination.pageSize
                                "
                                :total="
                                    recoveryRecordsDetails.search
                                        .resultPagination.total
                                "
                                @size-change="
                                    handleRecordsDetailsSearchResultSizeChange
                                "
                                @current-change="
                                    handleRecordsDetailsSearchResultCurrentChange
                                "
                            ></el-pagination>
                        </div>
                    </el-col>
                </el-row>
            </div>
        </el-dialog>
        <el-dialog
            :show-close="false"
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            width="400px"
            :visible.sync="recoveryProgress.dialogVisible"
            @opened="handleRecoveryProgressDialogOpened"
            @closed="handleRecoveryProgressDialogClosed"
        >
            <div style="text-align: center">
                <el-progress
                    type="circle"
                    :percentage="recoveryProgress.percentage"
                ></el-progress>
                <div style="margin-top: 30px; font-size: 16px">
                    发票修复中......请稍等
                </div>
            </div>
        </el-dialog>
    </div>
</template>

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

import {
    invoiceSyncCommit,
    invoiceSyncRecords,
    invoiceSyncDetails,
    invoiceSyncRecordProgress,
} from "@/api/invoice_sync";

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

// 发票种类列表
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_recovery",
    data() {
        return {
            loading: false,
            invoiceCategoryOptions: invoiceCategoryOptions,
            devices: GetLocalDevices(),
            recovery: {
                invoiceDevice: GetLocalDevice(
                    JSON.parse(cache.getSession("company")).defaultInvoiceDevice
                ),
                beginDate: DateHelper.LocalCurrentMonthStart(),
                endDate: DateHelper.LocalCurrentMonthEnd(),
                // dateRange: [
                //     DateHelper.LocalCurrentMonthStart(),
                //     DateHelper.LocalCurrentMonthEnd(),
                // ],
            },
            search: {
                invoiceDevice: GetLocalDevice(
                    JSON.parse(cache.getSession("company")).defaultInvoiceDevice
                ),
                beginDate: DateHelper.LocalCurrentMonthStart(),
                endDate: DateHelper.LocalCurrentMonthEnd(),
                // dateRange: [
                //     DateHelper.LocalCurrentMonthStart(),
                //     DateHelper.LocalCurrentMonthEnd(),
                // ],
                resultList: [],
                resultPagination: {
                    currentPage: 1,
                    pageSizes: [10, 30, 50, 100],
                    pageSize: 10,
                    total: 0,
                },
            },
            recoveryRecordsDetails: {
                loading: false,
                dialogVisible: false,
                selectRow: {}, // 用户选中的发票数据；
                search: {
                    invoiceCategory: "",
                    invoiceCode: "",
                    invoiceNumber: "",
                    resultList: [],
                    resultPagination: {
                        currentPage: 1,
                        pageSizes: [10, 30, 50, 100],
                        pageSize: 10,
                        total: 0,
                    },
                },
            },
            recoveryProgress: {
                dialogVisible: false,
                recordId: "", // 同步记录主键id，用于查询发票修复记录进度
                percentage: 0,
            },
        };
    },
    created() {
        this.callInvoiceSyncRecords(
            this.search.resultPagination.currentPage,
            this.search.resultPagination.pageSize
        );
    },
    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) {
            return GetInvoiceCategoryLabel(cellValue);
        },
        fmtInvoiceType(row, column, cellValue) {
            let result = cellValue;
            if (cellValue == 0) {
                result = "正数发票";
            } else if (cellValue == 1) {
                result = "负数发票";
            }
            return result;
        },
        // 发票修复
        handleInvoiceRecovery() {
            let beginTime = this.recovery.beginDate;
            let endTime = this.recovery.endDate;
            if (beginTime) {
                beginTime = this.dateFormat(
                    new Date(beginTime),
                    "yyyy-MM-dd HH:mm:ss"
                );
            }
            if (endTime) {
                let endTimeObj = new Date(endTime);
                endTime = this.dateFormat(
                    new Date(
                        endTimeObj.getFullYear(),
                        endTimeObj.getMonth(),
                        endTimeObj.getDate(),
                        "23",
                        "59",
                        "59"
                    ),
                    "yyyy-MM-dd HH:mm:ss"
                );
            }
            if (beginTime && endTime) {
                if (DateHelper.ValidateDateRange(beginTime, endTime) == false) {
                    this.$message.error(
                        "起始日期与结束日期不合法，请确定后重试！"
                    );
                    return false;
                }
            } else {
                this.$message.error(
                    "起始日期与结束日期为必输项，请确定后重试！"
                );
                return false;
            }
            this.loading = true;
            let _this = this;
            invoiceSyncCommit({
                deviceType: this.recovery.invoiceDevice.deviceType,
                taxDiscId: this.recovery.invoiceDevice.taxDiscId,
                beginDate: beginTime,
                endDate: endTime,
            })
                .then((val) => {
                    _this.recoveryProgress.recordId = val.data.recordId;
                    _this.loading = false;
                    _this.recoveryProgress.dialogVisible = true;
                })
                .catch((err) => {
                    _this.$message.error(err);
                    _this.loading = false;
                });
        },
        // 发票修复历史查询
        handleSearch() {
            this.callInvoiceSyncRecords(
                1,
                this.search.resultPagination.pageSize
            );
        },
        // 发票修复历史重置
        handleResetSearch() {
            this.search.invoiceDevice = GetLocalDevice(
                JSON.parse(cache.getSession("company")).defaultInvoiceDevice
            );
            this.search.beginDate = null;
            this.search.endDate = null;
        },
        handleSearchResultSizeChange(val) {
            this.callInvoiceSyncRecords(1, val);
        },
        handleSearchResultCurrentChange(val) {
            this.callInvoiceSyncRecords(
                val,
                this.search.resultPagination.pageSize
            );
        },
        // 调用分页查询同步的记录接口
        callInvoiceSyncRecords(pageNum, pageSize) {
            this.loading = true;
            let _this = this;
            this.callInvoiceSyncRecordsTask(pageNum, 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;
                });
        },
        // 调用分页查询同步的记录接口 任务
        callInvoiceSyncRecordsTask(pageNum, pageSize) {
            let beginTime = this.search.beginDate;
            let endTime = this.search.endDate;
            if (beginTime) {
                beginTime = this.dateFormat(
                    new Date(beginTime),
                    "yyyy-MM-dd HH:mm:ss"
                );
            }
            if (endTime) {
                let endTimeObj = new Date(endTime);
                endTime = this.dateFormat(
                    new Date(
                        endTimeObj.getFullYear(),
                        endTimeObj.getMonth(),
                        endTimeObj.getDate(),
                        "23",
                        "59",
                        "59"
                    ),
                    "yyyy-MM-dd HH:mm:ss"
                );
            }
            if (beginTime && endTime) {
                if (DateHelper.ValidateDateRange(beginTime, endTime) == false) {
                    return Promise.reject(
                        "起始日期与结束日期不合法，请确定后重试！"
                    );
                }
            }
            return invoiceSyncRecords({
                deviceType: this.search.invoiceDevice.deviceType,
                taxDiscId: this.search.invoiceDevice.taxDiscId,
                createTimeBegin: beginTime,
                createTimeEnd: endTime,
                pageNum: pageNum,
                pageSize: pageSize,
            });
        },
        // 显示发票恢复记录详细对话框
        handleShowRecoveryRecordsDetails(row) {
            // 设置用户选中的发票数据；
            this.recoveryRecordsDetails.selectRow = row;
            this.recoveryRecordsDetails.dialogVisible = true;
        },
        // 修复记录详细页面打开结束时的回调
        handleRecoveryRecordsDetailsDialogOpened() {
            this.callInvoiceSyncDetails();
        },
        // 修复记录详细页面关闭结束时的回调
        handleRecoveryRecordsDetailsDialogClosed() {
            // 删除查询记录
            this.recoveryRecordsDetails.search.resultList = [];
        },
        // 修复记录详情数据查询
        handleRecoveryRecordsDetailsSearch() {
            this.callInvoiceSyncDetails(
                1,
                this.recoveryRecordsDetails.search.resultPagination.pageSize
            );
        },
        handleRecordsDetailsSearchResultSizeChange(val) {
            this.callInvoiceSyncDetails(1, val);
        },
        handleRecordsDetailsSearchResultCurrentChange(val) {
            this.callInvoiceSyncDetails(
                val,
                this.recoveryRecordsDetails.search.resultPagination.pageSize
            );
        },
        // 调用同步的记录详情数据接口
        callInvoiceSyncDetails(pageNum, pageSize) {
            let row = this.recoveryRecordsDetails.selectRow;
            if (row) {
                this.recoveryRecordsDetails.loading = true;
                let _this = this;
                invoiceSyncDetails({
                    invoiceCategory: this.recoveryRecordsDetails.search
                        .invoiceCategory,
                    invoiceCode: this.recoveryRecordsDetails.search.invoiceCode,
                    invoiceNumber: this.recoveryRecordsDetails.search
                        .invoiceNumber,
                    deviceType: row.deviceType,
                    taxDiscId: row.taxDiscId,
                    recordId: row.recordId,
                    pageNum: pageNum,
                    pageSize: pageSize,
                })
                    .then((val) => {
                        _this.recoveryRecordsDetails.search.resultPagination.total =
                            val.data.total;
                        _this.recoveryRecordsDetails.search.resultPagination.pageSize =
                            val.data.size;
                        _this.recoveryRecordsDetails.search.resultPagination.currentPage =
                            val.data.current;
                        _this.recoveryRecordsDetails.search.resultList =
                            val.data.records;
                        _this.recoveryRecordsDetails.loading = false;
                    })
                    .catch((err) => {
                        _this.$message.error(err);
                        _this.recoveryRecordsDetails.loading = false;
                    });
            } else {
                console.log("没有选中数据！");
            }
        },
        // 修复进度对话框打开结束时的回调
        handleRecoveryProgressDialogOpened() {
            // 重置进度
            this.recoveryProgress.percentage = 0;
            let _this = this;
            // 三秒后执行发票修复进度查询
            setTimeout(function () {
                _this.callInvoiceSyncRecordProgress();
            }, 3000);
        },
        // 修复进度对话框关闭结束时的回调
        handleRecoveryProgressDialogClosed() {
            this.recoveryProgress.recordId = "";
            this.recoveryProgress.percentage = 0;
            // 刷新发票修复历史
            this.callInvoiceSyncRecords(
                1,
                this.search.resultPagination.pageSize
            );
        },
        // 调用发票修复同步记录进度接口
        callInvoiceSyncRecordProgress() {
            let _this = this;
            invoiceSyncRecordProgress(this.recoveryProgress.recordId)
                .then((val) => {
                    if (val.data) {
                        // status => 1：进行中  2：结束
                        if (val.data.status == 1) {
                            let num = Number.parseInt(val.data.handleCnt);
                            let total = Number.parseInt(val.data.totalCnt);
                            if (isNaN(num) || isNaN(total)) {
                                _this.recoveryProgress.percentage = 0;
                            } else {
                                _this.recoveryProgress.percentage =
                                    total <= 0
                                        ? 0
                                        : Math.round((num / total) * 100);
                            }
                            // 三秒后执行发票修复进度查询
                            setTimeout(function () {
                                _this.callInvoiceSyncRecordProgress();
                            }, 3000);
                        } else if (val.data.status == 2) {
                            // 发票总数为0，提示无发票可修复
                            if (val.data.totalCnt <= 0) {
                                _this.$message.success(
                                    "当前时间段无可修复发票！"
                                );
                            } else {
                                _this.$message.success(val.msg);
                            }
                            _this.recoveryProgress.dialogVisible = false;
                        } else {
                            _this.$message.error(
                                "发票修复状态未知，终止进度获取！"
                            );
                            _this.recoveryProgress.dialogVisible = false;
                        }
                    } else {
                        _this.$message.error("无进度信息，终止进度获取！");
                        _this.recoveryProgress.dialogVisible = false;
                    }
                })
                .catch((err) => {
                    _this.$message.error(err);
                    _this.recoveryProgress.dialogVisible = 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;
        },
    },
};
</script>

<style scoped>
</style>
