var tenderComm = {
    editFristTime: false,
    securityDepositFormPrefix: 'securityDeposit.',
    tenderFormPrefix: 'tender.',
    competitiveFormPrefix: 'competitive.',
    roundFormPrefix: 'round.',
    purchaseRequestType: '#purchaseRequestType',
    purchaseRequestTypeLabel: '#purchaseRequestTypeLabel',
    purchaseRequestTypeNoLabel: '#purchaseRequestTypeNoLabel',
    purchaseRequestTypeDiv: '#purchaseRequestTypeDiv',
    tenderDetailData: [],
    fileUploadType: 0,
    dictCodes: [],
    necessaryExt: [],
    materialCachMap: {},
    projectDataGrid: {},
    postField: [],
    detailField: [],
    tabsTitle: [],
    detailRequired: [],
    supplierNameMap: {},
    userIdMap: {},
    submitFlag: 0,
    detailEditIndex: 0,
    editSupplierIndex: 0,
    existMaterial: [],
    eventBind: function () {
        $("#tender input[comboname='" + tenderComm.tenderFormPrefix + "templateId']").combobox({'onSelect': tenderComm.templateSelect});
        $(tenderComm.purchaseRequestType).combobox({"onSelect": tenderComm.purchaseRequestTypeChangeEvent});
    },
    securityDepositFlagClick: function (target) {
        if ($('input[name="securityDeposit.securityDepositFlag"]:checked').val() == 0) {
            tenderComm.securityDepositSwitch(false);
            tenderComm.setSecurityDepositRequired(false)
        } else {
            tenderComm.securityDepositSwitch(true);
            tenderComm.setSecurityDepositRequired(true)

        }
    },
    securityDepositSwitch: function (flag) {
        if (flag) {
            $(".security_deposit").show();
            $(".security_deposit_no").hide();
        } else {
            $(".security_deposit").hide();
            $(".security_deposit_no").show();
        }
    },
    clearDetailData: function () {
        tenderComm.tenderDetailData = []
        if (tenderComm.projectDataGrid.length > 0) {
            tenderComm.projectDataGrid.datagrid("loadData", []);
        }
    },
    templateSelect: function (record) {
        tenderComm.hiddenPurchaseRequestType(record.id);
        if (tenderComm.editFristTime) {
            return
        }
        tenderComm.loadDetailField(record.id);
        //如果是mro自动默认器件分类
        if (record.id === '412') {
            $("#tender input[comboname='" + tenderComm.tenderFormPrefix + "purchaseCategoryCode']").combobox("setValue", 'Z005');
        }
    },
    typeIdChange: function () {
        if (tenderComm.editFristTime) {
            return
        }
        tenderComm.clearDetailData()
        $("#tender input[comboname='" + tenderComm.tenderFormPrefix + "templateId']").combobox("clear");
        tenderComm.templateLoad(0)
        tenderComm.loadDetailField(0);
    },
    templateLoad: function (templateId) {
        var typeId = $("#tender input[comboname='" + tenderComm.tenderFormPrefix + "typeId']").combobox('getValue');
        if (typeId) {
            var url2 = g.ctx + 'pc/tender/template/rest/listAll?typeId=' + typeId;
            $("#tender input[comboname='" + tenderComm.tenderFormPrefix + "templateId']").combobox("reload", url2);
        }
    },
    materialSelect: function (e) {
        tenderComm.materialDialogOpen();
    },
    materialCategorySelect: function (e) {
        parent.layer.open({
            title: '物料品类选择器',
            type: 2,
            area: ['80%', '80%'],
            skin: 'layui-layer-molv',
            content: '/material/group/category/selector',
            btn: ['确定', '关闭'],
            yes: function (index, layero) {
                let iframeWin = parent.window[layero.find('iframe')[0]['name']];
                parent.layer.close(index);
                iframeWin.chooseRow(function (data) {

                    let productType = tenderComm.projectDataGrid.datagrid('getEditor', {
                        index: tenderComm.detailEditIndex,
                        field: 'secondPurchaseCode'
                    }).target;
                    let productTypeName = tenderComm.projectDataGrid.datagrid('getEditor', {
                        index: tenderComm.detailEditIndex,
                        field: 'secondPurchaseName'
                    }).target;
                    productTypeName.textbox('setValue', data.secondLevelPurchaseName);
                    productType.textbox('setValue', data.secondLevelPurchaseCode);
                });

            }
        });
    },
    materialGroupSelect: function (e) {
        parent.layer.open({
            title: '物料组选择器',
            type: 2,
            area: ['80%', '80%'],
            skin: 'layui-layer-molv',
            content: '/material/group/selector',
            btn: ['确定', '关闭'],
            yes: function (index, layero) {
                let iframeWin = parent.window[layero.find('iframe')[0]['name']];
                parent.layer.close(index);
                iframeWin.chooseRow(function (data) {

                    let productType = tenderComm.projectDataGrid.datagrid('getEditor', {
                        index: tenderComm.detailEditIndex,
                        field: 'materialGroupCode'
                    }).target;
                    let productTypeName = tenderComm.projectDataGrid.datagrid('getEditor', {
                        index: tenderComm.detailEditIndex,
                        field: 'materialGroupName'
                    }).target;
                    productTypeName.textbox('setValue', data.name);
                    productType.textbox('setValue', data.code);
                });

            }
        });
    },
    materialDialogOpen: function () {
        var selectMaterialElement = openDialog("selectMaterialDialog", g.ctx + 'pc/sys/product/select/dialog?single=0', {
            title: '选择物料',
            width: '80%',
            height: '75%',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                selectMaterialElement.dialog('destroy');
            },
            buttons: [{
                text: '确定',
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['selectMaterialDialog'].chooseRows(function (rows) {
                        tenderComm.projectDataGrid.edatagrid("saveRow")
                        tenderComm.projectDataGrid.datagrid("deleteRow", tenderComm.detailEditIndex)
                        tenderComm.detailEditIndex = undefined
                        let tipMsg = []
                        $.each(rows, function (iidx, data) {
                            if (tenderComm.materialCachMap[data.id] == undefined) {
                                tenderComm.materialCachMap[data.id] = 1
                                data['materialId'] = data.id
                                data['unit'] = data.orderUnit
                                tenderComm.projectDataGrid.datagrid("appendRow", data)
                            } else {
                                tipMsg.push(data.materiaName)
                            }
                        })
                        selectMaterialElement.dialog('close');

                    })
                }
            }, {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    selectMaterialElement.dialog('close');
                }
            }]
        });
    },
    loadDetailField: function (templateId) {
        /**
         * 加载模板字段
         * 1.需要统计字典字段
         * 2.需要找到主数据字段
         * 3.需要找到日期字段
         * 4.
         */
        if (templateId == 0) {
            tenderComm.detailField = [];
            tenderComm.initItemDataGrid();
        } else {
            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.analysisFields(data)
                    tenderComm.initItemDataGrid();
                }
            });
        }
    },
    fieldsDictAndNecess: function (data) {
        $.each(data, function (index, item) {
            //需要单独处理
            if (item.fieldType === 'dict') {
                tenderComm.dictCodes.push(item.extVal)
            } else if (item.fieldType === 'data') {
                tenderComm.necessaryExt.push(item.extVal)
            }
        })
        if (tenderComm.dictCodes.length > 0) {
            initDict(tenderComm.dictCodes.join(","))
        }
        if (tenderComm.necessaryExt.length > 0) {
            initNecessaryDatas(tenderComm.necessaryExt.join(","))
        }
    },
    analysisFieldsForSupplier: function (data) {
        tenderComm.fieldsDictAndNecess(data)
        tenderComm.detailField = [{
            field: 'doorPrice',
            title: "门槛价",
            width: 150,
            align: 'left',
            hidden: true
        }];
        tenderComm.postField = [];
        tenderComm.detailRequired = {};
        $.each(data, function (index, item) {
            //需要单独处理
            if (item.fieldType === 'dict') {
                tenderComm.dictCodes.push(item.extVal)
            } else if (item.fieldType === 'data') {
                tenderComm.necessaryExt.push(item.extVal)
            }
        })
        if (tenderComm.dictCodes.length > 0) {
            initDict(tenderComm.dictCodes.join(","))
        }
        if (tenderComm.necessaryExt.length > 0) {
            initNecessaryDatas(tenderComm.necessaryExt.join(","))
        }
        $.each(data, function (index, item) {
            if (item.fieldName == 'tax_rate_code' || item.fieldName == 'currency') {
                item.supplierEdit = 1;
            }
            var supplierEditFlag = item.supplierEdit;
            var title = item.fieldAlias ? item.fieldAlias : item.labelName;
            if (supplierEditFlag === 1) {
                if (item.required === 1) {
                    tenderComm.detailRequired[toCamelCase(item.fieldName)] = title;
                }
            }

            if (supplierEditFlag !== 1) {
                title = '<span style="color: grey;">' + title + '</span>';
            }
            var items = {
                field: toCamelCase(item.fieldName),
                title: title,
                width: 150,
                align: 'left'
            };
            if (supplierEditFlag === 1 || item.supplierShow === 1) {
                if (item.required === 1) {
                    title = "<span style='color: red;'>*</span>" + title;
                    items.title = title
                }
                if (supplierEditFlag === 1 && item.copyFlag === 1) {
                    items.title = title + '<button type="button" onclick="page.copy(\'' + items.field + '\')" class="easyui-linkbutton">复制</button>'
                }
                if (item.fieldType === 'varchar') {
                    items.editor = {
                        type: 'textbox',
                        options: {
                            required: false, editable: true
                        }
                    };
                } else if (item.fieldType === 'numeric') {
                    var extOptions = JSON.parse(item.extVal)
                    if (extOptions !== undefined
                        && extOptions.precision !== undefined
                        && extOptions.precision === 'priceHandle.precision'
                    ) {
                        extOptions.precision = priceHandle.precision;
                    }
                    items.editor = {
                        type: 'numberbox',
                        options: extOptions
                    }
                    items.formatter = function (value) {
                        return formatterPrice(value)
                    }
                } else if (item.fieldType === 'date') {
                    items.editor = {
                        type: 'datebox',
                        options: {required: false, showSeconds: false, editable: false}
                    };
                    items.formatter = function (value, row, index) {
                        if (value === '') {
                            return '';
                        }
                        row[toCamelCase(item.fieldName)] = moment(value).format("YYYY-MM-DD");
                        return moment(value).format("YYYY-MM-DD");
                    }
                } else if (item.fieldType === 'dict') {
                    //字典字段
                    items.editor = {
                        type: 'combobox',
                        options: {
                            editable: true,
                            valueField: 'code',
                            textField: 'codeWithDesc',
                            data: getDictList(item.extVal)
                        }
                    }
                    items.formatter = function (value, row, index) {
                        return getDicName(item.extVal, value)
                    }
                    tenderComm.dictCodes.push(item.extVal)
                } else if (item.fieldType === 'data') {
                    items.editor = {
                        type: 'combobox',
                        options: {
                            editable: true,
                            valueField: 'code',
                            textField: 'codeWithDesc',
                            data: getNecessaryDataList(item.extVal)
                        }
                    }
                    items.formatter = function (value, row, index) {
                        return getNecessaryDataName(item.extVal, value)
                    }
                    tenderComm.necessaryExt.push(item.extVal)
                }
                if (item.supplierShow === 1 && supplierEditFlag !== 1) {
                    delete items.editor
                }
                tenderComm.detailField.push(items);
            }
            tenderComm.postField.push({
                fieldName: item.fieldAlias ? item.fieldAlias : item.labelName,
                supplierShow: item.supplierEdit === 1 ? 1 : item.supplierShow,
                supplierEdit: item.supplierEdit,
                extVal: item.extVal,
                fieldType: item.fieldType,
                fieldCode: item.fieldName,
                required: item.required,
                sort: item.fieldSort
            });
        });
    },
    analysisFields: function (data) {
        tenderComm.fieldsDictAndNecess(data)
        tenderComm.detailField = [{
            field: 'doorPrice',
            title: "<span style='color: red;'>*</span>门槛价",
            width: 150,
            align: 'left',
            hidden: true,
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    precision: priceHandle.precision
                }
            }
        }];
        tenderComm.postField = [];
        tenderComm.detailRequired = {};
        $.each(data, function (index, item) {
            //需要单独处理
            if (item.fieldType === 'dict') {
                tenderComm.dictCodes.push(item.extVal)
            } else if (item.fieldType === 'data') {
                tenderComm.necessaryExt.push(item.extVal)
            }
        })
        if (tenderComm.dictCodes.length > 0) {
            initDict(tenderComm.dictCodes.join(","))
        }
        if (tenderComm.necessaryExt.length > 0) {
            initNecessaryDatas(tenderComm.necessaryExt.join(","))
        }
        $.each(data, function (index, item) {
            if (item.fieldName === 'tax_rate_code' || item.fieldName === 'currency') {
                item.supplierEdit = 1;
            }
            var editFlag = item.edit;
            var supplierEditFlag = item.supplierEdit;
            var title = item.fieldAlias ? item.fieldAlias : item.labelName;
            if (editFlag === 1) {
                if (item.required === 1) {
                    tenderComm.detailRequired[toCamelCase(item.fieldName)] = title;
                }
            }

            if (supplierEditFlag && editFlag === 0) {
                title = '<span style="color: grey;">' + title + '</span>';
            }
            var items = {
                field: toCamelCase(item.fieldName),
                title: title,
                width: 150,
                align: 'left'
            };
            if (editFlag === 1) {
                if (item.required === 1) {
                    title = "<span style='color: red;'>*</span>" + title;
                    items.title = title
                }
                if (item.copyFlag === 1) {
                    items.title = title + '<button type="button" onclick="edit.copy(\'' + items.field + '\')" class="easyui-linkbutton">复制</button>'
                }
                if (item.fieldName === 'material_code') {
                    items.editor = {
                        type: 'textbox',
                        options: {
                            required: false, editable: false, icons: [{
                                iconCls: 'icon-search',
                                handler: tenderComm.materialSelect
                            }]
                        }
                    };
                } else if (item.fieldType === 'varchar') {
                    items.editor = {
                        type: 'textbox',
                        options: {
                            required: false, editable: true
                        }
                    };
                } else if (item.fieldType === 'numeric') {
                    var extOptions = JSON.parse(item.extVal)
                    items.editor = {
                        type: 'numberbox',
                        options: extOptions
                    };
                } else if (item.fieldType === 'date') {
                    items.editor = {
                        type: 'datebox',
                        options: {required: false, showSeconds: false, editable: false}
                    };
                    items.formatter = function (value, row, index) {
                        if (value == '') {
                            return '';
                        }
                        row[toCamelCase(item.fieldName)] = moment(value).format("YYYY-MM-DD");
                        return moment(value).format("YYYY-MM-DD");
                    }
                } else if (item.fieldType === 'dict') {
                    //字典字段
                    items.editor = {
                        type: 'combobox',
                        options: {
                            editable: true,
                            valueField: 'code',
                            textField: 'codeWithDesc',
                            data: getDictList(item.extVal)
                        }
                    }
                    items.formatter = function (value, row, index) {
                        return getDicName(item.extVal, value)
                    }
                    tenderComm.dictCodes.push(item.extVal)
                } else if (item.fieldType === 'data') {
                    items.editor = {
                        type: 'combobox',
                        options: {
                            editable: true,
                            valueField: 'code',
                            textField: 'codeWithDesc',
                            data: getNecessaryDataList(item.extVal)
                        }
                    }
                    items.formatter = function (value, row, index) {
                        return getNecessaryDataName(item.extVal, value)
                    }
                    tenderComm.necessaryExt.push(item.extVal)
                }
                tenderComm.detailField.push(items);
                tenderComm.postField.push({
                    fieldName: item.fieldAlias ? item.fieldAlias : item.labelName,
                    supplierShow: item.supplierEdit === 1 ? 1 : item.supplierShow,
                    supplierEdit: item.supplierEdit,
                    edit: item.edit,
                    extVal: item.extVal,
                    fieldType: item.fieldType,
                    fieldCode: item.fieldName,
                    required: item.required,
                    sort: item.fieldSort
                });
            } else {
                tenderComm.detailField.push(items);
            }
        });
    },
    initItemDataGrid: function () {
        var toolbars = [
            {
                text: '新增',
                iconCls: 'icon-add',
                hidden: true,
                handler: function () {
                    tenderComm.projectDataGrid.edatagrid("saveRow");
                    if (!$("#tender input[comboname='" + tenderComm.tenderFormPrefix + "templateId']").combobox("getValue")) {
                        topWin.layer.msg("请先选择招标模板!");
                        return;
                    }
                    tenderComm.projectDataGrid.datagrid('appendRow', {
                        priceStartDate: moment().format('YYYY-MM-DD'),
                        priceValidityDate: moment().add(1, 'years').format('YYYY-MM-DD'),
                        unit: 'PCS'
                    });
                }
            }, "-",
            {
                text: '复制',
                iconCls: 'icon-plan-copy',
                hidden: true,
                handler: function () {
                    debugger
                    tenderComm.projectDataGrid.edatagrid("saveRow");
                    var rows = tenderComm.projectDataGrid.edatagrid("getChecked");
                    if (rows.length != 1) {
                        layer.msg("请先选择需要复制的行!");
                        return;
                    }
                    debugger
                    var rr = rows[0];
                    // var newRow = JSON.parse(JSON.stringify(rr));
                    // newRow.id = null;
                    tenderComm.projectDataGrid.edatagrid('appendRow', rr);
                    tenderComm.projectDataGrid.datagrid('clearSelections');
                    tenderComm.detailEditIndex = null;
                    debugger
                }
            }, "-",
            {
                text: '下载模板',
                iconCls: 'icon-download',
                handler: function () {
                    tenderComm.projectDataGrid.edatagrid("saveRow");
                    if (!$("#tender input[comboname='" + tenderComm.tenderFormPrefix + "templateId']").combobox("getValue")) {
                        topWin.layer.msg("请先选择模板!");
                        return;
                    }
                    var val = $('input[name="tender.thresholdFlag"]:checked').val();
                    window.open(g.ctx + 'pc/tender/template/rest/export?thresholdFlag=' + val +
                        '&templateId=' + $("#tender input[comboname='" + tenderComm.tenderFormPrefix + "templateId']").combobox("getValue") + "&_" + new Date().valueOf())
                }
            }, "-",
            {
                text: '导入',
                iconCls: 'icon-import',
                handler: function () {
                    tenderComm.projectDataGrid.edatagrid("saveRow");
                    $("#detailUpload .filebox-label").click();
                }
            }, "-",
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    tenderComm.projectDataGrid.edatagrid("saveRow");
                    var rows = tenderComm.projectDataGrid.edatagrid("getChecked");
                    if (rows.length > 0) {
                        $.each(rows, function (index, row) {
                            delete tenderComm.materialCachMap[row.materialId]
                            var rowIndex = tenderComm.projectDataGrid.edatagrid('getRowIndex', row);
                            tenderComm.projectDataGrid.edatagrid("deleteRow", rowIndex);
                        });
                    } else {
                        layer.msg("请选择需要删除的行项目!")
                    }
                }
            }];
        if (tenderComm.readOnlyFlag()) {
            //查看和审核只能看不能添加和删除
            toolbars = []
        }
        tenderComm.detailField.unshift({
            field: 'ck',
            checkbox: true
        }, {
            field: 'materialId',
            hidden: true,
            editor: {
                type: 'textbox'
            }
        });
        //如果是 type =4 或者type=5是查看和审核
        if (tenderComm.readOnlyFlag()) {
            $.each(tenderComm.detailField, function (index, item) {
                item.editor = {}
            })
        }
        if (tenderComm.projectDataGrid.length === undefined) {
            tenderComm.projectDataGrid = $('#project_table').edatagrid({
                iconCls: 'icon-list',
                width: '100%',
                height: window.innerHeight - 55,
                autoSave: true,
                singleSelect: false,
                pagination: false,
                rownumbers: true,
                remoteSort: true,
                striped: true,
                toolbar: toolbars,
                columns: [tenderComm.detailField],
                onEdit: function (index) {
                    tenderComm.detailEditIndex = index;
                },
                onClickRow: function (index,row) {
                    debugger
                    if (tenderComm.detailEditIndex) {
                        var rows = tenderComm.projectDataGrid.datagrid("getRows");
                        for(var i = 0; i < rows.length; i++) {
                            if (tenderComm.detailEditIndex !== i) {
                                tenderComm.projectDataGrid.datagrid('endEdit', i);
                            }
                        }
                    }
                    if (tenderComm.detailEditIndex && tenderComm.detailEditIndex !== index) {
                        tenderComm.detailEditIndex = index;
                    } else {
                        tenderComm.detailEditIndex = index;
                    }
                }
                ,
                onLoadSuccess: function () {
                    setTimeout(function () {
                        tenderComm.thresholdFlagClick()
                    }, 2)

                }
            });
            if (tenderComm.tenderDetailData != undefined) {
                tenderComm.projectDataGrid.edatagrid("loadData", tenderComm.tenderDetailData);
            }

        } else {
            var rows = tenderComm.projectDataGrid.datagrid("getRows")
            tenderComm.projectDataGrid = $('#project_table').edatagrid({
                columns: [tenderComm.detailField]
            });
            tenderComm.projectDataGrid.edatagrid("loadData", rows);
        }
    },
    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/import',
                data: formData,
                type: 'POST',
                contentType: false,
                processData: false,
                complete: function (xhr) {
                    $("#detailFileInput").filebox("clear");
                    topWin.layer.close(index);
                },
                success: function (d) {
                    tenderComm.projectDataGrid.edatagrid("loadData", {
                        total: d.length,
                        rows: d
                    });
                },
                error: function (data) {
                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                }
            })
        }
    },
    //处理供应商选择
    initSupplierDataGrid: function (data) {
        var columns = [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'supplierCode',
                title: '供应商编码',
                width: 150,
                align: 'left'
            },
            {
                field: 'supplierName',
                title: '供应商名称',
                width: 300,
                align: 'left'
            },
            {
                field: 'currency',
                title: '币种',
                width: '10%',
                align: 'left',
                formatter: function (value, row) {
                    return getDicName('currency', value);
                }
            },
            {
                field: 'taxCode',
                title: '税率',
                width: '10%',
                align: 'center',
                formatter: function (value) {
                    return getNecessaryDataName('pc/sys/tax/rest/listAll', value);
                }
            },

            {
                field: 'paymentMethod',
                title: '付款条件',
                width: '12%',
                align: 'center',
                formatter: function (value) {
                    return getDicName('payment_method', value);
                }
            },
            {
                field: 'contactsId',
                hidden: true
            },
            {
                field: 'contacts',
                title: '<span style="color:red">*</span>邮箱',
                width: 360,
                editor: {
                    type: 'textbox',
                    options: {
                        editable: false,
                        icons: [{
                            iconCls: 'icon-search',
                            handler: function () {
                                var row = $('#supplier_table').datagrid('getRows')[tenderComm.editSupplierIndex];
                                var url = g.ctx + "pc/supplier/contact/page/select?single=0&supplierCode=" + row.supplierCode + '&type=12';
                                var choseSupplierEmailDialog = openDialog('choseEmailSupplier', url, {
                                    title: '供应商邮箱选择',
                                    width: '80%',
                                    height: '70%',
                                    cache: false,
                                    modal: true,
                                    border: 'thin',
                                    onClose: function () {
                                        choseSupplierEmailDialog.dialog('destroy');
                                    },
                                    buttons: [
                                        {
                                            text: '确定',
                                            iconCls: 'icon-ok',
                                            handler: function () {
                                                topWin.frames['choseEmailSupplier'].chooseRow(function (data) {
                                                    let supplierEmail = $('#supplier_table').datagrid('getEditor', {
                                                        index: tenderComm.editSupplierIndex,
                                                        field: 'contacts'
                                                    }).target;
                                                    var emailList = [];
                                                    var contactsList = [];
                                                    $.each(data, function (index, target) {
                                                        emailList.push(target.contactsName + ":" + target.email);
                                                        contactsList.push(target.id);
                                                    });
                                                    supplierEmail.textbox('setValue', emailList.join(','));
                                                    $('#supplier_table').edatagrid("saveRow")
                                                    $('#supplier_table').datagrid('updateRow', {
                                                        index: tenderComm.editSupplierIndex,
                                                        row: {
                                                            contactsId: contactsList.join(','),
                                                        }
                                                    });
                                                    choseSupplierEmailDialog.dialog('close');
                                                });
                                            }
                                        },
                                        {
                                            text: '关闭',
                                            iconCls: 'icon-cancel',
                                            handler: function () {
                                                choseSupplierEmailDialog.dialog('close');
                                            }
                                        }
                                    ]
                                });
                            }
                        }]
                    }
                }
            },
            {
                field: 'purchaseCategoryCode',
                title: '<span style="color:red">*</span>采购品类编码',
                width: 130,
                editor: {
                    type: 'textbox',
                    options: {
                        editable: false,
                        required: true,
                        icons: [{
                            iconCls: 'icon-search',
                            handler: function () {
                                var row = $('#supplier_table').datagrid('getRows')[tenderComm.editSupplierIndex];
                                var url = g.ctx + "pc/supplier/purchaseCategory/page/selector?single=1&supplierId=" + row.supplierId;
                                var chosePurchaseCategoryDialog = openDialog('chosePurchaseCategoryDialog', url, {
                                    title: '供应商品类选择',
                                    width: '80%',
                                    height: '70%',
                                    cache: false,
                                    modal: true,
                                    border: 'thin',
                                    onClose: function () {
                                        chosePurchaseCategoryDialog.dialog('destroy');
                                    },
                                    buttons: [
                                        {
                                            text: '确定',
                                            iconCls: 'icon-ok',
                                            handler: function () {
                                                topWin.frames['chosePurchaseCategoryDialog'].chooseRow(function (data) {
                                                    let purchaseCategoryCode = $('#supplier_table').datagrid('getEditor', {
                                                        index: tenderComm.editSupplierIndex,
                                                        field: 'purchaseCategoryCode'
                                                    }).target;
                                                    purchaseCategoryCode.textbox('setValue', data[0].purchaseCategoryCode);
                                                    $('#supplier_table').edatagrid("saveRow")
                                                    $('#supplier_table').datagrid('updateRow', {
                                                        index: tenderComm.editSupplierIndex,
                                                        row: {
                                                            purchaseCategoryName: data[0].purchaseCategoryName,
                                                            currencyCode: data[0].currencyCode,
                                                            taxCode: data[0].taxCode,
                                                            currency: data[0].currencyCode,
                                                            paymentMethod: data[0].paymentTerms,
                                                            companyCode: data[0].companyCode
                                                        }
                                                    });
                                                    chosePurchaseCategoryDialog.dialog('close');
                                                });
                                            }
                                        },
                                        {
                                            text: '关闭',
                                            iconCls: 'icon-cancel',
                                            handler: function () {
                                                chosePurchaseCategoryDialog.dialog('close');
                                            }
                                        }
                                    ]
                                });
                            }
                        }]
                    }
                }
            },
            {
                field: 'purchaseCategoryName',
                title: '采购品类名称',
                width: 160,
            },
            {
                field: 'companyCode',
                title: '公司',
                width: 240,
                formatter: function (value) {
                    return getNecessaryDataName('pc/sys/company/rest/listAll', value);
                }
            }
        ]];
        var toolbars = [
            {
                text: '新增供应商',
                iconCls: 'icon-add',
                id: "add_supplier_btn",
                handler: tenderComm.openSupplierDialog
            }, "-",
            {
                text: '删除供应商',
                iconCls: 'icon-remove',
                id: "del_supplier_btn",
                handler: function () {
                    var rows = tenderComm.supplierDataGrid.datagrid("getChecked");
                    var delCodes = [];
                    $.each(rows, function (index, item) {
                        delCodes.push(item.supplierName);
                    });
                    $.each(rows, function (index, item) {
                        var rowIndex = tenderComm.supplierDataGrid.datagrid('getRowIndex', item);
                        tenderComm.supplierDataGrid.datagrid('deleteRow', rowIndex);
                    });
                    $.each(delCodes, function (index, name) {
                        delete tenderComm.supplierNameMap[name];
                    });
                }
            }];
        if (tenderComm.readOnlyFlag()) {
            //查看和审核只能看不能添加和删除
            toolbars = []
        }
        initDict('currency,payment_way,payment_method');
        initNecessaryDatas('pc/sys/tax/rest/listAll,pc/sys/company/rest/listAll');
        this.supplierDataGrid = $('#supplier_table').edatagrid({
            iconCls: 'icon-list',
            singleSelect: false,
            data: data,
            width: '100%',
            height: window.innerHeight - 55,
            rownumbers: true,
            fitColumns: false,
            nowrap: true,
            remoteSort: true,
            autoSave: true,
            striped: true,
            columns: columns,
            toolbar: toolbars,
            onBeginEdit: function (index, row) {
                tenderComm.editSupplierIndex = index;
            },
            onSave: (index, row) => {
                tenderComm.supplierNameMap[row.supplierName] = "";
            }
        });
    },
    openSupplierDialog: function () {
        tenderComm.supplierDataGrid.edatagrid('saveRow');
        //需要先选品类和公司
        let companyCode = $("#tender input[comboname='" + tenderComm.tenderFormPrefix + "companyCode']").combobox("getValue")
        if (!companyCode) {
            topWin.layer.alert('请先选择签约主体', {icon: 0});
            return;
        }
        let purchaseCategoryCode = $("#tender input[comboname='" + tenderComm.tenderFormPrefix + "purchaseCategoryCode']").combobox("getValue")
        if (!purchaseCategoryCode) {
            topWin.layer.alert('请先选择器件分类', {icon: 0});
            return;
        }
        var supplierDialogElement = openDialog("supplierDialog", g.ctx + "pc/supplier/supplierSelect?single=0", {
            title: "供应商选择",
            width: '800',
            height: '80%',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                supplierDialogElement.dialog('destroy');
            },
            buttons: [{
                text: '选择', iconCls: 'icon-save', handler: function () {
                    topWin.frames['supplierDialog'].chooseRow(function (rows) {
                        let supplierIds = rows.map(a => a.id).join(",");
                        var load = topWin.layer.load(0, {
                            shade: [0.6, '#eee'] //0.1透明度的白色背景
                        });
                        $.ajax({
                            url: g.ctx + 'pc/supplier/purchaseCategory/rest/getCompanyCategoryAndSupplierIds',
                            method: "GET",
                            data: {companyCode: companyCode, category: purchaseCategoryCode, supplierIds: supplierIds},
                            complete: function () {
                                topWin.layer.close(load)
                            },
                            success: function (data) {
                                const transformedData = data.reduce((acc, item) => {
                                    acc[item.supplierId] = item;
                                    return acc;
                                }, {});
                                $.each(rows, function (index, item) {
                                    if (tenderComm.supplierNameMap[item.supplierName] == undefined) {
                                        var row = {}
                                        let cat = transformedData[item.id]
                                        if (cat !== undefined) {
                                            row = {
                                                supplierId: item.id,
                                                supplierCode: item.supplierCode,
                                                supplierName: item.supplierName,
                                                currency: cat.currencyCode,
                                                taxCode: cat.taxCode,
                                                paymentMethod: cat.paymentTerms,
                                                purchaseCategoryCode: cat.purchaseCategoryCode,
                                                purchaseCategoryName: cat.purchaseCategoryName,
                                                companyCode: cat.companyCode
                                            }
                                        }else{
                                            row = {
                                                supplierId: item.id,
                                                supplierCode: item.supplierCode,
                                                supplierName: item.supplierName
                                            }
                                        }
                                        tenderComm.getSupplierEmail(row)
                                        tenderComm.supplierDataGrid.datagrid('appendRow', row);
                                        tenderComm.supplierNameMap[item.supplierName] = '';
                                    }
                                })
                                supplierDialogElement.dialog('close');
                            },
                            error: function (data) {
                                topWin.layer.alert(data.responseJSON.message, {icon: 2});
                            }
                        });

                    });
                }
            }, {
                text: '关闭', iconCls: 'icon-cancel', handler: function () {
                    supplierDialogElement.dialog('close');
                }
            }]
        })
    },
    //处理开标小组
    initOpenBidUserDatagird: function (data) {
        var toolbars = [
            {
                text: '新增',
                iconCls: 'icon-add',
                hidden: true,
                handler: tenderComm.openUserDialog
            }, "-",
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    var rows = tenderComm.openBidUserDatagrid.datagrid("getChecked");
                    $.each(rows, function (index, item) {
                        delete tenderComm.userIdMap[item.id];
                        var rowIndex = tenderComm.openBidUserDatagrid.datagrid('getRowIndex', item);
                        tenderComm.openBidUserDatagrid.datagrid("deleteRow", rowIndex);
                    });
                }
            }];
        if (tenderComm.readOnlyFlag()) {
            //查看和审核只能看不能添加和删除
            toolbars = []
        }
        var columns = [[{
            field: 'ck',
            checkbox: true
        }, {
            field: 'id',
            hidden: true
        }, {
            field: 'username',
            title: '开标人姓名',
            width: 150,
            align: 'left'
        }, {
            field: 'accountName',
            title: '登录名',
            width: 150,
            align: 'left'
        }]];
        tenderComm.openBidUserDatagrid = $('#open_bid_table').datagrid({
            iconCls: 'icon-list',
            data: data,
            width: '100%',
            height: '100%',
            singleSelect: false,
            pagination: false,
            rownumbers: true,
            fitColumns: false,
            nowrap: true,
            remoteSort: true,
            striped: true,
            columns: columns,
            toolbar: toolbars
        });
    },
    openUserDialog: function () {
        var userDialogElement = openDialog("userDialog", g.ctx + "pc/sys/user/index?select=1&single=0", {
            title: "用户选择",
            width: '80%',
            height: '80%',
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                userDialogElement.dialog('destroy');
            },
            buttons: [{
                text: '选择', iconCls: 'icon-save', handler: function () {
                    topWin.frames['userDialog'].chooseRow(function (rows) {
                        $.each(rows, function (index, item) {
                            if (tenderComm.userIdMap[item.id] == undefined) {
                                item.userId = item.id;
                                tenderComm.openBidUserDatagrid.datagrid('appendRow', item);
                                tenderComm.userIdMap[item.id] = '';
                            }

                        });
                        userDialogElement.dialog('close');
                    });
                }
            }, {
                text: '关闭', iconCls: 'icon-cancel', handler: function () {
                    userDialogElement.dialog('close');
                }
            }]
        })
    },
    fileUpload: function (v1, v2) {
        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: tenderComm.fileUploadType
                }
                tenderComm.fileDataGrid.datagrid("appendRow", data);
                $("#fileInput").filebox("clear")
            })
            $("#fileInput").filebox("clear")
        }
    },
    initAttanchmentDatagrid: function (data, readOnlyFlag) {
        var columns = [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'filePath',
                hidden: true
            },
            {
                field: 'type',
                title: '类型',
                width: 120,
                align: 'left',
                formatter: function (value, row, index) {
                    return ATTACHMENT_TYPE[value].color
                }
            },
            {
                field: 'fileName',
                title: '文件名称',
                width: 400,
                align: 'left'
            }, {
                field: 'fileId',
                title: '查看',
                width: 150,
                align: 'left',
                formatter: function (value, row, index) {
                    return '<a href="' + g.ctx + 'pc/sys/file/rest/download/' + value + '">' + row.fileName + '</a>';
                }
            }
        ]];
        $("#fileInput").filebox({
            buttonText: 'Choose',
            buttonAlign: 'left',
            onChange: tenderComm.fileUpload
        });
        var toolbars = [
            {
                text: '上传技术标附件',
                iconCls: 'icon-add',
                hidden: true,
                handler: function () {
                    tenderComm.fileUploadType = 1;
                    $("#fileUpload .filebox-label").click();
                }
            }, "-",
            {
                text: '上传商务标附件',
                iconCls: 'icon-add',
                hidden: true,
                handler: function () {
                    tenderComm.fileUploadType = 2;
                    $("#fileUpload .filebox-label").click();
                }
            }, "-",
            {
                text: '删除文件',
                iconCls: 'icon-remove',
                handler: function () {
                    var rows = tenderComm.fileDataGrid.datagrid("getChecked");
                    $.each(rows, function (index, item) {
                        tenderComm.fileDataGrid.datagrid('deleteRow', tenderComm.fileDataGrid.datagrid('getRowIndex', item));
                    });
                }
            }];
        if (readOnlyFlag) {
            //查看和审核只能看不能添加和删除
            toolbars = []
        }
        this.fileDataGrid = $('#file_table').datagrid({
            iconCls: 'icon-list',
            data: data,
            width: '100%',
            height: window.innerHeight - 55,
            rownumbers: true,
            fitColumns: false,
            nowrap: true,
            remoteSort: true,
            striped: true,
            columns: columns,
            toolbar: toolbars
        });
    },
    //编辑数据处理
    loadData: function (id) {
        var index = topWin.layer.load(0, {
            shade: [0.6, '#eee'] //0.1透明度的白色背景
        });
        tenderComm.loadDataAjax(id, function (d) {
            //需要填充数据，需要把数据处理成 tender.name这种格式
            tenderComm.data = d
            tenderComm.tenderDetailData = d.tenderDetails;
            $.each(tenderComm.tenderDetailData, function (idx, itm) {
                tenderComm.materialCachMap[itm.materialId] = 1
            })
            const fd = {}
            $.each(d.tender, function (idx, itm) {
                fd[tenderComm.tenderFormPrefix + idx] = itm
            })
            $.each(d.securityDeposit, function (idx, itm) {
                fd[tenderComm.securityDepositFormPrefix + idx] = itm
            })
            $.each(d.competitive, function (idx, itm) {
                fd[tenderComm.competitiveFormPrefix + idx] = itm
            })
            $.each(d.round, function (idx, itm) {
                fd[tenderComm.roundFormPrefix + idx] = itm
            })
            $("#tender").form("load", fd)
            tenderComm.templateLoad(d.tender.templateId)
            tenderComm.loadDetailField(d.tender.templateId);
            var securityDeposit = d.securityDeposit || '';
            $.each(d.bidSupplierDtos, function (index, item) {
                tenderComm.supplierNameMap[item.supplierName] = '';
            });
            tenderComm.initSupplierDataGrid(d.bidSupplierDtos);
            $.each(d.userRelations, function (index, item) {
                tenderComm.userIdMap[item.id] = '';
            });
            setTimeout(function () {
                tenderComm.editFristTime = false
                if (securityDeposit == '') {
                    $("input[radiobuttonname='securityDeposit.securityDepositFlag'][value='0']").radiobutton("check");
                    tenderComm.securityDepositSwitch(false);
                    tenderComm.setSecurityDepositRequired(false)
                } else {
                    tenderComm.securityDepositSwitch(true);
                    tenderComm.setSecurityDepositRequired(true)
                    $("input[radiobuttonname='securityDeposit.securityDepositFlag'][value='1']").radiobutton("check");
                }
                if (tenderComm.readOnlyFlag()) {
                    //查看和审核所有控件只读
                    // 设置所有 datetimebox 为只读模式
                    $('.easyui-datetimebox').datetimebox('readonly', true);

                    // 设置所有 NumberBox 为只读模式
                    $('.easyui-numberbox').numberbox('readonly', true);

                    // 设置所有 TextBox 为只读模式
                    $('.easyui-textbox').textbox('readonly', true);

                    // 设置所有 ComboBox 为只读模式
                    $('.easyui-combobox').combobox('readonly', true);

                    $('input[type="radio"]').prop('disabled', true);

                    $('.easyui-radiobutton').radiobutton('disable');

                }
                topWin.layer.close(index)
                // 触发一次招标类型变更事件
                tenderComm.purchaseRequestTypeChangeEvent({code: $(tenderComm.purchaseRequestType).combobox("getValue")});
            }, 500)
            tenderComm.initOpenBidUserDatagird(d.userRelations)
            tenderComm.initAttanchmentDatagrid(d.tenderAttachmentList, tenderComm.readOnlyFlag());
        })
    },
    loadDataAjax: function (id, call) {
        $.ajax({
            url: g.ctx + 'pc/tender/rest/getDetail',
            data: {id: id},
            type: "GET",
            success: function (d) {
                call(d)
            }
        });
    },
    //采购申请转招标数据
    //编辑数据处理
    loadPurchaseDataData: function (ids) {
        var index = topWin.layer.load(0, {
            shade: [0.6, '#eee'] //0.1透明度的白色背景
        });
        tenderComm.loadPurchaseDataAjax(ids, function (d) {
            //需要填充数据，需要把数据处理成 tender.name这种格式
            tenderComm.data = d
            tenderComm.tenderDetailData = d.tenderDetails;
            $.each(tenderComm.tenderDetailData, function (idx, itm) {
                tenderComm.materialCachMap[itm.materialId] = 1
                itm.purchaseBillCode = itm.billCode;
                itm.purchaseBillItemCode = itm.itemCode;
            })
            const fd = {}
            $.each(d.tender, function (idx, itm) {
                fd[tenderComm.tenderFormPrefix + idx] = itm
            })
            $.each(d.securityDeposit, function (idx, itm) {
                fd[tenderComm.securityDepositFormPrefix + idx] = itm
            })
            $.each(d.competitive, function (idx, itm) {
                fd[tenderComm.competitiveFormPrefix + idx] = itm
            })
            $.each(d.round, function (idx, itm) {
                fd[tenderComm.roundFormPrefix + idx] = itm
            })
            $("#tender").form("load", fd)
            if (d.tender.purchaseOrgCode && d.tender.purchaseOrgCode != null) {
                $("#tender input[comboname='" + tenderComm.tenderFormPrefix + "purchaseOrgCode']").combobox("setValue", d.tender.purchaseOrgCode);
            }
            tenderComm.templateLoad(d.tender.templateId)
            tenderComm.loadDetailField(d.tender.templateId);
            var securityDeposit = d.securityDeposit || '';
            $.each(d.bidSupplierDtos, function (index, item) {
                tenderComm.supplierNameMap[item.supplierName] = '';
            });
            tenderComm.initSupplierDataGrid(d.bidSupplierDtos);
            $.each(d.userRelations, function (index, item) {
                tenderComm.userIdMap[item.id] = '';
            });
            setTimeout(function () {
                tenderComm.editFristTime = false
                if (securityDeposit == '') {
                    $("input[radiobuttonname='securityDeposit.securityDepositFlag'][value='0']").radiobutton("check");
                    tenderComm.securityDepositSwitch(false);
                    tenderComm.setSecurityDepositRequired(false)
                } else {
                    tenderComm.securityDepositSwitch(true);
                    tenderComm.setSecurityDepositRequired(true)
                    $("input[radiobuttonname='securityDeposit.securityDepositFlag'][value='1']").radiobutton("check");
                }
                if (tenderComm.readOnlyFlag()) {
                    //查看和审核所有控件只读
                    // 设置所有 datetimebox 为只读模式
                    $('.easyui-datetimebox').datetimebox('readonly', true);

                    // 设置所有 NumberBox 为只读模式
                    $('.easyui-numberbox').numberbox('readonly', true);

                    // 设置所有 TextBox 为只读模式
                    $('.easyui-textbox').textbox('readonly', true);

                    // 设置所有 ComboBox 为只读模式
                    $('.easyui-combobox').combobox('readonly', true);

                    $('input[type="radio"]').prop('disabled', true);

                    $('.easyui-radiobutton').radiobutton('disable');

                }
                topWin.layer.close(index)
            }, 500)
            tenderComm.initOpenBidUserDatagird(d.userRelations)
            tenderComm.initAttanchmentDatagrid(d.tenderAttachmentList, tenderComm.readOnlyFlag());
        })
    },
    loadPurchaseDataAjax: function (ids, call) {
        $.ajax({
            url: g.ctx + 'pc/inquiry/purchase/apply/bill/detail/rest/transfer/tender',
            data: {purchaseBillDetailIds: ids},
            type: "GET",
            success: function (d) {
                call(d)
            }
        });
    },
    setComboboxRequired: function (el, required) {
        if ($(el).length <= 0) {
            return
        }
        var val = $(el).combobox("getValue");
        $(el).textbox({required: required});
        $(el).combobox("setValue", val);
    },
    setDatetimeboxRequired: function (el, required) {
        if ($(el).length <= 0) {
            return
        }
        var val = $(el).datetimebox("getValue");
        $(el).textbox({required: required});
        $(el).datetimebox("setValue", val);
    },

    //保证金代码
    addBondAccount: function () {
        var url = g.ctx + "pc/tender/securityDeposit/page/index";
        tenderComm.bondAccountDialog = openDialog("bondAccountDialog",
            url, {
                title: '保证金账号',
                width: 800,
                height: 700,
                cache: false,
                modal: true,
                border: false,
                draggable: false,
                shadow: false,
                onClose: function () {
                    tenderComm.bondAccountDialog.dialog('destroy');
                },
                buttons: [{
                    text: '确定',
                    handler: function () {
                        var rows = topWin.frames['bondAccountDialog'].page.getChecked();
                        if (rows.length <= 0) {
                            return;
                        } else {
                            const fd = {}
                            $.each(rows[0], function (itx, itm) {
                                fd[tenderComm.securityDepositFormPrefix + itx] = itm
                            })
                            $("#tender").form("load", fd)
                            tenderComm.bondAccountDialog.dialog('close');
                        }
                    }
                }, {
                    text: '关闭',
                    handler: function () {
                        tenderComm.bondAccountDialog.dialog('close');
                    }
                }]
            });
    },
    setSecurityDepositRequired: function (required) {
        $("#tender input[textboxname='" + tenderComm.securityDepositFormPrefix + "amount']").numberbox({required: required});
        $("#tender input[textboxname='" + tenderComm.securityDepositFormPrefix + "bankNo']").textbox({required: required});
        $("#tender input[textboxname='" + tenderComm.securityDepositFormPrefix + "openBank']").textbox({required: required});
        $("#tender input[textboxname='" + tenderComm.securityDepositFormPrefix + "companyName']").textbox({required: required});
        $("#tender input[textboxname='" + tenderComm.securityDepositFormPrefix + "contacts']").textbox({required: required});
        tenderComm.setDatetimeboxRequired("#tender input[textboxname='" + tenderComm.securityDepositFormPrefix + "endDay']", required)
        tenderComm.setComboboxRequired("#tender input[textboxname='" + tenderComm.securityDepositFormPrefix + "payType']", required);
        tenderComm.setComboboxRequired("#tender input[textboxname='" + tenderComm.securityDepositFormPrefix + "currency']", required);

    },
    readOnlyFlag: function () {
        if (type == 4 || type == 5) {
            return true;
        }
        return false;
    },
    getFormData: function () {
        var array = $('#tender').serializeArray();
        //需要把数据分类组装
        var postData = {
            type: type,
            tender: {id: id},
            round: {},
            securityDeposit: {},
            competitive: {}
        }
        $.each(array, function (idx, itm) {
            if (itm.name.indexOf(tenderComm.tenderFormPrefix) != -1) {
                postData['tender'][itm.name.replace(tenderComm.tenderFormPrefix, '')] = itm.value;
            } else if (itm.name.indexOf(tenderComm.roundFormPrefix) != -1) {
                postData['round'][itm.name.replace(tenderComm.roundFormPrefix, '')] = itm.value;
            } else if (itm.name.indexOf(tenderComm.securityDepositFormPrefix) != -1) {
                postData['securityDeposit'][itm.name.replace(tenderComm.securityDepositFormPrefix, '')] = itm.value;
            } else if (itm.name.indexOf(tenderComm.competitiveFormPrefix) != -1) {
                postData['competitive'][itm.name.replace(tenderComm.competitiveFormPrefix, '')] = itm.value;
            }
        })
        if (postData.securityDeposit.securityDepositFlag === 0) {
            postData.securityDeposit = null
        }
        var supplier = tenderComm.supplierDataGrid.datagrid("getRows");
        postData.bidSupplierDtos = supplier
        var openUsers = tenderComm.openBidUserDatagrid.datagrid("getRows");
        postData.userRelations = openUsers
        var files = tenderComm.fileDataGrid.datagrid("getRows");
        postData.tenderAttachmentList = files
        var detailRows = [];
        if (tenderComm.projectDataGrid != null) {
            debugger
            tenderComm.projectDataGrid.edatagrid("saveRow");
            detailRows = tenderComm.projectDataGrid.datagrid("getRows");
        }
        postData.tenderDetails = detailRows
        return postData
    }, agree: function (call) {
        topWin.layer.prompt({title: '请输入审批意见', formType: 2, value: "同意"}, function (value, index, elem) {
            if (value === '') {
                return elem.focus();
            }
            tenderComm.postApproval(id, 1, value, call)
            topWin.layer.close(index);
        });

    },
    reject: function (call) {
        topWin.layer.prompt({title: '请输入审批意见', formType: 2}, function (value, index, elem) {
            if (value === '') {
                return elem.focus();
            }
            tenderComm.postApproval(id, 2, value, call)
            topWin.layer.close(index);
        });
    },
    postApproval: function (id, status, remark, callback) {
        if (tenderComm.submitFlag == 1) {
            return
        }
        tenderComm.submitFlag = 1
        $.ajax({
            url: g.ctx + 'pc/tender/rest/approval',
            type: "POST",
            data: {id: id, status: status, remark: remark},
            complete: function () {
                tenderComm.submitFlag = 0;
            },
            success: function (d) {
                callback();
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    },
    answerQuestions: function (id, type) {
        tenderComm.answerQuestionsDialogElement = openDialog("answerQuestionsDialog", "pc/tender/question/page/index?tenderId=" + id + "&type=" + type, {
            title: tenderTitles.tenderAQ,
            width: 1200,
            height: 753,
            cache: false,
            modal: true,
            border: false,
            draggable: false,
            shadow: false,
            onClose: function () {
                tenderComm.answerQuestionsDialogElement.dialog('destroy');
            },
            buttons: [{
                text: tenderBtns.close,
                handler: function () {
                    tenderComm.answerQuestionsDialogElement.dialog('close');
                }
            }]
        });
    },
    showDoorPrice: function (type) {
        if (type === 0) {
            if (tenderComm.projectDataGrid.length !== undefined) {
                if ($('#project_table').datagrid("getColumnOption", "doorPrice") !== null) {
                    $('#project_table').datagrid("hideColumn", "doorPrice")
                }
            }
        } else {
            if (tenderComm.projectDataGrid.length !== undefined) {
                if ($('#project_table').datagrid("getColumnOption", "doorPrice") !== null) {
                    $('#project_table').datagrid("showColumn", "doorPrice")
                }
            }
        }

        setTimeout(function () {
            $('#project_table').datagrid("resize")
        }, 10)
    },
    thresholdFlagClick: function () {
        if ($('input[name="tender.thresholdFlag"]:checked').val() === '0') {
            delete tenderComm.detailRequired['doorPrice']
            tenderComm.showDoorPrice(0)
        } else {
            tenderComm.detailRequired['doorPrice'] = '门槛价'
            tenderComm.showDoorPrice(1)
        }
    },
    /**
     * 根据供应商编码和业务类型获取供应商邮箱
     * @param supplierCode 供应商编码
     */
    getSupplierEmail: function (supplier) {
        var loading = topWin.layer.msg('正在获取供应商邮箱数据，请稍后', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/supplier/contact/rest/getOne',
            method: "get",
            async: false,
            data: {supplierCode: supplier.supplierCode, type: 12},
            success: function (data) {
                supplier.contacts = data.contactsName + ":" + data.email;
                supplier.contactsId = data.id;
            },
            complete: function (data) {
                topWin.layer.close(loading);
            },
            error: function (data) {
                topWin.layer.alert(JSON.parse(data.responseText).message, {
                    icon: 2,
                    shadeClose: true,
                    title: '温馨提示'
                });
            }
        });
    },

    /**
     * 根据不同模板编码显示或隐藏询价类型下拉框
     * @param id
     */
    hiddenPurchaseRequestType: function(id) {
        const purchaseRequestTypeDiv = $(tenderComm.purchaseRequestTypeDiv);
        const purchaseRequestType = $(tenderComm.purchaseRequestType);
        const purchaseRequestTypeLabel = $(tenderComm.purchaseRequestTypeLabel);
        const purchaseRequestTypeNoLabel = $(tenderComm.purchaseRequestTypeNoLabel);
        if (type === 4) {
            purchaseRequestType.combobox("disable");
            return;
        }
        if (id === "412"){
            // MRO询价模板
            // 显示下拉框和标签
            purchaseRequestTypeDiv.removeAttr("hidden");
            purchaseRequestTypeLabel.removeAttr("hidden");
            purchaseRequestTypeNoLabel.attr("hidden", true);
            purchaseRequestType.combobox("enable");
        } else {
            // 隐藏下拉框和标签
            purchaseRequestTypeDiv.attr("hidden", true);
            purchaseRequestTypeLabel.attr("hidden", true);
            purchaseRequestTypeNoLabel.removeAttr("hidden");
            purchaseRequestType.combobox("disable");
        }
    },

    /**
     * 合同类型变更事件
     * @param data
     */
    purchaseRequestTypeChangeEvent: function(data) {
        if (tenderComm.editFristTime) {
            return
        }
        const grid = $('#project_table');
        if (data.code === '01' || data.code === '02') {
            // 费用类
            // 待询价物料明细将列采购数量”、“订单单位”移到最后；
            tenderComm.moveFieldsAfter('#project_table', [
                'count',
                'unit'
            ]);
            // 待询价物料明细新增列“采购申请编码“、”采购申请行号“
            // grid.edatagrid('showColumn', 'purchaseBillCode');
            // grid.edatagrid('showColumn', 'purchaseBillItemCode');
        } else {
            // 非费用类
            const templateId = $("#tender input[comboname='" + tenderComm.tenderFormPrefix + "templateId']").combobox('getValue');
            tenderComm.loadDetailField(templateId);
        }
    },

    /**
     * 将指定列移动到最列后
     * @param dgId 表格ID
     * @param fieldsToMove
     */
    moveFieldsAfter: function(dgId, fieldsToMove) {
        const opts = $(dgId).edatagrid('options');
        let cols = opts.columns[0];

        // 1. 先把这些字段从原位置删除
        let movingCols = [];
        fieldsToMove.forEach(f => {
            let idx = cols.findIndex(c => c.field === f);
            if (idx !== -1) {
                movingCols.push(cols.splice(idx, 1)[0]);
            }
        });

        // 最后一列
        let afterIndex = cols.length - 1;
        if (afterIndex === -1) return;

        // 3. 插入到指定列后面
        cols.splice(afterIndex + 1, 0, ...movingCols);

        const rows = tenderComm.projectDataGrid.datagrid("getRows")
        // 4. 重新设置
        $(dgId).edatagrid({
            columns: [cols]
        });
        tenderComm.projectDataGrid.edatagrid("loadData", rows);
    }
};
$.extend($.fn.validatebox.defaults.rules, {
    validReduction: {
        validator: function (value) {
            let rex = /^(\d+|(\d+)%|\d+\.\d+|\d+\.\d+%|\d+%|\d+)$/;
            if (rex.test(value)) {
                return true;
            } else {
                return false;
            }
        }, message: '请输入正确的降幅,数字或者百分比'
    }
})
