var el = {
    form : '#form',
    dataPanel: '#dataPanel',
    dataTabs: '#dataTabs',
    dataDiv: '#dataDiv',
    purchaseGroupCode: '#purchaseGroupCode',
    purchaseOrgCode: '#purchaseOrgCode',
    companyCode: '#companyCode',
    templateCode: '#templateCode',
    inquiryType: '#inquiryType',
    quoteModel: '#quoteModel',
    purchaseType: '#purchaseType',
    purchaseCategoryCode: '#purchaseCategoryCode',
    supplierMaterialFlag:"supplierMaterialFlag",
    spotFlag: '#spotFlag',
    businessAgreeFlag: '#businessAgreeFlag',
    customerBearFlag: '#customerBearFlag',
    bearRatio: '#bearRatio',
    updateDataDialog: '#updateDataDialog',
    materialCode: '#materialCode',
    quoteFromDate: '#quoteFromDate',
    quoteEndDate: '#quoteEndDate',
    confirmDeliveryDate: '#confirmDeliveryDate',
    mpq: '#mpq',
    moq: '#moq',
    stageQuoteData: {},
    costQuoteData: {},
    costQuoteMaterial: {},
    dateViewTotal: [],
    tableDom: '',
    tb: '#tb',
    supplierFileTb: '#supplierFileTb',
    approveTb: '#approveTb',
    id: '#id',
    bargainFiles: '#bargainFiles',
    bargainRemark: '#bargainRemark',
    editIndex: undefined,
    supplierEditIndex: undefined,
    assistant: undefined,
    supplierMaterialTb: '#supplierMaterialTb',
    selectRowIndexColor : {},
    bodyHeight: document.documentElement.clientHeight,
    defaultColumns: [],
}
$(function () {
    initDict('inquiry_type,currency,payment_way,payment_method');
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll,pc/sys/purchaseOrg/rest/listAll,pc/sys/company/rest/listAll,pc/sys/tax/rest/listAll,pc/inquiry/template/rest/listAll,pc/sys/purchaseCategory/rest/listAll');
    initCombo();
    $(el.dataPanel).panel({
        collapsible: true
    });
    $(el.dataTabs).tabs({
        border: false,
        onSelect: function (title) {
            if (title === '物料-供应商') {
                if (!lookFlag) {
                    layer.msg("已清空供应商物料选中数据");
                }
                //通过编码查询数据库列排序
                let column = getRemoteColumnSort(columnSortCodeEnum.FIX_DETAIL+$(el.templateCode).val(),el.defaultColumns);
                loadGrid(column);
            } else if (title === '供应商-物料') {
                if (!lookFlag) {
                    layer.msg("已清空物料供应商选中数据");
                }
                loadSupplierGrid();
            } else if (title === '供应商报价附件') {
                loadSupplierFileGrid();
            } else if (title === '确认记录') {
                loadApproveGrid();
            }
        }
    });
    //原始列
    initColumns();
    //通过编码查询数据库列排序
    let column = getRemoteColumnSort(columnSortCodeEnum.FIX_DETAIL+$(el.templateCode).val(),el.defaultColumns);
    loadGrid(column);
});

/**
 * 加载下拉框数据
 */
function initCombo() {
    //采购组
    $(el.purchaseGroupCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        data: getNecessaryDataList('pc/sys/purchaseGroup/rest/listAll'),
    });
    //采购组织
    $(el.purchaseOrgCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        data:getNecessaryDataList('pc/sys/purchaseOrg/rest/listAll'),
    });
    $(el.companyCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        data: getNecessaryDataList('pc/sys/company/rest/listAll')
    });

    $(el.templateCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        data: getNecessaryDataList('pc/inquiry/template/rest/listAll')
    });

    $(el.inquiryType).combobox({
        panelHeight: 'auto',
        limitToList: 'true',
        prompt: '-- 请选择 --',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        data: getDictList('inquiry_type')
    });

    //报价模式
    $(el.quoteModel).combobox({
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': '价格比较', 'code': 1},
            {'name': '竞价模式', 'code': 2}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });
    //采购类型
    $(el.purchaseType).combobox({
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': '标准', 'code': '0'},
            {'name': '寄售', 'code': '2'},
            {'name': '委外', 'code': '3'}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });

    //器件分类
    $(el.purchaseCategoryCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        data:getNecessaryDataList('pc/sys/purchaseCategory/rest/listAll'),
    });

    //供方描述
   $(el.supplierMaterialFlag).combobox({
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': '长描述', 'code': '0'},
            {'name': '短描述', 'code': '1'}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto'
    });

    //是否现货
    $(el.spotFlag).combobox({
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': '否', 'code': '0'},
            {'name': '是', 'code': '1'}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        onChange: function (data) {
            if (Number(data)===1){
                $(el.businessAgreeFlag).combobox({ disabled: false, required: true });
                $(el.customerBearFlag).combobox({ disabled: false, required: true });
                $(el.bearRatio).numberbox({ disabled: false, required: true });
            }else {
                $(el.businessAgreeFlag).combobox({ disabled: true, required: false });
                $(el.customerBearFlag).combobox({ disabled: true, required: false });
                $(el.bearRatio).numberbox({ disabled: true, required: false });
                $(el.bearRatio).numberbox('setValue', '');
            }
        }
    });

    //事业部是否同意
    $(el.businessAgreeFlag).combobox({
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': '否', 'code': '0'},
            {'name': '是', 'code': '1'}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto'
    });

    //客户是否承担
    $(el.customerBearFlag).combobox({
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': '否', 'code': '0'},
            {'name': '是', 'code': '1'}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });

}

