<template>
    <div
        id="invoice_can_hongchong"
        v-loading="loading"
        element-loading-text="拼命加载中......请稍等"
    >
        <el-container>
            <el-form label-position="top" ref="form" style="width: 100%">
                <el-row :gutter="10">
                    <el-col :span="6">
                        <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="6">
                        <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" :offset="6">
                        <el-form-item>
                            <span slot="label" style="color: #909399">
                                <span>&nbsp;&nbsp;</span>
                            </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-row :gutter="10">
                    <el-col :span="6">
                        <el-form-item>
                            <el-select
                                v-model="search.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>
                            <el-select
                                v-model="search.hongchongFlag"
                                placeholder="请选择红冲状态"
                                style="width: 100%"
                            >
                                <el-option
                                    v-for="item in hongchongFlagOptions"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10">
                    <el-col :span="6">
                        <el-form-item>
                            <el-input
                                v-model="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="search.invoiceNumber"
                                clearable
                                placeholder="请输入..."
                            >
                                <template slot="prepend">发票号码</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item>
                            <el-input
                                v-model="search.entName"
                                clearable
                                placeholder="请输入..."
                            >
                                <template slot="prepend">企业名称</template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </el-container>
        <br />
        <el-container>
            <el-table
                :data="search.resultList"
                border
                stripe
                :height="tableHeight"
                style="width: 100%"
            >
                <el-table-column
                    type="index"
                    :index="pageIndex"
                    align="center"
                    label="序号"
                    width="50"
                ></el-table-column>
                <el-table-column
                    prop="invoiceCategory"
                    label="发票种类"
                    width="160"
                    align="center"
                    :formatter="fmtInvoiceCategory"
                ></el-table-column>
                <el-table-column
                    prop="invoiceCode"
                    label="发票代码"
                    width="120"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="invoiceNumber"
                    label="发票号码"
                    width="120"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="invoiceDate"
                    label="开票日期"
                    width="120"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="customerName"
                    label="名称"
                    width="240"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="customerEntTaxId"
                    label="纳税人识别号"
                    width="180"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="totalAmount"
                    label="合计金额"
                    width="100"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="totalTaxes"
                    label="合计税额"
                    width="100"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="totalAmountTaxes"
                    label="价税合计"
                    width="100"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="invoicePerson"
                    label="开票人"
                    width="100"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    prop="interactTypeDetail"
                    label="电子邮件"
                    width="180"
                    show-overflow-tooltip
                ></el-table-column>
                <el-table-column
                    label="操作"
                    width="120"
                    align="center"
                    fixed="right"
                >
                    <template slot-scope="scope">
                        <el-button
                            @click="handleShowInvoiceDetails(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-dialog
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            center
            width="300mm"
            top="10vh"
            :visible.sync="invoiceDetails.dialogVisible"
            @opened="handleInvoiceDetailsDialogOpened"
            @closed="handleInvoiceDetailsDialogClosed"
        >
            <div
                v-loading="invoiceDetails.loading"
                element-loading-text="拼命加载中......请稍等"
            >
                <el-row>
                    <el-col :span="6">
                        <el-radio-group v-model="invoiceDetails.tabPosition">
                            <el-radio-button
                                v-for="item in invoiceDetails.tabPositonOptions"
                                :key="item.value"
                                :label="item.value"
                                :disabled="item.disabled"
                                >{{ item.label }}</el-radio-button
                            >
                        </el-radio-group>
                    </el-col>
                    <el-col :span="18">
                        <div style="text-align: right">
                            <el-button
                                @click="handleSaveHongchong"
                                type="primary"
                                >立即红冲</el-button
                            >
                        </div>
                    </el-col>
                </el-row>
                <el-divider></el-divider>
                <div>
                    <el-card
                        v-show="invoiceDetails.tabPosition == 1"
                        style="text-align: center"
                    >
                        <invoice-dzfp ref="invoice-dzfp-sample"></invoice-dzfp>
                    </el-card>
                    <div v-show="invoiceDetails.tabPosition == 2">
                        <el-table
                            :data="invoiceDetails.goodsList"
                            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="goodsCode"
                                label="商品编码"
                                width="180"
                                show-overflow-tooltip
                            ></el-table-column>
                            <el-table-column
                                prop="goodsName"
                                label="项目名称"
                                width="180"
                                show-overflow-tooltip
                            ></el-table-column>
                            <el-table-column
                                prop="goodsSpecification"
                                label="规格型号"
                            ></el-table-column>
                            <el-table-column
                                prop="goodsUnit"
                                label="单位"
                            ></el-table-column>
                            <el-table-column
                                prop="goodsQuantity"
                                label="数量"
                            ></el-table-column>
                            <el-table-column
                                prop="goodsPrice"
                                label="单价"
                            ></el-table-column>
                            <el-table-column
                                prop="goodsTotalPrice"
                                label="金额"
                            ></el-table-column>
                            <el-table-column
                                prop="goodsTaxRate"
                                label="税率"
                            ></el-table-column>
                            <el-table-column
                                prop="goodsTotalTax"
                                label="税额"
                            ></el-table-column>
                        </el-table>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { invoiceQuery } from "@/api/invoice_management";
