/**
 *
 * @author BOGON
 * @version 1.0
 */
var page = {
        bidFormPrefix: "bid.",
        purchaseRequestType: "",
        bidFileType: 0,
        submitFlag: 0,
        dataGrid: {},
        tenderFileGrid: {},
        columns: [],
        initTenderFileGrid: function (data) {
            var columns = [{
                field: 'fileName', // title: '文件名',
                title: tenderTitles.fileName, width: 200, align: 'left'
            }, {
                field: 'type', title: '类型', width: 80, align: 'left', formatter: function (value, row, index) {
                    return ATTACHMENT_TYPE[value].color
                }
            }, {
                field: 'fileId', // title: '文件选择',
                title: tenderTitles.fileSelect, width: 80, align: 'center', formatter: function (value, row, index) {
                    return '<a href="' + g.ctx + 'pc/sys/file/rest/download/' + value + '">下载</a>';
                }

            }];
            page.tenderFileGrid = $("#tenderFileTb").datagrid({
                iconCls: 'icon-list',
                width: '100%',
                height: '100%',
                data: data,
                singleSelect: true,
                pagination: false, // loadMsg: "数据加载中......",
                loadMsg: tenderTxt.dataLoad,
                rownumbers: true,
                nowrap: true,
                remoteSort: true,
                striped: true,
                columns: [columns]
            })
        },
        bidFileGrid: {},
        suppplierEditField: undefined,
        allFields: {},
        thresholdFlag: 0,
        totalDoorPrice: 0,
        loadData: function (id) {
            var loadIndex = topWin.layer.load(0, {shade: [0.6, '#FFF']})
            tenderComm.loadDataAjax(id, function (d) {
                const fd = {}
                page.purchaseRequestType = d.tender.purchaseRequestType;
                $.each(d.tender, function (idx, itm) {
                    fd[tenderComm.tenderFormPrefix + idx] = itm
                })
                page.thresholdFlag = d.tender.thresholdFlag;
                page.totalDoorPrice = d.tender.totalDoorPrice;
                $.each(d.securityDeposit, function (idx, itm) {
                    fd[tenderComm.securityDepositFormPrefix + idx] = itm
                })
                $.each(d.round, function (idx, itm) {
                    fd[tenderComm.roundFormPrefix + idx] = itm
                })
                if (d.tender['typeId'] === "1") {
                    $("input[textboxname='bid.finalAmount']").textbox("readonly", true)
                    $("input[comboname='bid.currency']").combobox("readonly", true)
                }
                const countdownElement = document.getElementById('time');
                if (countdownElement != null) {
                    const targetTime = moment(d.round.endDay, "YYYY-MM-DD HH:mm:ss");
                    if (targetTime.isValid()) {
                        page.startCountdown(targetTime, countdownElement);
                    } else {
                        countdownElement.textContent = "无效的日期格式";
                    }
                }
                $("#tender").form("load", fd)

                page.initTenderFileGrid(d.tenderAttachmentList);
                $.ajax({
                    url: g.ctx + 'pc/tender/bid/rest/getDetail', data: {id: bidId}, type: "GET", success: function (dd) {
                        const bid = {}
                        $.each(dd.bid, function (idx, itm) {
                            bid[page.bidFormPrefix + idx] = itm
                        })
                        bid[page.bidFormPrefix + 'typeId'] = d.tender['typeId']
                        $("#bid").form("load", bid)
                        if (dd.bid.ranking) {
                            $("#rank").html(dd.bid.ranking)
                        }
                        page.loadTenderField(d.tender.templateId, dd.bidDetail, page.thresholdFlag)
                        page.initBidFileGrid(dd.bidFiles);
                        setTimeout(function () {
                            topWin.layer.close(loadIndex)
                            if (page.isReadOnly()) {
                                //查看和审核所有控件只读
                                // 设置所有 datetimebox 为只读模式
                                $('.easyui-datetimebox').datetimebox('readonly', true);
                                // 设置所有 NumberBox 为只读模式
                                $('.easyui-numberbox').numberbox('readonly', true);
                                // 设置所有 TextBox 为只读模式
                                $('.easyui-textbox').textbox('readonly', true);
                                // 设置所有 ComboBox 为只读模式
                                $('.easyui-combobox').combobox('readonly', true);
                            }
                        }, 500)
                    }
                });
            })
        },
        bidFileUpload: function () {
            var filebox = $("#fileInput").filebox("files");
            if (filebox.length == 1) {
                var formData = new FormData();
                formData.append("file", filebox[0]);
                fileUploadAjaxWithCall(formData, function (obj) {
                    let data = {
                        fileId: obj.id, fileName: obj.fileName, type: page.bidFileType
                    }
                    page.bidFileGrid.datagrid("appendRow", data);
                    $("#fileInput").filebox("clear")
                })
            }
        },
        initBidFileGrid: function (data) {
            var toolbar = [];
            if (!page.isReadOnly()) {
                toolbar.push({
                    text: '上传技术附件<span style="color: red">*</span>', iconCls: 'icon-add', handler: function () {
                        page.bidFileType = 3;
                        $("#bidFileUpload .filebox-label").click();
                    }
                });
                toolbar.push("-");
                toolbar.push({
                    text: '上传报价Excel附件', iconCls: 'icon-add', handler: function () {
                        page.bidFileType = 5;
                        $("#bidFileUpload .filebox-label").click();
                    }
                });
                toolbar.push("-");
                toolbar.push({
                    text: '报价PDF盖章附件<span style="color: red">*</span>', iconCls: 'icon-add', handler: function () {
                        page.bidFileType = 6;
                        $("#bidFileUpload .filebox-label").click();
                    }
                });
                toolbar.push("-");
                toolbar.push({
                    text: buttonI18n.delete, iconCls: 'icon-remove', handler: function () {
                        var rows = page.bidFileGrid.datagrid("getChecked");
                        if (rows.length == 0) {
                            topWin.layer.msg(commonTxt.chooseDeleteFile)
                            return;
                        }
                        var rowIndex = [];
                        $.each(rows, function (index, item) {
                            rowIndex.push(page.bidFileGrid.datagrid("getRowIndex", item));
                        });
                        let reversedArray = rowIndex.reverse();
                        $.each(reversedArray, function (idx, itm) {
                            page.bidFileGrid.datagrid("deleteRow", itm);
                        })
                    }
                });
            }
            if (type === 2) {
                data = []
                toolbar.push({
                    text: '上传报价Excel附件', iconCls: 'icon-add', handler: function () {
                        page.bidFileType = 5;
                        $("#bidFileUpload .filebox-label").click();
                    }
                });
                toolbar.push("-");
                toolbar.push({
                    text: '报价PDF盖章附件<span style="color: red">*</span>', iconCls: 'icon-add', handler: function () {
                        page.bidFileType = 6;
                        $("#bidFileUpload .filebox-label").click();
                    }
                });
                toolbar.push("-");
                toolbar.push({
                    text: buttonI18n.delete, iconCls: 'icon-remove', handler: function () {
                        var rows = page.bidFileGrid.datagrid("getChecked");
                        if (rows.length == 0) {
                            topWin.layer.msg(commonTxt.chooseDeleteFile)
                            return;
                        }
                        var rowIndex = [];
                        $.each(rows, function (index, item) {
                            rowIndex.push(page.bidFileGrid.datagrid("getRowIndex", item));
                        });
                        let reversedArray = rowIndex.reverse();
                        $.each(reversedArray, function (idx, itm) {
                            page.bidFileGrid.datagrid("deleteRow", itm);
                        })
                    }
                });
            }
            var columns = [{
                field: 'ck', checkbox: true
            }, {
                field: 'fileName', // title: '文件名',
                title: tenderTitles.fileName, width: 200, align: 'left'
            }, {
                field: 'type', title: '类型', width: 115, align: 'left', formatter: function (value, row, index) {
                    return ATTACHMENT_TYPE[value].color
                }
            }, {
                field: 'fileId', // title: '文件地址',
                title: "下载", width: 80, align: 'left', formatter: function (value) {
                    var url = g.ctx + "pc/sys/file/rest/download/" + value;
                    return "<a href='" + url + "'>" + tenderBtns.download + "</a>";
                }

            }];
            page.bidFileGrid = $("#bidFileTb").datagrid({
                iconCls: 'icon-list',
                width: '100%',
                height: '100%',
                singleSelect: false,
                pagination: false, // loadMsg: "数据加载中......",
                loadMsg: tenderTxt.dataLoad,
                rownumbers: true,
                nowrap: true,
                remoteSort: true,
                striped: true,
                data: data,
                columns: [columns],
                toolbar: toolbar
            });
        },
        bargaining: function (call) {
            page.dataGrid.edatagrid("saveRow");
            var url = g.ctx + 'pc/tender/bid/rest/submitBargaining';
            var data = page.dataGrid.datagrid("getData");
            let rows = data.rows;
            tenderComm.detailRequired['bargainingSupplier'] = "回复价";
            var requiredMsg = [];
            for (var i = 0; i < rows.length; i++) {
                var changeRow = rows[i];
                for (var prop in tenderComm.detailRequired) {
                    if (prop === 'taxPrice') {
                        continue
                    }
                    if (changeRow[prop] === undefined || changeRow[prop] === '') {
                        requiredMsg.push(tenderTxt.the + (i + 1) + " " + tenderTxt.line + "<span style='color: red;'>" + tenderComm.detailRequired[prop] + "</span>" + tenderTxt.cannotEmpty)
                    }
                }
                //判断国系如果是美国需要必填ECCM
                if (tenderComm.detailRequired["countryName"] !== undefined) {
                    if (changeRow['countryName'] === 'america' && !changeRow['eccn']) {
                        requiredMsg.push(tenderTxt.the + (i + 1) + " " + tenderTxt.line + "<span style='color: red;'>ECCN码</span>" + tenderTxt.cannotEmpty)
                    }
                }
            }
            if (requiredMsg.length > 0) {
                topWin.layer.alert(requiredMsg.join("</br>"), {
                    icon: 2
                });
                return
            }
            var items = [];
            $.each(rows, function (index, item) {
                items.push(item);
            });

            var bidFiles = page.bidFileGrid.edatagrid("getRows");
            if (bidFiles.length <= 0) {
                topWin.layer.alert("<span style='color: red;'>投标文件</span>不能为空", {
                    icon: 2
                });
                return;
            }
            //所有类型的附件都需要上传一遍
            if (bidFiles.filter(a => a.type == 6).length === 0) {
                topWin.layer.alert("<span style='color: red;'>报价PDF盖章附件</span>不能为空", {
                    icon: 2
                });
                return;
            }
            let postData = {
                items: items,
                bidFiles: bidFiles
            }
            if (page.submitFlag === 1) {
                return;
            }
            var loadIndex = topWin.layer.msg('数据正在保存......', {icon: 16, time: 0, shade: 0.1});
            page.submitFlag = 1;
            $.ajax({
                url: url,
                method: "POST",
                data: JSON.stringify(postData),
                contentType: 'application/json',
                complete: function () {
                    page.submitFlag = 0
                    topWin.layer.close(loadIndex);
                },
                success: function (data) {
                    topWin.layer.alert(commonTxt.operateSuccess, {
                        icon: 1, closeBtn: 0, yes: function (idx) {
                            topWin.layer.close(idx);
                            call();

                        }
                    });
                },
                error: function (d) {
                    topWin.layer.alert(d.responseJSON.message, {icon: 2});
                }
            });
        },
        loadTenderField: function (templateId, bidDetail) {
            var url = g.ctx + 'pc/tender/template/rest/templateFieldList?id=' + templateId;
            $.ajax({
                url: url, type: 'GET', async: false, data: {templateId: templateId}, success: function (data) {
                    tenderComm.analysisFieldsForSupplier(data)
                    page.initDetailTable(bidDetail);
                }
            });
        },
        initDetailTable: function (bidDetail) {
            var toolbars = [{
                text: '清空报价', id: 'empty_price', iconCls: 'icon-remove', handler: function () {
                    if (type == 1) {
                        page.dataGrid.edatagrid("saveRow");
                        let rows = page.dataGrid.datagrid('getRows');
                        var selectedRow = rows[0];

                        var newRow = {};
                        for (var prop in selectedRow) {
                            if (page.isEdit(prop)) {
                                newRow[prop] = '';
                            }
                        }
                        $.each(rows, function (idx, itm) {
                            page.dataGrid.datagrid('updateRow', {
                                index: idx, row: newRow
                            });
                        })
                    }
                }
            }, "-", {
                text: '下载', id: 'export', iconCls: 'icon-download', handler: function () {
                    if (type == 1) {
                        page.exportRows(0, 0);
                    }
                }
            }, "-", {
                text: '导入', id: 'import', iconCls: 'icon-import', handler: function () {
                    if (type == 1) {
                        $("#detailUpload .filebox-label").click();
                    }
                }
            }];
            if (page.isReadOnly()) {
                //需要增加判断，如果是议价也需要修改之前的字段除了含税单价
                if (type === 2) {
                    $.each(tenderComm.detailField, function (i, item) {
                        if (item.field === 'taxPrice') {
                            delete item.editor
                        }
                    })
                } else {
                    //如果只读需要把设置成不可编辑
                    $.each(tenderComm.detailField, function (i, item) {
                        delete item.editor
                    })
                }

                toolbars = []
            }
            if (type === 0 || type === 3) {
                //需要额外增加议价的数据显示
                tenderComm.detailField.push({
                    field: 'bargaining', title: '期望价', width: 100, align: 'center'
                }, {
                    field: 'bargainingRemark', title: '议价备注', width: 100, align: 'center'
                }, {
                    field: 'bargainingSupplier', title: '回复价(含税单价)', width: 100, align: 'center'
                }, {
                    field: 'bargainingSupplierRemark', title: '回复议价备注', width: 100, align: 'center'
                })
            }
            if (type === 2) {
                toolbars = [{
                    text: '清空报价', id: 'empty_price', iconCls: 'icon-remove', handler: function () {
                        page.dataGrid.edatagrid("saveRow");
                        let rows = page.dataGrid.datagrid('getRows');
                        var newRow = {
                            bargainingSupplierRemark: '', bargainingSupplier: '',
                        };
                        $.each(rows, function (idx, itm) {
                            page.dataGrid.datagrid('updateRow', {
                                index: idx, row: newRow
                            });
                        })
                    }
                }, "-", {
                    text: '下载', id: 'export', iconCls: 'icon-download', handler: function () {
                        if (type == 2) {
                            page.exportRows(1, 0);
                        }
                    }
                }, "-", {
                    text: '导入', id: 'import', iconCls: 'icon-import', handler: function () {
                        if (type == 2) {
                            $("#bargainingUpload .filebox-label").click();
                        }
                    }
                }]
                //表示议价
                tenderComm.detailField.unshift({
                    field: 'bargaining', title: '期望价', width: 100, align: 'center'
                }, {
                    field: 'bargainingRemark', title: '议价备注', width: 100, align: 'center'
                }, {
                    field: 'bargainingSupplier', title: '回复价', width: 100, align: 'center', editor: {
                        type: 'numberbox', options: {
                            min: 0, precision: priceHandle.precision
                        }
                    }
                }, {
                    field: 'bargainingSupplierRemark', title: '回复议价备注', width: 120, align: 'center', editor: {
                        type: 'textbox', prompt: "请输入", options: {}
                    }
                })
            } else if (type === 3) {
                //表示历史查看
                //表示议价
                toolbars = [{
                    text: '导出', id: 'export', iconCls: 'icon-download', handler: function () {
                        if (type == 3) {
                            page.exportRows(0, 1);
                        }
                    }
                }]
                tenderComm.detailField.unshift({
                    field: 'bargaining', title: '期望价', width: 100, align: 'center'
                }, {
                    field: 'bargainingRemark', title: '议价备注', width: 100, align: 'center'
                }, {
                    field: 'bargainingSupplier', title: '回复价', width: 100, align: 'center'
                }, {
                    field: 'bargainingSupplierRemark', title: '回复议价备注', width: 100, align: 'center'
                })
                //表示议价
                tenderComm.detailField.unshift({
                    field: 'status',
                    title: '是否中标',
                    width: 100,
                    align: 'center',
                    formatter: function (value, row, index) {
                        if (value == 1) {
                            return '是';
                        } else {
                            return '否';
                        }
                    }
                })
            }
            // 请购类型是“费用类”时，投标明细，在“含税单价”后增加列“发票类型”
            if (page.purchaseRequestType === "01") {
                const invoiceTypeColumn = {
                    field: 'invoiceType',
                    title: '<span style="color: red">*</span>发票类型',
                    width: 120,
                    editor: {
                        type: 'combobox',
                        options: {
                            valueField: 'code',
                            textField: 'codeWithDesc',
                            panelHeight: 'auto',
                            required: 1,
                            editable: false,
                            data: getDictList("invoice_type"),
                            prompt: '-- 请选择 --',
                            disabled: type === 0
                        }
                    },
                    formatter: function (value) {
                        return getDicName("invoice_type", value);
                    }
                };
                page.insertColumnBefore(tenderComm.detailField, invoiceTypeColumn, "投标备注");
            }
            var columns = [tenderComm.detailField];
            page.dataGrid = $("#tb").edatagrid({
                showFooter: true,
                iconCls: 'icon-list',
                width: '100%',
                height: '100%',
                singleSelect: true,
                pagination: false,
                loadMsg: "数据加载中......",
                rownumbers: true,
                remoteSort: true,
                striped: true,
                columns: columns,
                autoSave: true,
                toolbar: toolbars,
                onSave: function (index, row) {
                    if (!page.isReadOnly()) {
                        //需要计算未税价格
                        page.calculateUnTaxPrice(index, row)
                        page.calculateNoTaxTotalPrice()
                        page.calculateTaxTotalPrice()
                    }
                },
                onLoadSuccess: function () {
                    setTimeout(function () {
                        if (page.thresholdFlag === 0) {
                            $("#tb").datagrid("hideColumn", "doorPrice");
                        } else {
                            $("#tb").datagrid("showColumn", "doorPrice");
                        }
                    }, 2)
                }
            });
            if (type === 2) {
                let filteredBidDetail = bidDetail.filter(item => item.bargainingStatus === 1);
                page.dataGrid.datagrid("loadData", filteredBidDetail);
            } else {
                page.dataGrid.datagrid("loadData", bidDetail);
            }

        },
        exportRows: function (bargaining, historyFlag) {
            window.open(g.ctx + 'pc/tender/template/rest/export1?thresholdFlag=' + page.thresholdFlag + "&historyFlag=" + historyFlag + "&bargaining=" + bargaining + "&bidId=" + bidId + "&_" + new Date().valueOf())
        },
        isEdit: function (obj) {
            if (page.suppplierEditField === undefined) {
                page.suppplierEditField = tenderComm.postField.filter(it => it.supplierEdit === 1).map(item => toCamelCase(item.fieldCode));
            }
            return page.suppplierEditField.indexOf(obj) !== -1
        },
        detailImport: function (v1, v2) {
            var filebox = $("#detailFileInput").filebox("files");
            if (filebox.length == 1) {
                var formData = new FormData();
                formData.append("file", filebox[0]);
                var index = topWin.layer.load(1, {
                    shade: [0.1, '#eee'] //0.1透明度的白色背景
                });
                $.ajax({
                    url: g.ctx + 'pc/tender/template/rest/import1',
                    data: formData,
                    type: 'post',
                    contentType: false,
                    processData: false,
                    complete: function () {
                        topWin.layer.close(index);
                        $("#detailFileInput").filebox("clear");
                    },
                    success: function (d) {
                        let rows = page.dataGrid.datagrid("getRows")
                        let indexCache = {}
                        $.each(rows, function (index, it) {
                            indexCache[it.id] = index
                        })
                        $.each(d, function (index, item) {
                            var id = item.id;
                            var rowIndex = indexCache[id];
                            var tmp = {}
                            for (var prop in item) {
                                if (page.isEdit(prop)) {
                                    tmp[prop] = item[prop];
                                }
                            }
                            page.dataGrid.datagrid("updateRow", {index: rowIndex, row: tmp});
                            console.log(tmp)
                            page.calculateUnTaxPrice(rowIndex, tmp)
                        })
                        page.calculateNoTaxTotalPrice()
                        page.calculateTaxTotalPrice()

                    },
                    error: function () {
                        topWin.layer.alert(JSON.parse(data.responseText).message);
                    }
                })
            }
        },
        bargainingImport: function () {
            var filebox = $("#bargainingFileInput").filebox("files");
            if (filebox.length == 1) {
                var formData = new FormData();
                formData.append("file", filebox[0]);
                var index = topWin.layer.load(1, {
                    shade: [0.1, '#eee'] //0.1透明度的白色背景
                });
                $.ajax({
                    url: g.ctx + 'pc/tender/template/rest/import1',
                    data: formData,
                    type: 'post',
                    contentType: false,
                    processData: false,
                    complete: function () {
                        topWin.layer.close(index);
                        $("#bargainingFileInput").filebox("clear");
                    },
                    success: function (d) {
                        let rows = page.dataGrid.datagrid("getRows")
                        let indexCache = {}
                        $.each(rows, function (index, it) {
                            indexCache[it.id] = index
                        })
                        $.each(d, function (index, item) {
                            var id = item.id;
                            var rowIndex = indexCache[id];
                            var tmp = {
                                bargainingSupplierRemark: item['bargainingSupplierRemark'],
                                bargainingSupplier: item['bargainingSupplier']
                            }
                            for (var prop in item) {
                                if (page.isEdit(prop)) {
                                    tmp[prop] = item[prop];
                                }
                            }
                            page.dataGrid.datagrid("updateRow", {index: rowIndex, row: tmp});
                        })

                    },
                    error: function () {
                        topWin.layer.alert(JSON.parse(data.responseText).message);
                    }
                })
            }
        },
        saveDetail: function () {
            if (page.submitFlag == 1) {
                return;
            }
            const opts = page.dataGrid.edatagrid('options');
            const editIndex = opts.editIndex;
            if (!page.dataGrid.edatagrid('validateRow', editIndex)) {
                const ed = page.dataGrid.edatagrid('getEditor', {
                    index: editIndex,
                    field: 'invoiceType'
                });

                if (ed && !$(ed.target).combobox('isValid')) {
                    layer.msg('报价资料第' + (editIndex + 1) + '行，发票类型不能为空');
                    return false;
                }
            }
            if (!$("#bid").form('validate')) {
                topWin.layer.msg("必填项不得为空!");
                return false;
            }
            page.dataGrid.edatagrid("saveRow");
            var changeRows = page.dataGrid.datagrid('getChanges');
            //可以是报总价也可以是报明细
            const formData = $("#bid").serializeJson();

            let totalAmount = formData[page.bidFormPrefix + 'totalAmount']
            var taxedQuotationMsg = [];
            var doorPriceMsg = [];
            var requiredMsg = [];
            for (var i = 0; i < changeRows.length; i++) {
                var changeRow = changeRows[i];
                var taxedQuotation = changeRow['taxPrice'];
                if (taxedQuotation === '' || taxedQuotation === undefined) {
                    taxedQuotationMsg.push(tenderTxt.the + (i + 1) + " " + tenderTxt.line + ",<span style='color: red;'> " + tenderTxt.quote + " </span>" + tenderTxt.isEmpty);
                } else {
                    for (var prop in tenderComm.detailRequired) {
                        if (changeRow[prop] === undefined || changeRow[prop] === '') {
                            requiredMsg.push(tenderTxt.the + (i + 1) + " " + tenderTxt.line + "<span style='color: red;'>" + tenderComm.detailRequired[prop] + "</span>" + tenderTxt.cannotEmpty)
                        }
                    }
                    //判断是否高于门槛价
                    if (page.thresholdFlag !== 0) {
                        const detailAmount = (parseFloat(changeRow['currentPrice']) || 0);
                        const doorPrice = (parseFloat(changeRow['doorPrice']) || 0);
                        if (detailAmount > doorPrice) {
                            doorPriceMsg.push(tenderTxt.the + (i + 1) + " " + tenderTxt.line + ",<span style='color: red;'>报价高于门槛价 </span>")
                        }
                    }
                }
                //判断国系如果是美国需要必填ECCM
                if (tenderComm.detailRequired["countryName"] !== undefined) {
                    if (changeRow['countryName'] === 'america' && !changeRow['eccn']) {
                        requiredMsg.push(tenderTxt.the + (i + 1) + " " + tenderTxt.line + "<span style='color: red;'>ECCN码</span>" + tenderTxt.cannotEmpty)
                    }
                }
            }
            if (requiredMsg.length > 0) {
                topWin.layer.alert(requiredMsg.join("</br>"), {
                    icon: 2
                });
                return
            }
            var bidFiles = page.bidFileGrid.edatagrid("getRows");
            if (bidFiles.length <= 0) {
                topWin.layer.alert("<span style='color: red;'>投标文件</span>不能为空", {
                    icon: 2
                });
                return;
            }
            //所有类型的附件都需要上传一遍
            if (bidFiles.filter(a => a.type == 6).length === 0) {
                topWin.layer.alert("<span style='color: red;'>报价PDF盖章附件</span>不能为空", {
                    icon: 2
                });
                return;
            }
            if (taxedQuotationMsg.length > 0 && totalAmount === '') {
                topWin.layer.confirm(taxedQuotationMsg.join("</br>") + "</br>请填写报价信息", {
                    icon: 2, title: commonTxt.warning
                }, function (index) {
                    topWin.layer.close(index);
                });
            } else {
                //需要把数据组装然后提交
                const postData = {}
                const bid = {}
                $.each(formData, function (idx, itm) {
                    bid[idx.replace(page.bidFormPrefix, "")] = itm
                })
                bid['id'] = bidId
                postData['type'] = type;
                postData['bid'] = bid;
                postData['bidFiles'] = bidFiles;
                postData['bidDetail'] = changeRows;
                const amount = parseFloat(totalAmount) || 0;
                if (page.thresholdFlag === 0) {
                    page.postAjax(postData, function () {
                        window.location.reload();
                    });
                } else if (amount > page.totalDoorPrice) {
                    topWin.layer.confirm("报价高于门槛价", {
                        icon: 0, title: commonTxt.warning
                    }, function (index) {
                        if (page.thresholdFlag === 2) {
                            page.postAjax(postData, function () {
                                topWin.layer.close(index)
                                window.location.reload();
                            });
                        } else {
                            topWin.layer.close(index)
                        }
                    })
                } else if (doorPriceMsg.length > 0) {
                    topWin.layer.confirm(doorPriceMsg.join("<br>"), {
                        icon: 0, title: commonTxt.warning
                    }, function (index) {
                        if (page.thresholdFlag === 2) {
                            page.postAjax(postData, function () {
                                topWin.layer.close(index)
                                window.location.reload();
                            });
                        } else {
                            topWin.layer.close(index)
                        }
                    })
                } else {
                    page.postAjax(postData, function () {
                        window.location.reload();
                    });
                }
            }
        },
        postAjax: function (postData, call) {
            var index = topWin.layer.load(0, {
                shade: [0.6, '#eee'] //0.1透明度的白色背景
            });
            page.submitFlag = 1
            $.ajax({
                url: g.ctx + 'pc/tender/bid/rest/submitQuotation',
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify(postData),
                complete: function () {
                    page.submitFlag = 0
                    topWin.layer.close(index)
                },
                success: function (data) {
                    topWin.layer.alert("保存成功", {icon: 1}, function (idx) {
                        topWin.layer.close(idx);
                        if (call !== undefined) {
                            call()
                        }
                    });
                },
                error: function (data) {
                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                }
            });
        },
        isReadOnly: function () {
            if (type === 0 || type === 2 || type === 3) {
                return true;
            }
            return false;
        },
        calculateNoTaxTotalPrice: function () {
            const rows = page.dataGrid.datagrid('getRows');
            // 初始化合计值为 0
            let totalTaxedQuotation = 0;
            // 循环遍历 rows 中的每一行，累加 taxedQuotation 字段的值
            for (let i = 0; i < rows.length; i++) {
                totalTaxedQuotation += parseFloat(rows[i].currentPrice) * parseFloat(rows[i].count) || 0;
            }
            let tt = getPrice(totalTaxedQuotation)
            $("input[numberboxname='bid.totalAmount']").numberbox("setValue", tt)
        },
        calculateTaxTotalPrice: function () {
            const rows = page.dataGrid.datagrid('getRows');
            // 初始化合计值为 0
            let totalTaxedQuotation = 0;
            // 循环遍历 rows 中的每一行，累加 taxedQuotation 字段的值
            for (let i = 0; i < rows.length; i++) {
                totalTaxedQuotation += parseFloat(rows[i].taxPrice) * parseFloat(rows[i].count) || 0;
            }
            let tt = getPrice(totalTaxedQuotation)
            $("input[numberboxname='bid.finalAmount']").numberbox("setValue", tt)
        },
        calculateUnTaxPrice: function (index, row) {
            var currentPrice = getDefaultTaxPrice(row.taxRateCode, row.taxPrice, 0)
            page.dataGrid.datagrid('updateRow', {index: index, row: {currentPrice: currentPrice}});
        },
        copy: function (field) {
            page.dataGrid.edatagrid("saveRow");
            var rows = page.dataGrid.edatagrid("getRows");
            var row = {}
            //取第一个
            var val = rows[0][field]
            row[field] = val
            $.each(rows, function (index) {
                    page.dataGrid.datagrid("updateRow", {
                        index: index, row: row
                    });
                }
            )
        },
        // 倒计时功能
        startCountdown: function (targetTime, display) {
            let timerInterval = undefined

            function updateCountdown() {
                const now = moment();
                const duration = moment.duration(targetTime.diff(now));

                if (duration.asSeconds() <= 0) {
                    if (timerInterval !== undefined) {
                        clearInterval(timerInterval);
                    }
                    display.textContent = "已截止";
                    return;
                }

                const hours = Math.floor(duration.asHours());
                const minutes = Math.floor(duration.minutes());
                const seconds = Math.floor(duration.seconds());

                display.textContent =
                    (hours < 10 ? "0" : "") + hours + "时" +
                    (minutes < 10 ? "0" : "") + minutes + "分" +
                    (seconds < 10 ? "0" : "") + seconds + "秒";
            }

            updateCountdown();  // 初始化显示
            timerInterval = setInterval(updateCountdown, 1000);
        },
        calNoTaxTotal: function (val) {
            let typeId = $('input[comboname="bid.typeId"]').combobox("getValue")
            if (typeId == 2) {
                const rows = page.dataGrid.datagrid('getRows');
                var currentPrice = getDefaultTaxPrice(rows[0].taxRateCode, val, 0)
                $("input[numberboxname='bid.totalAmount']").numberbox("setValue", currentPrice)
            }
        },

        /**
         * 在 columns 中插入一个列到某个列之前
         * @param {Array} columns - easyUI datagrid 的 columns（二维数组）
         * @param {Object} newCol - 要插入的新列（如 {field:'xxx', title:'xxx', width:100}）
         * @param {String} beforeLabelName - 要插入到这个 beforeLabelName 之前
         */
        insertColumnBefore: function(columns, newCol, beforeLabelName) {
            if (!columns || !columns.length) return columns;
            const index = columns.findIndex(function(c){
                return c.title === beforeLabelName;
            });

            // 找不到就直接 push 到最后
            if (index === -1) {
                columns.push(newCol);
            } else {
                columns.splice(index, 0, newCol);
            }

            return columns;
        }

    }
;
$(document).ready(function () {
    initDict('invoice_type');
    page.loadData(tenderId);
    $("#fileInput").filebox({
        buttonText: 'Choose', buttonAlign: 'left', onChange: page.bidFileUpload
    });
});