function initColumns() {
    el.defaultColumns = [
        {
            field: 'bargainFlag',
            title: '报价状态',
            width: 90,
            exportEnum:[
                {code:1,codeWithDesc:'议价中'},
                {code:2,codeWithDesc:'已重新报价'},
                {code:0,codeWithDesc:'结束'},
            ],
            formatter: function (value, row, rec) {
                if (value === 1) {
                    return '<span style="color: red;">议价中</span>';
                } else if (value === 2) {
                    return '<span style="color: green;">已重新报价</span>';
                } else {
                    return '<span style="color: rebeccapurple;">结束</span>';
                }
            }
        },
        {
            field: 'taxCode',
            title: '税率',
            width: 80,
            exportEnum:getNecessaryDataList('pc/sys/tax/rest/listAll'),
            formatter: function (value) {
                return getNecessaryDataName('pc/sys/tax/rest/listAll',value);
            }
        },

        // {
        //     field: 'lastBidPrice',
        //     title: '原中标价格(未税)',
        //     width: 120 ,
        //     formatter:function (value) {
        //         return formatterPrice(value);
        //     }
        // },
        {
            field: 'historyPrice',
            title: '历史未税单价(CNY)',
            width: 120 ,
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'increasePrice',
            title: '涨降幅',
            width: 120,
            formatter: function (value, row, index) {
                if (value) {
                    if (value.indexOf("-")) {
                        return '<span style="color: red;">' + value + '%</span>';
                    } else {
                        return value+'%';
                    }
                }
                return value
            }
        },
        {
            field: 'paymentMethod',
            title: '付款条件',
            width: 80,
            exportEnum:getDictList('payment_method'),
            formatter: function (value) {
                return getDicName('payment_method',value);
            }
        },
        {
            field: 'bidFlag',
            title: '定价',
            width: 60,
            exportEnum:[
                {code:1,codeWithDesc:'是'},
                {code:0,codeWithDesc:'否'}
            ],
            formatter: function (value) {
                if (value === 1) {
                    return '<span style="color: red">是</span>'
                } else {
                    return '否';
                }
            }
        },
        {
            field: 'minPriceFlag',
            title: '是否最低价',
            width: 90,
            exportEnum:[
                {code:1,codeWithDesc:'是'},
                {code:0,codeWithDesc:'否'}
            ],
            formatter: function (value, row, index) {
                if(value===1){
                    return "<sapn style='color: red'>是</sapn>"
                }else{
                    return "<sapn>否</sapn>"
                }
            }
        },
        {
            field: 'taxPrice',
            title: '最终含税单价(原币)',
            width: 100,
            styler: function (value, row, index) {
                return 'background-color:#f4b084;';
            },
            formatter: function (value, row, index) {
                if (Number(row.costFlag) === 1) {
                    return '<a href="javascript:void(0);" style="color: blue;" onclick="costQuote('+index+')" data-index="' + index + '" data-value="' + row.taxfree_quote + '">' + formatterPrice(value) + '</a>';
                }
                return formatterPrice(value);
            }
        },
        {
            field: 'conversionPrice',
            title: '换算后未税单价(CNY)',
            width: 120,
            styler: function (value, row, index) {
                return 'background-color:#f4b084;';
            },
            formatter: function (value, row, index) {
                if (value) {
                    var values = formatterPrice(value)
                    return '<span style="color:blue;" title="'+values+'">' + values + '</span>';
                }
                // return formatterPrice(value);
            }
        },
        {
            field: 'firstTaxPrice',
            title: '最初含税单价(原币)',
            width: 100,
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'confirmQuota',
            title: '配额%',
            width: 80,
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    precision: 2
                }
            }
        },
        {
            field: 'confirmQuotaView',
            title: '配额%(参考)',
            width: 80
        },
        {
            field: 'purchaseNum',
            title: '采购数量',
            width: 80
        },
        {
            field: 'taxTotalPrice',
            title: '报价总金额(含税)',
            width: 125,
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        // {
        //     field: 'bidNumber',
        //     title: '定价数量',
        //     width: 80,
        //     editor: {
        //         type: 'numberbox',
        //         options: {
        //             min: 0,
        //             precision: 2
        //         }
        //     }
        // },
        // {
        //     field: 'bidTotalPrice',
        //     title: '定价总金额(含税)',
        //     width: 125,
        //     formatter:function (value) {
        //         return formatterPrice(value);
        //     }
        // },
        {
            field: 'noTaxPrice',
            title: '未税单价',
            width: 100,
            formatter: function (value, row, index) {
                return formatterPrice(value);
            }
        },
    ];
    var afterColumns = [
        {
            field: 'desirePrice',
            title: '期望含税单价(原币)',
            width: 80,
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    precision: priceHandle.precision
                }
            },
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'priceOpinion',
            title: '议价意见',
            width: 170,
            editor: {type: 'text'}
        },
        // {
        //     field: 'stagePriceFlag',
        //     title: '阶梯报价',
        //     width: 90,
        //     exportEnum:[
        //         {code:1,codeWithDesc:'是'},
        //         {code:0,codeWithDesc:'否'}
        //     ],
        //     formatter: function (value, row, index) {
        //         if (value === 1) {
        //             return '<a href="javascript:void(0);" style="color: blue;" onclick="stageQuote('+index+')">' + BJGL.BJGL__JTBJ + '</a>';
        //         } else {
        //             return '否';
        //         }
        //     }
        // },
        {
            field: 'stageNum1',
            title: '阶梯数量1',
            width: '120',
            align: 'left'
        },
        {
            field: 'stagePrice1',
            title: '阶梯报价1',
            width: '120',
            align: 'left',
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'stageNum2',
            title: '阶梯数量2',
            width: '120',
            align: 'left'
        },
        {
            field: 'stagePrice2',
            title: '阶梯报价2',
            width: '120',
            align: 'left',
            formatter:function (value) {
                return formatterPrice(value);
            }
        }, {
            field: 'stageNum3',
            title: '阶梯数量3',
            width: '120',
            align: 'left'
        },
        {
            field: 'stagePrice3',
            title: '阶梯报价3',
            width: '120',
            align: 'left',
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'stageNum4',
            title: '阶梯数量4',
            width: '120',
            align: 'left'
        },
        {
            field: 'stagePrice4',
            title: '阶梯报价4',
            width: '120',
            align: 'left',
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'stageNum5',
            title: '数量5',
            width: '120',
            align: 'left'
        },
        {
            field: 'stagePrice5',
            title: '阶梯报价5',
            width: '120',
            align: 'left',
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        // {
        //     field: 'quoteRemark',
        //     title: '报价说明',
        //     width: 80
        // },

        {
            field: 'quoteFromDate',
            title: '有效期起始日',
            exportDateFormatter: 'date',
            width: 120,
            formatter: function (value) {
                if (value) {
                    return moment(value).format("YYYY-MM-DD");
                }
                return '';
            }
        },
        {
            field: 'quoteEndDate',
            title: '有效期结束日',
            exportDateFormatter: 'date',
            width: 120,
            formatter: function (value) {
                if (value) {
                    return moment(value).format("YYYY-MM-DD");
                }
                return '';
            }
        },
        // {
        //     field: 'requireFiles',
        //     title: '需求附件',
        //     exportHidden: true,
        //     width: 120,
        //     formatter: function (value, row,rec) {
        //         if (value){
        //             value.split(',').length
        //             return '<a href="#" onclick="uploadFilesDialog(this)" data-index="' + rec + '" data-value="' + value + '">查看('+value.split(',').length+')个附件</a>';
        //         }else {
        //             return '无附件';
        //         }
        //     }
        // }
    ];
    loadFixTemplateFiled($(el.templateCode).val(), el.defaultColumns, afterColumns);
}