import { InvoiceResultData } from "@/api/invoice_ext";
import { saveHongchong } from "@/api/hongchong_info";
import InvoiceDZFP from "@/components/InvoiceSample/InvoiceDZFP";
import DateHelper from "@/utils/date";

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

const hongchongFlagOptions = [
    {
        value: 2,
        label: "发票未红冲",
    },
    {
        value: 3,
        label: "发票红冲中",
    },
    {
        value: 4,
        label: "发票红冲失败",
    },
];

// 发票明细页面标签列表
const invoiceDetailsTabPositonOptions = [
    {
        value: 1,
        label: "发票",
    },
    {
        value: 2,
        label: "商品清单",
    },
];

// 发票明细页面无发票清单标签列表
const invoiceDetailsTabPositonDisabledGoodsListOptions = [
    {
        value: 1,
        label: "发票",
    },
    {
        value: 2,
        label: "商品清单",
        disabled: true,
    },
];

/**
 * 获取发票类别文本；
 * @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_can_hongchong",
    components: {
        "invoice-dzfp": InvoiceDZFP,
    },
    data() {
        return {
            loading: false,
            invoiceCategoryOptions: invoiceCategoryOptions,
            hongchongFlagOptions: hongchongFlagOptions,
            search: {
                entName: "",
                hongchongFlag: 2, // 可红冲开票
                beginDate: DateHelper.LocalCurrentMonthStart(),
                endDate: DateHelper.LocalCurrentMonthEnd(),
                invoiceCode: "",
                invoiceNumber: "",
                invoiceCategory: "",
                resultList: [],
                resultPagination: {
                    currentPage: 1,
                    pageSizes: [10, 30, 50, 100],
                    pageSize: 10,
                    total: 0,
                },
            },
            invoiceDetails: {
                loading: false,
                dialogVisible: false,
                tabPositonOptions: invoiceDetailsTabPositonOptions,
                tabPosition: 1,
                selectRow: {}, // 用户选中的发票数据；
                goodsList: [], // 发票清单；
            },
            tableHeight: "",
        };
    },
    created() {
        this.tableHeight = window.innerHeight - 250;
        this.callInvoiceQuery(
            this.search.resultPagination.currentPage,
            this.search.resultPagination.pageSize
        );
    },
    mounted() {
        this.tableHeight = window.innerHeight - 250;
        window.onresize = () => {
            return (() => {
                this.tableHeight = window.innerHeight - 250;
            })();
        };
    },
    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;
        },
        // 显示发票详细信息弹窗；
        handleShowInvoiceDetails(row) {
            console.log("显示发票详细信息：");
            console.log(row);

            // 开票中
            if (row.status == 2) {
                this.$message.error("发票开票中，无法查看票样！");
                return false;
            }

            // 开票失败
            if (row.status == 4) {
                this.$message.error("发票开票失败，无法查看票样！");
                return false;
            }

            // 如果此时发票状态不是开票成功
            if (row.status != 3) {
                this.$message.error("发票状态未知，请您稍后重试！");
                return false;
            } else {
                // 设置用户选中的发票数据；
                this.invoiceDetails.selectRow = row;
                this.invoiceDetails.dialogVisible = true;
            }
        },
        // 发票详细页面打开结束时的回调；
        handleInvoiceDetailsDialogOpened() {
            // 重置
            this.invoiceDetails.tabPosition = 1;
            this.invoiceDetails.goodsList = []; // 发票清单；

            let row = this.invoiceDetails.selectRow;
            if (row) {
                this.invoiceDetails.loading = true;
                let _this = this;
                InvoiceResultData(row.orderId, row.invoiceType)
                    .then((val) => {
                        // 设置发票票样显示信息；
                        let invoiceSample = _this.$refs["invoice-dzfp-sample"];
                        let title = GetInvoiceCategoryLabel(
                            row.invoiceCategory
                        );
                        invoiceSample.setTitle(title);
                        invoiceSample.setInvoiceBaseInfo({
                            invoiceCode: val.data.invoiceData.invoiceCode,
                            invoiceNo: val.data.invoiceData.invoiceNo,
                            invoiceDate: val.data.invoiceData.invoiceDate,
                            invoiceCheckCode:
                                val.data.invoiceData.invoiceCheckCode,
                            machineNo: val.data.invoiceData.machineNo,
                            invoiceTotalPrice:
                                val.data.invoiceData.invoiceTotalPrice,
                            invoiceTotalTax:
                                val.data.invoiceData.invoiceTotalTax,
                            invoiceTotalPriceTax:
                                val.data.invoiceData.invoiceTotalPriceTax,
                            payee: val.data.invoiceData.payee,
                            checker: val.data.invoiceData.checker,
                            drawer: val.data.invoiceData.drawer,
                            taxControlCode: val.data.invoiceData.taxControlCode,
                            remarks: val.data.invoiceData.remarks,
                        });
                        invoiceSample.setInvoiceGF({
                            name: val.data.invoiceData.buyerName,
                            entTaxId: val.data.invoiceData.buyerEntTaxId,
                            bankAccount: val.data.invoiceData.buyerBankAccount,
                            addressPhone:
                                val.data.invoiceData.buyerAddressPhone,
                        });
                        invoiceSample.setInvoiceXF({
                            name: val.data.invoiceData.sellerEntName,
                            entTaxId: val.data.invoiceData.sellerEntTaxId,
                            bankAccount: val.data.invoiceData.sellerBankAccount,
                            addressPhone:
                                val.data.invoiceData.sellerAddressPhone,
                        });
                        if (val.data.invoiceData.goodsListMark == 1) {
                            // 有清单；
                            invoiceSample.setInvoiceCommodity([]);
                            _this.invoiceDetails.goodsList =
                                val.data.invoiceData.goodsDetailVOs;
                            _this.invoiceDetails.tabPositonOptions = invoiceDetailsTabPositonOptions;
                        } else {
                            invoiceSample.setInvoiceCommodity(
                                val.data.invoiceData.goodsDetailVOs
                            );
                            _this.invoiceDetails.tabPositonOptions = invoiceDetailsTabPositonDisabledGoodsListOptions;
                        }
                        _this.invoiceDetails.loading = false;
                    })
                    .catch((err) => {
                        _this.$message.error(err);
                        _this.invoiceDetails.loading = false;

                        _this.invoiceDetails.selectRow = {};
                        _this.invoiceDetails.dialogVisible = false;
                    });
            } else {
                console.log("没有选中数据！");
            }
        },
        // 发票详细页面关闭结束时的回调
        handleInvoiceDetailsDialogClosed() {
            let row = this.invoiceDetails.selectRow;
            if (row) {
                this.callInvoiceQuery(
                    this.search.resultPagination.currentPage,
                    this.search.resultPagination.pageSize
                );
            } else {
                console.log("没有选中数据！");
            }
        },
        // 立即红冲
        handleSaveHongchong() {
            let row = this.invoiceDetails.selectRow;
            let _this = this;
            if (row) {
                let tempMsg = `请输入红冲备注信息！对应发票代码：${row.invoiceCode} 号码：${row.invoiceNumber}`;
                this.$prompt(tempMsg, "确定红冲？", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                })
                    .then(({ value }) => {
                        _this.invoiceDetails.loading = true;
                        saveHongchong({
                            oriInvoiceReqFlowNo: row.invoiceReqFlowNo,
                            remark: value,
                        })
                            .then((val) => {
                                _this.invoiceDetails.loading = false;
                                _this.$message.success(val.msg);
                            })
                            .catch((err) => {
                                _this.invoiceDetails.loading = false;
                                _this.$message.error(err);
                            });
                    })
                    .catch(() => {
                        // 取消
                    });
                // 增值税普通纸质发票
                // if (row.invoiceCategory == 3) {
                //     let bzMsg = `对应正数发票代码：${row.invoiceCode} 号码：${row.invoiceNumber}`;
                //     this.$confirm(bzMsg, "确定红冲？", {
                //         confirmButtonText: "确定",
                //         cancelButtonText: "取消",
                //         type: "warning",
                //     })
                //         .then(() => {
                //             _this.invoiceDetails.loading = true;
                //             saveHongchong({
                //                 oriInvoiceReqFlowNo: row.invoiceReqFlowNo,
                //                 remark: bzMsg,
                //             })
                //                 .then((val) => {
                //                     _this.invoiceDetails.loading = false;
                //                     _this.$message.success(val.msg);
                //                 })
                //                 .catch((err) => {
                //                     _this.invoiceDetails.loading = false;
                //                     _this.$message.error(err);
                //                 });
                //         })
                //         .catch(() => {
                //             // 取消
                //         });
                // } else {
                //     this.$prompt("请输入红冲备注信息", "确定红冲？", {
                //         confirmButtonText: "确定",
                //         cancelButtonText: "取消",
                //     })
                //         .then(({ value }) => {
                //             _this.invoiceDetails.loading = true;
                //             saveHongchong({
                //                 oriInvoiceReqFlowNo: row.invoiceReqFlowNo,
                //                 remark: value,
                //             })
                //                 .then((val) => {
                //                     _this.invoiceDetails.loading = false;
                //                     _this.$message.success(val.msg);
                //                 })
                //                 .catch((err) => {
                //                     _this.invoiceDetails.loading = false;
                //                     _this.$message.error(err);
                //                 });
                //         })
                //         .catch(() => {
                //             // 取消
                //         });
                // }
            } else {
                console.log("没有选中数据！");
            }
        },
        handleSearch() {
            this.callInvoiceQuery(1, this.search.resultPagination.pageSize);
        },
        handleResetSearch() {
            this.search.entName = "";
            this.search.hongchongFlag = 2; // 可红冲开票
            this.search.beginDate = "";
            this.search.endDate = "";
            this.search.invoiceCode = "";
            this.search.invoiceNumber = "";
            this.search.invoiceCategory = "";
        },
        handleSearchResultSizeChange(val) {
            this.callInvoiceQuery(1, val);
        },
        handleSearchResultCurrentChange(val) {
            this.callInvoiceQuery(val, this.search.resultPagination.pageSize);
        },
        /**
         * 查询发票
         * @param {Number} pageNum : 当前页码
         * @param {Number} pageSize : 每页数量
         */
        callInvoiceQuery(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) {
                    this.$message.error(
                        "起始日期与结束日期不合法，请确定后重试！"
                    );
                    return false;
                }
            }
            this.loading = true;
            let _this = this;
            invoiceQuery({
                invoiceCode: this.search.invoiceCode,
                invoiceNumber: this.search.invoiceNumber,
                invoiceCategory: this.search.invoiceCategory,
                customerName: this.search.entName,
                hongchongFlag: this.search.hongchongFlag,
                invoiceDateBegin: beginTime,
                invoiceDateEnd: endTime,
                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;
        },
    },
};
</script>