function loadGrid(columns) {
    let toolbar = [], dataFormHeight = $(el.dataForm).outerHeight() - 10;
    if (!lookFlag) {
        toolbar.push({
                text: '议价',
                iconCls: 'icon-ok',
                handler: function () {
                    bargain();
                }
            },
            "-", {
                text: '议价截止',
                iconCls: 'icon-delete',
                handler: function () {
                    bargainEnd();
                }
            },
            "-", {
                text: '标记最低价',
                iconCls: 'icon-tip',
                handler: function () {
                    selectLowestPrice();
                }
            },
            "-", {
                text: '比价小助手',
                iconCls: 'icon-search',
                handler: function () {
                    assistant();
                }
            },
            "-", {
                text: '数据补充',
                iconCls: 'icon-edit',
                handler: function () {
                    updateDataDialog();
                }
            },
            // "-", {
            //     text: '数据补充导出',
            //     iconCls: 'icon-undo',
            //     handler: function () {
            //         exportExcel();
            //     }
            // },
            "-", {
                text: '数据补充导入',
                iconCls: 'icon-import',
                handler: function () {
                    var importDialog = openQueryImportExcelDialog('pc/inquiry/fix/rest/material/supplier/data/export',{inquiryId:$(el.id).val(), bidFlag:optType===4?1:''},'数据补充导入',function(file){
                        let formData = new FormData();
                        formData.append("file", file);
                        var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                        $.ajax({
                            url: g.ctx + 'pc/inquiry/fix/rest/material/supplier/data/import',
                            method: "POST",
                            data: formData,
                            contentType: false,
                            processData: false,
                            success: function (data) {
                                topWin.layer.alert("导入成功", {icon: 1}, function (idx) {
                                    topWin.layer.close(idx);
                                    $(el.tb).datagrid('reload');
                                    importDialog.dialog('close');
                                });
                            },
                            complete: function(data) {
                                topWin.layer.close(loading);
                            },
                            error: function (data) {
                                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                            }
                        });
                    });
                }
            },
            "-",
            {
                text: '定价/议价导入',
                iconCls: 'icon-import',
                handler: function () {
                    var importDialog = openQueryImportExcelDialog('pc/inquiry/fix/rest/material/supplier/fix/export',{inquiryId:$(el.id).val(), bidFlag:optType===4?1:''},'数据补充导入',function(file){
                        let formData = new FormData();
                        formData.append("file", file);
                        var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                        $.ajax({
                            url: g.ctx + 'pc/inquiry/fix/rest/material/supplier/fix/import',
                            method: "POST",
                            data: formData,
                            contentType: false,
                            processData: false,
                            success: function (list) {
                                var rows = $(el.tb).datagrid("getRows");
                                $.each(rows, function (index, item) {
                                    $.each(list, function (dataIndex, data) {
                                        if (item.id === data.id){
                                            var rowIndex = $(el.tb).datagrid("getRowIndex", item);
                                            $(el.tb).datagrid("updateRow", {
                                                index: rowIndex,
                                                row: {
                                                    bidFlag: data.bidFlag&&data.bidFlag.toString() === '是'?1:0,
                                                    confirmQuota: data.confirmQuota,
                                                    confirmQuotaView: data.confirmQuota,
                                                    desirePrice: data.desirePrice,
                                                    priceOpinion: data.priceOpinion
                                                }
                                            });
                                            if (data.bidFlag&&data.bidFlag.toString() === '是'){
                                                $(el.tb).datagrid('selectRow', rowIndex);
                                            }
                                        }
                                    });
                                });
                                topWin.layer.alert("导入成功", {icon: 1}, function (idx) {
                                    topWin.layer.close(idx);
                                    importDialog.dialog('close');
                                });
                            },
                            complete: function(data) {
                                topWin.layer.close(loading);
                            },
                            error: function (data) {
                                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                            }
                        });
                    });
                }
            },
            "-",
            {
                text: '计算配额',
                iconCls: 'icon-coins',
                handler: function () {
                    calculateQuota();
                }
            },
            "-",
            {
                text: '导出',
                iconCls: 'icon-print',
                handler: function () {
                    openExportDialog('pc/inquiry/fix/rest/material/supplier/export','tb',{inquiryId:$(el.id).val(), bidFlag:optType===4?1:''});
                }
            }
            ,"-",
            {
                text: '列设置',
                iconCls: 'icon-anchor',
                id: 'btn_column_sort',
                handler: function () {
                    openSortDialog({
                        //唯一编码
                        code: columnSortCodeEnum.FIX_DETAIL+$(el.templateCode).val(),
                        //初始列（每次新增或删除列需要手动删除sys_column_sort表中对应code数据）
                        columns: el.defaultColumns,
                        callBack : function (newColumns) {
                            loadGrid(newColumns);
                        },
                    });
                }
            }
            ,"-",
            {
                text: '查询选中',
                iconCls: 'icon-ok',
                id: 'btn_column_sort',
                handler: function () {
                    topWin.layer.prompt({title: '请输入供应商编码', formType: 2, maxlength: 255}, function (text, index) {
                        text= text.replace(/(\r\n|\n|\r)/gm, " ")
                        var arr = text.split(' ');
                        var rows = $(el.tb).datagrid("getRows");
                        var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                        $.each(rows, function (idx, itm) {
                            let rowIndex = $(el.tb).datagrid("getRowIndex", itm)
                            $.each(arr, function (idx1, itm1) {
                                //如果供应商编码包含输入的itm1
                                if (itm1&&itm.supplierCode.indexOf(itm1) > -1) {
                                    $(el.tb).datagrid('selectRow', rowIndex);
                                }
                            })
                        })
                        topWin.layer.close(loading)
                        topWin.layer.close(index);
                    });

                }
            }
        );
    }else {
        toolbar.push(
            {
                text: '比价小助手',
                iconCls: 'icon-search',
                handler: function () {
                    assistant();
                }
            },"-",
            {
                text: '导出',
                iconCls: 'icon-import',
                handler: function () {
                    openExportDialog('pc/inquiry/fix/rest/material/supplier/export','tb',{inquiryId:$(el.id).val(), bidFlag:optType===4?1:''});
                }
            }
            ,"-",
            {
                text: '列设置',
                iconCls: 'icon-anchor',
                id: 'btn_column_sort',
                handler: function () {
                    openSortDialog({
                        //唯一编码
                        code: columnSortCodeEnum.FIX_DETAIL,
                        //初始列（每次新增或删除列需要手动删除sys_column_sort表中对应code数据）
                        columns: el.defaultColumns,
                        callBack : function (newColumns) {
                            loadGrid(newColumns);
                        },
                    });
                }
            }
        );
    }
    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/inquiry/fix/rest/material/supplier/list',
        singleSelect: false,
        height: '460px',
        width: '98%',
        pagination: false,
        autoRowHeight: false,
        remoteSort:false,
        fitColumns: false,
        checkbox: true,
        rownumbers: true,
        queryParams: {
            inquiryId:$(el.id).val(),
            // bidFlag:optType===4?1:''
        },
        frozenColumns: [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'materialCode',
                title: '物料编码',
                width: 110,
                formatter: function (value) {
                    if (value) {
                        return '<span style="color:blue;">' + value + '</span>';
                    }
                    return '';
                }
            },
            {
                field: 'materialName',
                title: '物料名称',
                width: 160,
                formatter: function (value) {
                    if (value) {
                        return '<span style="color:blue;" title="'+value+'">' + value + '</span>';
                    }
                    return '';
                }
            },
            // {
            //     field: 'productName',
            //     title: '品名',
            //     width: 100
            // },
            {
                field: 'materialSpec',
                title: '详细规格参数',
                width: 100
            },
            // {
            //     field: 'brand',
            //     title: '品牌',
            //     width: 100
            // },
            {
                field: 'supplierCode',
                title: '供应商编码',
                width: 110
            },
            {
                field: 'supplierShortName',
                title: '供应商简称',
                width: 110
            },
            {
                field: 'currencyCode',
                title: '币别',
                width: 80,
                exportEnum:getDictList('currency'),
                formatter: function (value) {
                    return getDicName('currency',value);
                }
            },
        ]],
        columns: [columns],
        toolbar: toolbar,
        onLoadSuccess: function (data) {
            //如果是大数据定价，不合并物料
            if (optType!==2){
                autoMergeCells();
            }
            var rows = data.rows;
            for (var j = 0; j < rows.length; j++) {
                rows[j].rowNum = j+1;
                if (rows[j].bidFlag === 1) {
                    $(el.tb).datagrid('selectRow', j);
                }
                //如果不参与报价，不允许点击
                // if (Number(rows[j].joinQuoteFlag)===0){
                //     $(".datagrid-row[datagrid-row-index=" + j + "] input[type='checkbox']")[0].disabled = true;
                // }
            }
            // bidTotalAll();
        },
        onClickRow: function (index, rowData) {
            //如果不参与报价，不允许点击
            // if (Number(rowData.joinQuoteFlag)===0){
            //     $(el.tb).datagrid('selectRow', index);
            // }
            if (!lookFlag){
                if (el.editIndex === undefined) {
                    $(el.tb).datagrid('beginEdit', index);
                    el.editIndex = index;
                } else {
                    endEditing();
                    $(el.tb).datagrid('beginEdit', index);
                    el.editIndex = index;
                }
            }
            // combboxBindEvent(index)
        },
    });
}

function loadSupplierGrid(){
    let toolbar = [];
    if (!lookFlag) {
        toolbar.push({
                text: '议价',
                iconCls: 'icon-ok',
                handler: function () {
                    bargain();
                }
            }
        );
    }

    var columns = [{
        field: 'bargainFlag',
        title: '报价状态',
        width: 90,
        formatter: function (value, row, rec) {
            if (value === 1) {
                return '<span style="color: red;">议价中</span>';
            } else if (value === 2) {
                return '<span style="color: green;">已重新报价</span>';
            } else {
                return '<span style="color: rebeccapurple;">结束</span>';
            }
        }
    },
        // {
        //     field: 'lastBidPrice',
        //     title: '原中标价格(未税)',
        //     width: 120 ,
        //     formatter:function (value) {
        //         return formatterPrice(value);
        //     }
        // },
        {
            field: 'historyPrice',
            title: '历史未税单价(CNY)',
            width: 120 ,
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'increasePrice',
            title: '涨降幅',
            width: 120,
            formatter: function (value, row, index) {
                if (value) {
                    if (value.indexOf("-")) {
                        return '<span style="color: red;">' + value + '%</span>';
                    } else {
                        return value+'%';
                    }
                }
                return value
            }
        },
        {
            field: 'noTaxPrice',
            title: '未税单价',
            width: 100,
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'conversionPrice',
            title: '换算后未税单价(CNY)',
            width: 120,
            styler: function (value, row, index) {
                return 'background-color:#f4b084;';
            },
            formatter:function (value) {
                if (value) {
                     var values = formatterPrice(value)
                    return '<span style="color:blue;" title="'+values+'">' + values + '</span>';
                }
                // return formatterPrice(value);
            }
        },
        {
            field: 'taxPrice',
            title: '最终含税单价(原币)',
            width: 100,
            styler: function (value, row, index) {
                return 'background-color:#f4b084;';
            },
            formatter: function (value, row, index) {
                if (Number(row.costFlag) === 1) {
                    return '<a href="javascript:void(0);" style="color: blue;" onclick="costQuote('+index+')" data-index="' + index + '" data-value="' + row.taxfree_quote + '">' + formatterPrice(value) + '</a>';
                }
                return formatterPrice(value);
            }
        },
        {
            field: 'firstTaxPrice',
            title: '最初报价(含税)',
            width: 100,
            formatter:function (value) {
                return formatterPrice(value);
            }
        },];
    var afterColumns = [

        {
            field: 'desirePrice',
            title: '期望含税单价(原币)',
            width: 80,
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    precision: precision
                }
            },
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'priceOpinion',
            title: '议价意见',
            width: 170,
            editor: {type: 'text'}
        },
        // {
        //     field: 'stagePriceFlag',
        //     title: '阶梯报价',
        //     width: 90,
        //     formatter: function (value, row, index) {
        //         if (value === 1) {
        //             return '<a href="javascript:void(0);" style="color: blue;" onclick="stageQuote('+index+')">' + BJGL.BJGL__JTBJ + '</a>';
        //         } else {
        //             return '否';
        //         }
        //     }
        // },
        {
            field: 'stageNum1',
            title: '阶梯数量1',
            width: '120',
            align: 'left'
        },
        {
            field: 'stagePrice1',
            title: '阶梯报价1',
            width: '120',
            align: 'left',
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'stageNum2',
            title: '阶梯数量2',
            width: '120',
            align: 'left'
        },
        {
            field: 'stagePrice2',
            title: '阶梯报价2',
            width: '120',
            align: 'left',
            formatter:function (value) {
                return formatterPrice(value);
            }
        }, {
            field: 'stageNum3',
            title: '阶梯数量3',
            width: '120',
            align: 'left'
        },
        {
            field: 'stagePrice3',
            title: '阶梯报价3',
            width: '120',
            align: 'left',
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'stageNum4',
            title: '阶梯数量4',
            width: '120',
            align: 'left'
        },
        {
            field: 'stagePrice4',
            title: '阶梯报价4',
            width: '120',
            align: 'left',
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'stageNum5',
            title: '数量5',
            width: '120',
            align: 'left'
        },
        {
            field: 'stagePrice5',
            title: '阶梯报价5',
            width: '120',
            align: 'left',
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'bidFlag',
            title: '定价',
            width: 60,
            formatter: function (value) {
                if (value === 1) {
                    return '<span style="color: red">是</span>'
                } else {
                    return '否';
                }
            }
        },
        {
            field: 'minPriceFlag',
            title: '是否最低价',
            width: 90,
            formatter: function (value, row, index) {
                if(value===1){
                    return "<sapn style='color: red'>是</sapn>"
                }else{
                    return "<sapn>否</sapn>"
                }
            }
        },
        {
            field: 'confirmQuota',
            title: '配额%',
            width: 80,
            editor: {
                type: 'numberbox',
                options: {
                    min: 0,
                    precision: 2
                }
            }
        },
        {
            field: 'confirmQuotaView',
            title: '配额%(参考)',
            width: 80
        },
        {
            field: 'purchaseNum',
            title: '采购数量',
            width: 80
        },
        {
            field: 'taxTotalPrice',
            title: '报价总金额(含税)',
            width: 125,
            formatter:function (value) {
                return formatterPrice(value);
            }
        },
        // {
        //     field: 'bidNumber',
        //     title: '定价数量',
        //     width: 80,
        //     editor: {
        //         type: 'numberbox',
        //         options: {
        //             min: 0,
        //             precision: 2
        //         }
        //     }
        // },
        // {
        //     field: 'bidTotalPrice',
        //     title: '定价总金额(含税)',
        //     width: 125,
        //     formatter:function (value) {
        //         return formatterPrice(value);
        //     }
        // },

        // {
        //     field: 'quoteRemark',
        //     title: '报价说明',
        //     width: 80
        // },
        {
            field: 'quoteFromDate',
            title: '有效期起始日',
            width: 120,
        },
        {
            field: 'quoteEndDate',
            title: '有效期结束日',
            width: 120,
        },
    ];
    loadFixTemplateFiled($(el.templateCode).val(), columns, afterColumns);
    $(el.supplierMaterialTb).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/inquiry/material/supplier/rest/getGroupListByInquiryId',
        singleSelect: false,
        height: '460px',
        width: '98%',
        pagination: false,
        autoRowHeight: false,
        fitColumns: true,
        queryParams: {
            inquiryId:$(el.id).val(),
            bidFlag:optType===4?1:''
        },
        columns: [[
            {
                field: 'supplierCode',
                title: '供应商编码',
                width: 80
            },
            {
                field: 'supplierShortName',
                title: '供应商简称',
                width: 150
            },
            {
                field: 'currencyCode',
                title: '币种',
                width: 100,
                align: 'left',
                formatter: function (value, row) {
                    console.log(value)
                    return getDicName('currency',value);
                }
            },
            {
                field: 'taxCode',
                title: '税率',
                width: 100,
                align: 'center',
                formatter: function (value) {
                    return getNecessaryDataName('pc/sys/tax/rest/listAll',value);
                }
            },
            {
                field: 'paymentMethod',
                title: '付款条件',
                width: 80,
                align: 'center',
                formatter: function (value) {
                    return getDicName('payment_method',value);
                }
            },
            {
                field: 'purchaseCategoryName',
                title: '采购品类',
                width: 80,
            },
            {
                field: 'companyCode',
                title: '公司',
                width: 150,
                formatter: function (value) {
                    return getNecessaryDataName('pc/sys/company/rest/listAll',value);
                }
            },
            {
                field: 'materialTaxTotalPrice',
                title: '报价金额合计',
                width: 80,
                formatter:function (value) {
                    return formatterPrice(value);
                }
            }
        ]],
        view: detailview,
        toolbar: toolbar,
        detailFormatter: function (index) {
            return '<div id="ddv-' + index + '" style="padding: 5px;"></div>';
        },
        onExpandRow: function (index, row) {
            el.dateViewTotal.push(index);
            detail(index, row,columns);
        },
        onCollapseRow: function (indexDetail, row) {
            let index = el.dateViewTotal.indexOf(indexDetail);
            el.dateViewTotal.splice(index, 1);
            supplierEndEditor();
        }
    });
}

function detail(index, row,columns) {
    $('#ddv-' + index).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/inquiry/fix/rest/material/supplier/list',
        singleSelect: false,
        height: 'auto',
        pagination: false,
        rownumbers: true,
        width: screenWidth - 70,
        page: 1,
        pageSize: 1000,
        queryParams: {
            inquiryId: $(el.id).val(),
            supplierId: row.supplierId,
            bidFlag:optType===4?1:''
        },
        frozenColumns: [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'materialCode',
                title: '物料编码',
                width: 110,
                formatter: function (value) {
                    if (value) {
                        return '<span style="color:blue;">' + value + '</span>';
                    }
                    return '';
                }
            },
            {
                field: 'materialName',
                title: '物料名称',
                width: 160,
                formatter: function (value) {
                    if (value) {
                        return '<span style="color:blue;">' + value + '</span>';
                    }
                    return '';
                }
            },
            // {
            //     field: 'productName',
            //     title: '品名',
            //     width: 100
            // },
            {
                field: 'materialSpec',
                title: '规格',
                width: 100
            },
            {
                field: 'brand',
                title: '品牌',
                width: 100
            }
        ]],
        columns: [columns],
        onLoadSuccess: function (data) {
            $(el.supplierMaterialTb).datagrid('fixDetailRowHeight', index);
            var rows = data.rows;
            for (var j = 0; j < rows.length; j++) {
                rows[j].rowNum = j+1;
                if (rows[j].bidFlag === 1) {
                    $('#ddv-' + index).datagrid('selectRow', j);
                }
                //如果不参与报价，不允许点击
                // if (Number(rows[j].joinQuoteFlag)===0){
                //     $(".datagrid-view"+index+" .datagrid-row[datagrid-row-index=" + j + "] input[type='checkbox']")[0].disabled = true;
                // }
            }
        },
        onClickRow: function (detailIndex, rowData) {
            //如果不参与报价，不允许点击
            // if (Number(rowData.joinQuoteFlag)===0){
            //     $('#ddv-' + index).datagrid('selectRow', index);
            // }
            if (el.supplierEditIndex === undefined) {
                el.tableDom = '#ddv-' + index;
                $(el.tableDom).datagrid('beginEdit', detailIndex);
                el.supplierEditIndex = detailIndex;
            } else {
                supplierEndEditor();
                el.tableDom = '#ddv-' + index;
                $(el.tableDom).datagrid('beginEdit', detailIndex);
                el.supplierEditIndex = detailIndex;
            }
        },
        onResize: function () {
            $(el.supplierMaterialTb).datagrid('fixDetailRowHeight', index);
        },
        onCheck: function (rowIndex, rowData) {
            $(el.tb).datagrid('unselectAll');
        },
        onCheckAll: function (rows) {
            $(el.tb).datagrid('unselectAll');
        }
    });
}

function supplierEndEditor() {
    if (el.supplierEditIndex === undefined) {
        return true
    }
    $(el.tableDom).datagrid('endEdit', el.supplierEditIndex);
    el.supplierEditIndex = undefined;
    return true;
}

/**
 * 供应商报价附件
 */
function loadSupplierFileGrid(){
    $(el.supplierFileTb).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/inquiry/fix/rest/supplier/file/list?inquiryId=' + $(el.id).val(),
        height: '460px',
        width: '98%',
        pagination: false,
        autoRowHeight: false,
        remoteSort:false,
        fitColumns: true,
        checkbox: true,
        rownumbers: false,
        queryParams: {},
        columns: [[
            {
                field: 'supplierCode',
                title: '供应商编号',
                width: 140
            }, {
                field: 'supplierShortName',
                title: '供应商简称',
                width: 250
            }, {
                field: 'supplierFormFiles',
                title: '文件',
                width: 410,
                formatter: function (value, row, index) {
                    return '<div class="supplier-file-form custom-file-form-style" data-options=\'{"deleteEnable":false, "previewEnable":true, "uploadEnable": false, "moreFileUploadEnable": true, "fileSize": 50, "fileTypes": ".xls,.doc,.txt,.pdf"}\' data-fileIds = "'+value+'"></div>';
                }
            }, {
                field: 'supplierFormRemark',
                title: '供应商备注',
                width: 410
            }
        ]],
        toolbar:[{
            text: "一键下载",
            iconCls: 'icon-remove',
            handler: function () {
                let rows = $(el.supplierFileTb).datagrid("getRows");
                var fileIdsArr = [];
                $.each(rows, function (idx, itm) {
                    var files = itm.supplierFormFiles;
                    fileIdsArr.push(files)
                });
                batchDownload(fileIdsArr.join(','))
            }
        }],
        onLoadSuccess: function (data) {
            initFileForm('supplier-file-form');
        },
    });
}

/**
 * 初始化审批信息表格
 */
function loadApproveGrid() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;

    $(el.approveTb).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'pc/inquiry/approve/rest/list',
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: true,
        queryParams: {
            inquiryId: $(el.id).val()
        },
        columns: [
            [
                {
                    field: 'approveNode',
                    title: '审批节点描述',
                    width: 120,
                    formatter: function (value) {
                        if(Number(value) === 1){
                            return '主管确认';
                        }else {
                            return '价格确认';
                        }
                    }
                },
                {
                    field: 'approveResult',
                    title: '审批结果',
                    width: 120,
                    formatter: function (value) {
                        switch (Number(value)){
                            case 0:
                                return '<span style="color: red;">拒绝</span>';
                            case 1:
                                return '<span style="color: green;">同意</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'approveOpinion',
                    title: '审批意见',
                    width: 300
                },
                {
                    field: 'approveUserName',
                    title: '审批用户姓名',
                    width: 130
                },
                {
                    field: 'approveTime',
                    title: '审批时间',
                    width: 140,
                    sortable: true,
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format("YYYY-MM-DD HH:mm:ss");
                        }
                        return '';
                    }
                }
            ]
        ]
    });
}
/**
 * 议价
 */
function bargain(){
    endEditing();
    supplierEndEditor();
    let rows = $(el.tb).datagrid('getSelections');
    if (rows.length === 0) {
        for (let i = 0; i < el.dateViewTotal.length; i++) {
            let tbDom = '#ddv-' + el.dateViewTotal[i];
            let selectRows = $(tbDom).datagrid('getSelections');
            if (selectRows.length > 0) {
                rows.push.apply(rows, selectRows);
            }
        }
    }
    if (rows.length === 0) {
        topWin.layer.msg('请选取一条记录进行操作', {icon: 0});
        return false;
    }
    var formData = {};
    formData.inquiryId = $(el.id).val();
    formData.bargainFiles = $(el.bargainFiles).attr('data-fileIds');
    formData.bargainRemark = $(el.bargainRemark).val();
    formData.inquiryMaterialSupplierList = rows;
    parent.layer.confirm('是否确认议价？', function (index) {
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/inquiry/fix/rest/bargain',
            method: "post",
            data: JSON.stringify(formData),
            contentType: 'application/json',
            success: function () {
                parent.layer.close(index);
                top.layer.close(loading);
                topWin.layer.msg('议价成功', {icon: 1});
                let parentPage = topWin.window.frames[g.ctx + 'pc/inquiry/fix/index'];
                parentPage.window.closeFixPriceDialog();
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                top.layer.close(loading);
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}
/**
 * 议价截止
 */
function bargainEnd(){
    endEditing();
    supplierEndEditor();
    let rows = $(el.tb).datagrid('getSelections');
    if (rows.length === 0) {
        for (let i = 0; i < el.dateViewTotal.length; i++) {
            let tbDom = '#ddv-' + el.dateViewTotal[i];
            let selectRows = $(tbDom).datagrid('getSelections');
            if (selectRows.length > 0) {
                rows.push.apply(rows, selectRows);
            }
        }
    }
    if (rows.length === 0) {
        topWin.layer.msg('请选取一条记录进行操作', {icon: 0});
        return false;
    }
    var formData = {};
    formData.inquiryId = $(el.id).val();
    formData.bargainFiles = $(el.bargainFiles).attr('data-fileIds');
    formData.bargainRemark = $(el.bargainRemark).val();
    formData.inquiryMaterialSupplierList = rows;
    parent.layer.confirm('是否确认议价截止？', function (index) {
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/inquiry/fix/rest/bargain/end',
            method: "post",
            data: JSON.stringify(formData),
            contentType: 'application/json',
            success: function () {
                parent.layer.close(index);
                top.layer.close(loading);
                topWin.layer.msg('议价截止成功', {icon: 1});
                let parentPage = topWin.window.frames[g.ctx + 'pc/inquiry/fix/index'];
                parentPage.window.closeFixPriceDialog();
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                top.layer.close(loading);
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}
//标记最低价
function selectLowestPrice() {
    let rows = $(el.tb).datagrid('getRows');
    for (let i = 0; i < rows.length; i++) {
        if (rows[i].minPriceFlag === 1) {
            $(el.tb).datagrid('selectRow', i);
        }
    }
}

function assistant() {
    let url = g.ctx + 'pc/inquiry/fix/assistant?inquiryId=' + $(el.id).val();
    el.assistant = openDialog('assistant', url, {
        title: '比价小助手',
        width: '98%',
        height: '98%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.assistant.dialog('destroy');
        },
        buttons: [
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.assistant.dialog('close');
                }
            }
        ]
    });
}

/**
 * 数据补充弹窗
 */
function updateDataDialog() {
    var row = $(el.tb).datagrid('getSelected');
    if (null == row) {
        layer.msg('请选中一条记录', {icon: 0});
        return;
    }
    $(el.materialCode).textbox('setValue', row.materialCode);
    $(el.quoteFromDate).datebox('setValue', row.quoteFromDate);
    $(el.quoteEndDate).datebox('setValue', row.quoteEndDate);
    $(el.confirmDeliveryDate).numberbox('setValue', row.confirmDeliveryDate);
    $(el.mpq).numberbox('setValue', row.mpq);
    $(el.moq).numberbox('setValue', row.moq);
    $(el.updateDataDialog).dialog('open');
}

/**
 * 数据补充弹窗确认
 */
function confirmUpdateData() {
    var row = $(el.tb).datagrid('getSelected');
    var materialCode = $(el.materialCode).textbox('getValue');
    if (!materialCode) {
        layer.msg('请输入物料编码', {icon: 0});
        return;
    }
    var quoteFromDate = $(el.quoteFromDate).textbox('getValue');
    if (!quoteFromDate) {
        layer.msg('请输入有效期起始日', {icon: 0});
        return;
    }
    var quoteEndDate = $(el.quoteEndDate).textbox('getValue');
    if (!quoteEndDate) {
        layer.msg('请输入有效期结束日', {icon: 0});
        return;
    }
    if (quoteFromDate > quoteEndDate) {
        layer.msg("有效起始日必须小于有效结束日");
        return;
    }
    //判断有效期结束日和有效期起始日是否大于一年
    if (moment(quoteEndDate).diff(moment(quoteFromDate), 'years', true)>1) {
        layer.msg("有效期结束日和有效期起始日不能大于一年");
        return;
    }
    var confirmDeliveryDate = $(el.confirmDeliveryDate).textbox('getValue');
    if (!confirmDeliveryDate) {
        layer.msg('请输入货期(天)', {icon: 0});
        return;
    }
    var numValue = parseInt(confirmDeliveryDate, 10) || 0; // 转换失败时设为0
    if (numValue > 999) {
        layer.msg("货期不能超过999");
        return;
    }

    var mpq = $(el.mpq).textbox('getValue');
    if (!mpq) {
        layer.msg('请输入最小包装量', {icon: 0});
        return;
    }
    var moq = $(el.moq).textbox('getValue');
    if (!moq) {
        layer.msg('请输入最小订货量', {icon: 0});
        return;
    }
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/inquiry/fix/rest/updateMaterialAndSupplierData',
        method: 'post',
        data: {
            inquiryMaterialId: row.inquiryMaterialId,
            inquiryMaterialSupplierId: row.id,
            materialCode: materialCode,
            quoteFromDate: quoteFromDate,
            quoteEndDate: quoteEndDate,
            confirmDeliveryDate: confirmDeliveryDate,
            mpq: mpq,
            moq: moq,
            supplierCode: row.supplierCode,
        },
        success: function (data) {
            topWin.layer.msg('数据保存成功', {icon: 1});
            $(el.updateDataDialog).dialog('close');
            $(el.tb).datagrid('reload');
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}

/**
 * 关闭数据补充弹框
 */
function closeUpdateDataDialog() {
    $(el.updateDataDialog).dialog('close');
}

/**
 * 自动合并单元格
 */
function autoMergeCells() {
    let judge = 'materialName';
    // field_arr 需要合并的列
    let field_arr = ['materialName', 'materialCode', 'productName','materialSpec', 'materialModel', 'brand'];

    let rows = $(el.tb).datagrid('getRows');
    if (!rows) {
        return;
    }
    for (let i = 1; i < rows.length; i++) {
        for (let k = 0; k < field_arr.length; k++) {
            // 要排序的字段
            let field = field_arr[k];
            // 相邻的上下两行
            if (rows[i][field] === rows[i - 1][field]) {
                if (judge) {
                    if (rows[i][judge]+rows[i].materiainfo_id !== rows[i - 1][judge]+rows[i -1].materiainfo_id) {
                        continue;
                    }
                }
                let rowSpan = 2;
                // 判断上下多行内容一样
                for (let j = 2; i - j >= 0; j++) {
                    if (rows[i][field] !=undefined && rows[i][field]+rows[i].materiainfo_id !== rows[i - j][field] + rows[i - j].materiainfo_id) {
                        break;
                    } else {
                        if (judge) {
                            if (rows[i][judge] !== rows[i - j][judge]) {
                                break;
                            }
                        }
                        rowSpan = j + 1;
                    }
                }
                // 合并
                $(el.tb).datagrid('mergeCells', {
                    index: i - rowSpan + 1,
                    field: field,
                    rowspan: rowSpan
                });

            }
        }
    }
}

function beginEditing(rowIndex) {
    if (rowIndex !== el.editIndex) {
        if (endEditing()) {
            $(el.tb).datagrid('beginEdit', rowIndex);
            el.editIndex = rowIndex;
        } else {
            $(el.tb).datagrid('selectRow', el.editIndex);
        }
    }
}

/**
 * 成本报价
 */
function costQuote(index){
    var row = $(el.tb).datagrid('getRows')[index];
    // 当前成本报价的物料信息
    el.costQuoteMaterial.materialCode = row.materialCode;
    el.costQuoteMaterial.materialName = row.materialName;
    el.costQuoteMaterial.taxTotalPrice = row.taxPrice;
    var costQuoteDialog = openDialog('costQuoteDialog', g.ctx + "pc/inquiry/supplier/cost/quote/detail/dialog?inquiryMaterialSupplierId="+row.id+"&lookFlag=1&parentFrameName=fixPriceDialog"+"&costTemplateCode="+row.costTemplateCode+"&inquiryMaterialId="+row.inquiryMaterialId, {
        title: BJGL.BJGL__CBBJ,
        width: '900px',
        height: '70%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            costQuoteDialog.dialog('destroy');
        },
        buttons: [
            {
                text: BJGL.BJGL__GB,
                iconCls: 'icon-cancel',
                handler: function () {
                    costQuoteDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 阶梯报价
 */
function stageQuote(index){
    var row = $(el.tb).datagrid('getRows')[index];
    el.stageQuoteData[row.id] = row;
    var stageQuoteDialog = openDialog('stageQuoteDialog', g.ctx + "pc/inquiry/supplier/quote/stage/quote/dialog?templateCode="+$(el.templateCode).val()+"&lookFlag=1&parentFrameName=fixPriceDialog&inquiryMaterialSupplierId="+row.id, {
        title: BJGL.BJGL__JTBJ,
        width: '900px',
        height: '70%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            stageQuoteDialog.dialog('destroy');
        },
        buttons: [
            {
                text: BJGL.BJGL__GB,
                iconCls: 'icon-cancel',
                handler: function () {
                    stageQuoteDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 获取成本报价数据
 *
 * @param inquiryMaterialSupplierId 报价记录的ID
 * @returns {object} 结果
 */
function getCostQuoteData(inquiryMaterialSupplierId) {
    var obj = {};
    obj.material = el.costQuoteMaterial;
    obj.data = [];
    if (el.costQuoteData[inquiryMaterialSupplierId] !== undefined && el.costQuoteData[inquiryMaterialSupplierId].length !== 0) {
        obj.data = el.costQuoteData[inquiryMaterialSupplierId];
    }
    return obj;
}

/**
 * 获取阶梯报价数据
 *
 * @param inquiryMaterialSupplierId 供应商报价记录ID
 * @returns {*} 结果
 */
function getStageQuoteData(inquiryMaterialSupplierId) {
    return el.stageQuoteData[inquiryMaterialSupplierId];
}

function endEditing() {
    if (el.editIndex === undefined) {
        return true
    }
    if ($(el.tb).datagrid('validateRow', el.editIndex)) {
        $(el.tb).datagrid('endEdit', el.editIndex);
        autoMergeCells();
        el.editIndex = undefined;
        bidTotalAll();
        let rows = $(el.tb).datagrid('getRows');
        for (var j = 0; j < rows.length; j++) {
            rows[j].rowNum = j+1;
            //如果不参与报价，不允许点击
            // if (Number(rows[j].joinQuoteFlag)===0){
            //     $(".datagrid-row[datagrid-row-index=" + j + "] input[type='checkbox']")[0].disabled = true;
            // }
        }
        return true;
    } else {
        autoMergeCells();
        return false;
    }
}

function bidTotalAll() {
    // var rows = $(el.tb).datagrid("getSelections");
    // var sum = 0;
    // for (var i = 0; i < rows.length; i++) {
    //     if(rows[i].bid_total){
    //         sum = accAdd(sum, rows[i].bid_total);
    //     }
    // }
    // if (rows.length === 0) {
    //     for (let i = 0; i < el.dateViewTotal.length; i++) {
    //         let tbDom = '#ddv-' + el.dateViewTotal[i];
    //         let selectRows = $(tbDom).datagrid('getSelections');
    //         for (var j = 0; j < selectRows.length; j++) {
    //             if(selectRows[j].bid_total){
    //                 sum = accAdd(sum, selectRows[j].bid_total);
    //             }
    //         }
    //
    //     }
    // }
    // $(el.bidTotalAll).val(sum);

}

/**
 * 定价
 * @param call 回调
 * @param optType 定价类型；0-暂存；1-提交
 * @returns {boolean}
 */
function fixPrice(call,optType){
    endEditing();
    supplierEndEditor();
    if (!$(el.form).form('validate')){
        return false;
    }
    let rows = $(el.tb).datagrid('getSelections');
    if (rows.length === 0) {
        for (let i = 0; i < el.dateViewTotal.length; i++) {
            let tbDom = '#ddv-' + el.dateViewTotal[i];
            let selectRows = $(tbDom).datagrid('getSelections');
            if (selectRows.length > 0) {
                rows.push.apply(rows, selectRows);
            }
        }
    }
    if (rows.length === 0) {
        topWin.layer.msg('请选取一条记录进行操作', {icon: 0});
        return false;
    }
    var isNoJoin = false;
    let materialList = [];
    for (let m = 0; m < rows.length; m++) {

        let item = rows[m];
        var rowNumber = item.rowNum;
        if (Number(item.joinQuoteFlag)===1){
            isNoJoin = true;
        }
        if (!item.taxPrice) {
            layer.confirm('物料: (' + (item.materialCode?item.materialCode:item.materialName) + ') 选中供方：('+item.supplierShortName+')未报价,不允许定价,请取消勾选!', {icon: 2, title: '温馨提示'});
            return false;
        }
        // if (Number(item.purchaseNum) < Number(item.bidNumber)) {
        //     layer.confirm('物料: (' + (item.materialCode?item.materialCode:item.materialName) + ') 选中供方：('+item.supplierShortName+')定价数量大于采购数量,不允许定价!', {icon: 2, title: '温馨提示'});
        //     return false;
        // }
        if (item.confirmQuota === false || item.confirmQuota == null) {
            layer.confirm('物料: (' + (item.materialCode?item.materialCode:item.materialName) + ') 选中供方：('+item.supplierShortName+')未填写配额,不允许定价!', {icon: 2, title: '温馨提示'});
            return false;
        }

        // if (!item.materialCode) {
        //     layer.confirm('物料: (' + item.materialName + ') 未补充料号,不允许定价!', {icon: 2, title: '温馨提示'});
        //     return false;
        // }
        materialList.push({
            materialName: item.materialName,
            inquiryMaterialId: item.inquiryMaterialId,
            materialCode: item.materialCode
        });
    }
    if (!isNoJoin){
        layer.confirm('请至少选择一个中标供应商', {icon: 2, title: '温馨提示'});
        return false;
    }

    //根据物料编码去重
    var obj = {};
    materialList = materialList.reduce(function(item, next) {
        obj[next.inquiryMaterialId] ? '' : obj[next.inquiryMaterialId] = item.push(next);
        return item;
    }, []);
    //根据物料编码判断配额是否为100%
    for (let m = 0; m < materialList.length; m++) {
        let item = materialList[m];
        let totalQuota = 0;
        for (let mm = 0; mm < rows.length; mm++) {
            let item1 = rows[mm];
            if (item1.inquiryMaterialId===item.inquiryMaterialId){
                totalQuota+=Number(item1.confirmQuota);
            }
        }
        console.log(totalQuota)
        if (totalQuota!==100&&totalQuota!==0){
            debugger
            layer.confirm('物料: (' + (item.materialCode?item.materialCode:item.materialName) + ') 配额合计不为100或0,不允许定价,请取消勾选!', {icon: 2, title: '温馨提示'});
            return false;
        }
    }

    var formData = {};
    formData.inquiryId = $(el.id).val();
    formData.optType = optType;
    formData.purchaseCategoryCode = $(el.purchaseCategoryCode).combobox('getValue');
    formData.spotFlag = $(el.spotFlag).combobox('getValue');
    formData.businessAgreeFlag = $(el.businessAgreeFlag).combobox('getValue');
    formData.customerBearFlag = $(el.customerBearFlag).combobox('getValue');
    formData.bearRatio = $(el.bearRatio).numberbox('getValue');
    formData.bargainRemark = $(el.bargainRemark).val();
    formData.bargainRemark = $(el.bargainRemark).val();
    formData.bargainFiles = $(el.bargainFiles).attr('data-fileIds');
    formData.bargainRemark = $(el.bargainRemark).val();
    formData.inquiryMaterialSupplierList = rows;

    //根据物料编码判断是否选择中标供应商
    for (let m = 0; m < materialList.length; m++) {
        let item = materialList[m];
        var su = false;
        var materialSu = false;
        for (let mm = 0; mm < rows.length; mm++) {
            let item1 = rows[mm];
            if (!item1.materialCode){
                materialSu = true;
                break;
            }
            if (item1.inquiryMaterialId===item.inquiryMaterialId){
                su = true;
                break;
            }
        }
        if (materialSu){
            layer.confirm('物料: (' + item.materialName + ') 未补充物料编码,将不会传入OA且不生成价格信息记录,是否继续定价？', {
                btn: ['确定','取消'] //按钮
            }, function(){
                layer.closeAll()
                fixPriceAjax(call,formData)
                return false;
            }, function(){
                return false;
            });
        }else {
            if (!su){
                layer.confirm('物料: (' + (item.materialCode?item.materialCode:item.materialName) + ') 未选择中标供应商,是否继续定价？', {
                    btn: ['确定','取消'] //按钮
                }, function(){
                    layer.closeAll()
                    fixPriceAjax(call,formData)
                    return false;
                }, function(){
                    return false;
                });
            }else {
                fixPriceAjax(call,formData)
                return false;
            }
        }
    }

}

function fixPriceAjax(call,formData){
    parent.layer.confirm('是否确认定价？', function (index) {
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/inquiry/fix/rest/fixPrice',
            method: "post",
            data: JSON.stringify(formData),
            contentType: 'application/json',
            success: function () {
                parent.layer.close(index);
                top.layer.close(loading);
                call();
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                top.layer.close(loading);
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}

function calculateQuota(){
    endEditing();
    supplierEndEditor();
    let rows = $(el.tb).datagrid('getSelections');
    if (rows.length === 0) {
        for (let i = 0; i < el.dateViewTotal.length; i++) {
            let tbDom = '#ddv-' + el.dateViewTotal[i];
            let selectRows = $(tbDom).datagrid('getSelections');
            if (selectRows.length > 0) {
                rows.push.apply(rows, selectRows);
            }
        }
    }
    if (rows.length === 0) {
        topWin.layer.msg('请选取一条记录进行操作', {icon: 0});
        return false;
    }
    var isNoJoin = false;
    for (let m = 0; m < rows.length; m++) {
        let item = rows[m];
        if (Number(item.joinQuoteFlag)===1){
            isNoJoin = true;
        }
        if (!item.taxPrice) {
            layer.confirm('物料: (' + item.materialName + ') 选中供方：('+item.supplierShortName+')未报价,不允许定价,请取消勾选!', {icon: 2, title: '温馨提示'});
            return false;
        }
        if (!item.materialCode) {
            layer.confirm('物料: (' + item.materialName + ') 未补充料号,无法计算配额!', {icon: 2, title: '温馨提示'});
            return false;
        }
    }
    if (!isNoJoin){
        layer.confirm('请至少选择一个中标供应商', {icon: 2, title: '温馨提示'});
        return false;
    }
    var formData = {};
    formData.inquiryId = $(el.id).val();
    formData.inquiryMaterialSupplierList = rows;
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/inquiry/fix/rest/calculateQuota',
        method: "post",
        data: JSON.stringify(formData),
        contentType: 'application/json',
        success: function () {
            top.layer.close(loading);
            $(el.tb).datagrid('reload');
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            top.layer.close(loading);
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}

/**
 * 定价确认
 * @param call 回调
 * @param optType 定价类型；1-通过；2-驳回
 * @returns {boolean}
 */
function fixConfirm(call,optType){
    var formData = {};
    formData.inquiryId = $(el.id).val();
    formData.optType = optType;
    formData.bargainRemark = $(el.bargainRemark).val();
    topWin.layer.prompt({title: '请输入审核意见', formType: 2, maxlength: 255,value:optType===1?'同意':''}, function (text, index) {
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        formData.optRemark = text;
        $.ajax({
            url: g.ctx + 'pc/inquiry/fix/rest/fixConfirm',
            method: "post",
            data: JSON.stringify(formData),
            contentType: 'application/json',
            success: function () {
                parent.layer.close(index);
                top.layer.close(loading);
                call();
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                top.layer.close(loading);
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
    // parent.layer.confirm(optType===1?'是否确认通过？':'是否确认驳回？', function (index) {
    //
    // });
}


/**
 * 主管确认
 * @param call 回调
 * @param optType 定价类型；1-通过；2-驳回
 * @returns {boolean}
 */
function chargeConfirm(call,optType){
    endEditing();
    supplierEndEditor();
    if (!$(el.form).form('validate')){
        return false;
    }
    let rows = $(el.tb).datagrid('getSelections');
    if (rows.length === 0) {
        for (let i = 0; i < el.dateViewTotal.length; i++) {
            let tbDom = '#ddv-' + el.dateViewTotal[i];
            let selectRows = $(tbDom).datagrid('getSelections');
            if (selectRows.length > 0) {
                rows.push.apply(rows, selectRows);
            }
        }
    }
    if (rows.length === 0) {
        topWin.layer.msg('请选取一条记录进行操作', {icon: 0});
        return false;
    }
    var formData = {};
    formData.inquiryId = $(el.id).val();
    formData.optType = optType;
    formData.bargainRemark = $(el.bargainRemark).val();
    formData.inquiryMaterialSupplierList = rows;
    topWin.layer.prompt({title: '请输入审核意见', formType: 2, maxlength: 255,value:optType===1?'同意':''}, function (text, index) {
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        formData.optRemark = text;
        $.ajax({
            url: g.ctx + 'pc/inquiry/fix/rest/chargeConfirm',
            method: "post",
            data: JSON.stringify(formData),
            contentType: 'application/json',
            success: function () {
                parent.layer.close(index);
                top.layer.close(loading);
                call();
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                top.layer.close(loading);
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
    // parent.layer.confirm(optType===1?'是否确认通过？':'是否确认驳回？', function (index) {
    //
    // });
}

/**
 * 加载定价价模板设置字段
 *
 * @param templateCode 询价模板编码
 * @param fieldGroup 模板字段分组；0-基础字段；1-基础扩展；2-阶梯报价；3-自定义扩展字段
 * @param existColumns 固定列
 * @param afterColumns 追加列
 */
function loadFixTemplateFiled(templateCode,existColumns,afterColumns){
    var loading = top.layer.msg('加载中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/inquiry/template/rest/getFixFieldByTemplateCode',
        type: 'GET',
        data: {templateCode: templateCode},
        async: false,
        complete: function() {
            top.layer.close(loading);
        },
        success: function (data) {
            // console.log(data);
            if (data){
                // tmpData.templateFieldData = [];
                //先加载供应商可见但不可编辑的列
                for (let i = 0; i < data.length; i++) {
                    let item = data[i];
                    if (item.fixLookFlag===1){
                        if (item.fieldType === 'dict'){
                            initDict(item.dictTypeCode);
                        }
                        if (item.fieldType === 'data'){
                            initNecessaryDatas(item.sqlSentence);
                        }
                        existColumns.push({
                            field: item.fieldName,
                            title: item.fieldAlias?item.fieldAlias:item.labelName,
                            width: item.labelWidth,
                            formatter:function (value, row,rec) {
                                if (value&&item.fieldType === 'number') {
                                    return formatNumber(value, item.decimalPoint, 0).toString().replace(/(?:\.0*|(\.\d+?)0+)$/,'$1');
                                }
                                if (value&&item.fieldType === 'dict') {
                                    return getDicName(item.dictTypeCode,value)
                                }
                                if (value&&item.fieldType === 'data') {
                                    return getNecessaryDataName(item.sqlSentence,value)
                                }
                                // if (item.fieldType === 'files') {
                                //     return '<a href="#" onclick="uploadFilesDialog(this)" data-index="' + rec + '" data-value="' + value + '">上传/下载</a>';
                                // }
                                if (item.fieldType === 'files') {
                                    if (value){
                                        value.split(',').length
                                        return '<a href="#" onclick="uploadFilesDialog(this)" data-index="' + rec + '" data-value="' + value + '" data-fieldName="' + item.fieldName + '">查看('+value.split(',').length+')个附件</a>';
                                    }else {
                                        return '无附件';
                                    }
                                }
                                return value;
                            }
                        });

                        // tmpData.supplierLookField.push(item.fieldName);
                    }
                }
                // //如果报价类型为议价或查看，则追加期望价格和议价意见
                // if (quoteType!==0){
                //     existColumns.push({
                //         field: 'priceOpinion',
                //         title: '议价意见',
                //         width: 170
                //     });
                // }
                existColumns.push.apply(existColumns,afterColumns)
            }
        },
        error: function (data) {
            layer.alert(JSON.parse(data.responseText).message);
        }
    });
}

function uploadFilesDialog(target){
    let rowIndex = $(target).data('index'), value = $(target).data('value'),fieldName = $(target).attr('data-fieldName');
    openFileUploadDialog('uploadFilesDialog',{
        title:'查看',
        fileIds : value,
        height: '75%',
        lookFlag: 1,
        callBack : function (fileId) {

            console.log(fileId)
        },
    });
}