var el = {
    form : '#form',
    optType : '#optType',
    tbMaterial : '#tb_material',
    tbSupplier : '#tb_supplier',
    id : '#id',
    dataSource: '#dataSource',
    purchaseBillDetailIds: '#purchaseBillDetailIds',
    priceInfoIds: '#priceInfoIds',
    beginTime: '#beginTime',
    purchaseFiles: '#purchaseFiles',
    files: '#files',
    endTime: '#endTime',
    purchaseGroupCode: '#purchaseGroupCode',
    purchaseOrgCode: '#purchaseOrgCode',
    templateCode: '#templateCode',
    companyCode: '#companyCode',
    inquiryType: '#inquiryType',
    quoteModel: '#quoteModel',
    purchaseType: '#purchaseType',
    supplierMaterialFlag: '#supplierMaterialFlag',
    purchaseCategoryCode: '#purchaseCategoryCode',
    supplierDescLabel: '#supplierDescLabel',
    supplierDescNoLabel: '#supplierDescNoLabel',
    supplierDescDiv: '#supplierDescDiv',
    purchaseRequestType: '#purchaseRequestType',
    purchaseRequestTypeLabel: '#purchaseRequestTypeLabel',
    purchaseRequestTypeNoLabel: '#purchaseRequestTypeNoLabel',
    purchaseRequestTypeDiv: '#purchaseRequestTypeDiv',
    editIndex: undefined,
    editSupplierIndex: undefined,
    self: this
};
var tmpData = {
    //成本构成数组
    costModuleData: [],
    //模板字段数组
    templateFieldData: [],
    //模板字段名称数组
    templateFieldNameData: [],
}
$(function () {
    initDict('currency,payment_way,payment_method,procure_sub_class');
    initNecessaryDatas('pc/sys/tax/rest/listAll,pc/sys/company/rest/listAll,pc/sys/productGroup/rest/listAll,pc/sys/purchaseCategory/rest/listAll');
    initCombo();
    firstInitMaterialGrid();
    loadSupplierGrid();
});


function loadGrid(templateCode, loadType){
    // 在页面上申明一个新的表格DOM
    if (typeof(loadType) === 'undefined'){
        el.tbMaterial = $('<table id="tb_material" width="100%"></table>').appendTo($('.tb-material'));
    }
    // 固定加载的列
    let existColumns = [
        {
            field: 'costFlag',
            title: '成本构成<button type="button" onclick="copy(\'costFlag\')" class="easyui-linkbutton">复制</button>',
            width: 80,
            formatter: function (value) {
                if (Number(value) === 1) {
                    return '是';
                } else {
                    return '否';
                }
            },
            editor: {
                type: 'combobox',
                options: {
                    data: [
                        {'name': '否', 'code': '0'},
                        {'name': '是', 'code': '1'}
                    ],
                    valueField: 'code',
                    textField: 'name',
                    editable: false,
                    required:true,
                    limitToList: 'true',
                    panelHeight: 'auto',
                    onSelect: function (data) {
                        requireCostChange(Number(data.code));
                    }
                }
            }
        },
        {
            field: 'costTemplateCode',
            title: '成本构成模板<button type="button" onclick="copy(\'costTemplateCode\')" class="easyui-linkbutton">复制</button>',
            width: 100,
            formatter: function (value, row) {
                for (let i = 0; i < tmpData.costModuleData.length; i++) {
                    if (tmpData.costModuleData[i].value === value) {
                        return tmpData.costModuleData[i].text;
                    }
                }
                return row['text'];
            },
            editor: {
                type: 'combobox',
                options: {
                    data: tmpData.costModuleData,
                    valueField: 'value',
                    textField: 'text',
                    editable: false,
                    panelHeight: 150
                }
            }
        },
        {
            field: 'stagePriceFlag',
            title: '阶梯报价<button type="button" onclick="copy(\'stagePriceFlag\')" class="easyui-linkbutton">复制</button>',
            width: 80,
            formatter: function (value) {
                if (Number(value) === 1) {
                    return '是';
                } else {
                    return '否';
                }
            },
            editor: {
                type: 'combobox',
                options: {
                    data: [
                        {'name': '否', 'code': '0'},
                        {'name': '是', 'code': '1'}
                    ],
                    valueField: 'code',
                    textField: 'name',
                    editable: false,
                    required:true,
                    limitToList: 'true',
                    panelHeight: 'auto'
                }
            }
        }
        // {
        //     field: 'purchaseBillCode',
        //     title: '采购订单号',
        //     width: 120
        // },
        // {
        //     field: 'purchaseBillItemCode',
        //     title: '采购行项目号',
        //     width: 120
        // }
    ];
    var url = g.ctx + 'pc/inquiry/material/rest/listAll';
    if (optType===otpTypeEnum.COPY){
        url = g.ctx + 'pc/inquiry/material/rest/copyListAll';
    }
    //数据来源；0-手动新增；1-采购申请；2-价格信息记录
    if (Number($(el.dataSource).val())===1){
        url =  g.ctx + 'pc/inquiry/purchase/apply/bill/detail/rest/make/inquiry/material?purchaseBillDetailIds='+$(el.purchaseBillDetailIds).val();
    }
    if (Number($(el.dataSource).val())===2){
        url =  g.ctx + 'pc/inquiry/price/rest/make/inquiry/material?priceInfoIds='+$(el.priceInfoIds).val();
    }
    loadTemplateFiled(templateCode,3,existColumns);
    let options = {
        iconCls: 'icon-list',
        title: '待询价物料',
        loadMsg: '数据加载中......',
        url: url,
        height: 300,
        singleSelect: false,
        rownumbers: true,
        pagination: false,
        queryParams: {inquiryId:$(el.id).val()},
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'materialCode',
                    title: '物料编码',
                    width: 100
                },
                {
                    field: 'procureSubclass',
                    title: '采购类别',
                    width: 160,
                    formatter: function() {
                        // 直接使用全局变量的值，忽略后端返回的value
                        let procureSubclass = window.procureSubclass;
                        return getDicName('procure_sub_class', procureSubclass);
                    }
                },
                {
                    field: 'materialName',
                    title: '物料名称',
                    width: 160,
                    formatter: function (value, row) {
                        if (!value){
                            return '';
                        }
                        return '<span title="'+value+'">'+value+'</span>';
                    }
                },
                // {
                //     field: 'productName',
                //     title: '品名',
                //     width: 100,
                //     editor: {
                //         type: 'textbox'
                //     }
                // },
                {
                    field: 'materialSpec',
                    title: '详细规格参数',
                    width: 100,
                    editor: {
                        type: 'textbox'
                    }
                },
                // {
                //     field: 'brand',
                //     title: '品牌'+ '<button type="button" onclick="copy(\'brand\')" class="easyui-linkbutton">复制</button>',
                //     width: 100,
                //     editor: {
                //         type: 'textbox'
                //     }
                // }
            ]
        ],
        columns: [existColumns],
        toolbar: [
            {
                text: '选择物料',
                iconCls: 'icon-add',
                handler: function () {
                    selectMaterial();
                }
            }, "-",
            {
                text: '无物料',
                iconCls: 'icon-add',
                handler: function () {
                    noMaterialAdd();
                }
            }, "-",
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    deleteProduct();
                }
            }, "-",
            {
                text: '导入物料信息',
                iconCls: 'icon-import',
                handler: function () {
                    materialImport();
                }
            }
        ],
        onClickRow: function (index, row) {
            /**
             * 当选择有物料编码时:   物料描述，物料组编码，物料组描述不可编辑
             *
             * 无物料时:    物料描述，物料组编码，物料组描述可编辑
             */
            var rows = $(el.tbMaterial).datagrid('getRows');
            var materialCode = rows[index].materialCode;
            var materialName =  $(el.tbMaterial).datagrid('getColumnOption', 'materialName');
            // var purchaseUnit =  $(el.tbMaterial).datagrid('getColumnOption', 'purchaseUnit');
            var factoryCode =  $(el.tbMaterial).datagrid('getColumnOption', 'factoryCode');
            var materialGroupCode =  $(el.tbMaterial).datagrid('getColumnOption', 'materialGroupCode');

            var number =  $(el.tbMaterial).datagrid('getColumnOption', 'number');
            if (number != null){
                number.editor = {};
            }

            if (materialCode) {
                if (materialName != null){
                    materialName.editor = {};
                }
                // if (purchaseUnit != null){
                //     purchaseUnit.editor = {};
                // }
                if (factoryCode != null){
                    factoryCode.editor.options.readonly = true;
                    factoryCode.editor.options.disable = true;
                }
                if (materialGroupCode != null){
                    materialGroupCode.editor.options.readonly = true;
                }
            }else {
                materialName.editor = {
                    type: 'textbox'
                }
                if (materialGroupCode != null){
                    materialGroupCode.editor.options.readonly = false;
                }
                if (factoryCode != null){
                    factoryCode.editor.options.readonly = false;
                }
            }
            onClickRow(index);
        },
        onLoadSuccess: function (data) {
            $(el.tbMaterial).datagrid('clearSelections');
            // 检查是否为 MRO 模板，如果是则隐藏相应列
            if ($(el.templateCode).combobox('getValue') === 'PLATE_PRO_M002') {
                $(el.tbMaterial).datagrid('hideColumn', 'factoryCode');
                $(el.tbMaterial).datagrid('hideColumn', 'materialGroupCode');
            }
            //数据来源；0-手动新增；1-采购申请；2-价格信息记录
            if (Number($(el.dataSource).val())===1||Number($(el.dataSource).val())===2){
                var rows = data.rows;
                let companyCode =   $(el.companyCode).combobox('getValue');
                for (var j = 0; j < rows.length; j++) {
                    if (rows[j].materialCode&&rows[j].factoryCode&&companyCode) {
                        getSupplierByMaterialCodeAndFactoryCode(rows[j].materialCode,rows[j].factoryCode,companyCode);
                    }
                }
            }
        }
    };
    $(el.tbMaterial).datagrid(options);
    // $(el.tbMaterial).datagrid('hideColumn', 'purchaseBillCode');
    // $(el.tbMaterial).datagrid('hideColumn', 'purchaseBillItemCode');
}

/**
 * 加载供应商数据
 */
function loadSupplierGrid() {
    var url = g.ctx + 'pc/inquiry/rest/supplierListByInquiryId';
    if (optType===otpTypeEnum.COPY){
        url = g.ctx + 'pc/inquiry/rest/supplierCopyListByInquiryId';
    }
    $(el.tbSupplier).datagrid({
        iconCls: 'icon-list',
        title: '待报价供应商',
        loadMsg: '数据加载中......',
        url: url,
        height: 270,
        singleSelect: false,
        pagination: false,
        rownumbers: true,
        queryParams: {inquiryId:$(el.id).val()},
        rowStyler: function (index, row) {
            //如果为配额供应商，显示灰色
            if (row.quotaSupplierFlag) {
                return 'background-color:#d9d9d9;';
            }
        },
        columns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'joinQuoteFlag',
                    title: '参与报价',
                    width: 80,
                    formatter: function (value) {
                        if (Number(value) === 1) {
                            return '参与';
                        } else {
                            return '不参与';
                        }
                    },
                    editor: {
                        type: 'combobox',
                        options: {
                            data: [
                                {'name': '不参与', 'code': '0'},
                                {'name': '参与', 'code': '1'}
                            ],
                            valueField: 'code',
                            textField: 'name',
                            editable: false,
                            required:true,
                            limitToList: 'true',
                            panelHeight: 'auto'
                        }
                    }
                },
                {
                    field: 'procureSubclass',
                    title: '采购类别',
                    width: 160,
                    formatter: function() {
                        // 直接使用全局变量的值，忽略后端返回的value
                        let procureSubclass = window.procureSubclass;
                        return getDicName('procure_sub_class', procureSubclass);
                    }
                },
                {
                    field: 'supplierCode',
                    title: '供应商编码',
                    width: 80
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 180
                },
                {
                    field: 'currencyCode',
                    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: 'paymentWay',
                //     title: '付款方式',
                //     width: '12%',
                //     align: 'center',
                //     formatter: function (value) {
                //         getDicName('payment_way',value);
                //     }
                // },
                {
                    field: 'paymentMethod',
                    title: '付款条件',
                    width: '12%',
                    align: 'center',
                    formatter: function (value) {
                        return getDicName('payment_method',value);
                    }
                },
                {
                    field: 'supplierContactsName',
                    title: '供应商联系人',
                    width: 130
                },
                {
                    field: 'supplierEmail',
                    title: '<span style="color:red">*</span>邮箱',
                    width: 130,
                    editor: {
                        type: 'textbox',
                        options: {
                            editable: false,
                            required: true,
                            icons: [{
                                iconCls: 'icon-search',
                                handler: function () {
                                    var row = $(el.tbSupplier).datagrid('getRows')[el.editSupplierIndex];
                                    var url = g.ctx + "pc/supplier/contact/page/select?single=0&supplierCode="+row.supplierCode;
                                    el.choseSupplierEmailDialog = openDialog('choseEmailSupplier', url, {
                                        title: '供应商邮箱选择',
                                        width: '80%',
                                        height: '70%',
                                        cache: false,
                                        modal: true,
                                        border: 'thin',
                                        onClose: function () {
                                            el.choseSupplierEmailDialog.dialog('destroy');
                                        },
                                        buttons: [
                                            {
                                                text: '确定',
                                                iconCls: 'icon-ok',
                                                handler: function () {
                                                    topWin.frames['choseEmailSupplier'].chooseRow(function (data) {
                                                        console.log(data)
                                                        let supplierEmail = $(el.tbSupplier).datagrid('getEditor', {
                                                            index: el.editSupplierIndex,
                                                            field: 'supplierEmail'
                                                        }).target;
                                                        var emailList = [];
                                                        var contactsList = [];
                                                        $.each(data, function (index, target) {
                                                            emailList.push(target.email);
                                                            contactsList.push(target.contactsName);
                                                        });
                                                        console.log(emailList.join(','))
                                                        supplierEmail.textbox('setValue', emailList.join(','));
                                                        $(el.tbSupplier).datagrid('updateRow', {
                                                            index: el.editSupplierIndex,
                                                            row: {
                                                                supplierContactsName: contactsList.join(','),
                                                                supplierEmail: emailList.join(','),
                                                            }
                                                        });
                                                        el.choseSupplierEmailDialog.dialog('close');
                                                    });
                                                }
                                            },
                                            {
                                                text: '关闭',
                                                iconCls: 'icon-cancel',
                                                handler: function () {
                                                    el.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 () {
                                    let purchaseCategoryCode = $(el.purchaseCategoryCode).combobox('getValue');
                                    if(!purchaseCategoryCode){
                                        layer.msg("请选择器件分类");
                                        return ;
                                    }
                                    var row = $(el.tbSupplier).datagrid('getRows')[el.editSupplierIndex];
                                    var url = g.ctx + "pc/supplier/purchaseCategory/page/selector?single=1&supplierId="+row.supplierId+"&category="+purchaseCategoryCode;
                                    el.choseSupplierDialog = openDialog('choseSupplier', url, {
                                        title: '供应商品类选择',
                                        width: '80%',
                                        height: '70%',
                                        cache: false,
                                        modal: true,
                                        border: 'thin',
                                        onClose: function () {
                                            el.choseSupplierDialog.dialog('destroy');
                                        },
                                        buttons: [
                                            {
                                                text: '确定',
                                                iconCls: 'icon-ok',
                                                handler: function () {
                                                    topWin.frames['choseSupplier'].chooseRow(function (data) {
                                                        let purchaseCategoryCode = $(el.tbSupplier).datagrid('getEditor', {
                                                            index: el.editSupplierIndex,
                                                            field: 'purchaseCategoryCode'
                                                        }).target;
                                                        purchaseCategoryCode.textbox('setValue', data[0].purchaseCategoryCode);
                                                        $(el.tbSupplier).datagrid('updateRow', {
                                                            index: el.editSupplierIndex,
                                                            row: {
                                                                purchaseCategoryName: data[0].purchaseCategoryName,
                                                                currencyCode: data[0].currencyCode,
                                                                taxCode: data[0].taxCode,
                                                                paymentMethod: data[0].paymentTerms,
                                                                companyCode: data[0].companyCode
                                                            }
                                                        });
                                                        el.choseSupplierDialog.dialog('close');
                                                    });
                                                }
                                            },
                                            {
                                                text: '关闭',
                                                iconCls: 'icon-cancel',
                                                handler: function () {
                                                    el.choseSupplierDialog.dialog('close');
                                                }
                                            }
                                        ]
                                    });
                                }
                            }]
                        }
                    }
                },
                {
                    field: 'purchaseCategoryName',
                    title: '采购品类名称',
                    width: 160,
                },
                {
                    field: 'companyCode',
                    title: '公司',
                    width: 240,
                    formatter: function (value) {
                        return getNecessaryDataName('pc/sys/company/rest/listAll',value);
                    }
                },
            ]
        ],
        toolbar: [
            {
                text: '选择供应商',
                iconCls: 'icon-add',
                handler: function () {
                    selectSupplier();
                }
            }, '-', {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    deleteSupplier();
                }
            }, "-",
            {
                text: '导入供应商',
                iconCls: 'icon-import',
                handler: function () {
                    supplierImport();
                }
            }
        ],
        onBeginEdit: function (index, row) {
            el.editSupplierIndex = index;
        },
        onClickRow: function (index, row) {
            var joinQuoteFlag =  $(el.tbSupplier).datagrid('getColumnOption', 'joinQuoteFlag');
            //如果为配额供应商，允许编辑
            if (row.quotaSupplierFlag) {
                if (joinQuoteFlag != null){
                    joinQuoteFlag.editor.options.readonly = false;
                }
            }else {
                joinQuoteFlag.editor.options.readonly = true;
            }
            onClickSupplierRow(index);
        }
    });
}

function deleteSupplier() {
    let rows = $(el.tbSupplier).datagrid('getSelections');
    if (rows.length === 0) {
        layer.msg('请选中需要删除的报价供应商', {icon: 0});
        return false;
    }
    $.each(rows, function (index, item) {
        // if (item.quotaSupplierFlag) {
        //     layer.msg('选中供应商包含配额供应商，不可删除', {icon: 0});
        //     return false;
        // }
        let rowIndex = $(el.tbSupplier).datagrid('getRowIndex', item);
        $(el.tbSupplier).datagrid('deleteRow', rowIndex);
    });
}

/**
 * 物料数据导入
 */
function materialImport() {
    let purchaseGroupCode = $(el.purchaseGroupCode).combobox('getValue');
    if(!purchaseGroupCode){
        layer.alert("请先选择采购组", {icon: 0});
        return false;
    }
    let companyCode =   $(el.companyCode).combobox('getValue');
    if(!companyCode){
        layer.alert('请先选择签约主体', {icon: 0});
        return false;
    }
    endEditing();

    var importDialog = openImportExcelDialog('static/excel/material_list.xls','物料导入',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/rest/importMaterialData',
            method: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: function (data) {
                topWin.layer.alert("导入成功", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    let ps = $(el.tbMaterial).datagrid('getRows');
                    console.log(data)
                    console.log(ps)
                    for (let i = 0; i < data.length; i++) {
                        let product = data[i];
                        let sameFlag = false;
                        for (let j = 0; j < ps.length; j++) {
                            if ((product.materialCode+product.materialName) === (ps[j].materialCode+ps[j].materialName)) {
                                sameFlag = true;
                                break;
                            }
                        }
                        if (sameFlag){
                            continue;
                        }
                        getSupplierByMaterialCodeAndFactoryCode(product.materialCode,product.factoryCode,companyCode);
                        $(el.tbMaterial).datagrid('appendRow', {
                            costFlag: 0,
                            stagePriceFlag: 0,
                            number: 0,
                            productId: product.productId,
                            materialName: product.materialName,
                            materialDesc: product.materialDesc,
                            materialCode: product.materialCode,
                            factoryCode: product.factoryCode,
                            purchaseUnit: product.purchaseUnit,
                            purchaseNum: product.purchaseNum?product.purchaseNum:1,
                            targetPriceType:2,
                            targetPrice:product.lastBidPrice,
                            historyPriceId:product.historyPriceId,
                            historyPrice:product.historyPrice,
                            lastBidPriceId:product.lastBidPriceId,
                            lastBidPrice:product.lastBidPrice,
                            quoteFromDate: product.quoteFromDate?moment(product.quoteFromDate).format('YYYY-MM-DD'):moment().format('YYYY-MM-DD'),
                            quoteEndDate: product.quoteEndDate?moment(product.quoteEndDate).format('YYYY-MM-DD'):moment().add(12, 'month').format('YYYY-MM-DD'),
                            productName: product.productName,
                            materialSpec: product.materialSpec,
                            brand: product.brand,
                            currencyCode: product.currencyCode?product.currencyCode:'CNY',
                            remark: product.remark,
                            materialGroupCode: product.materialGroupCode,
                            materialGroupName: product.materialGroupName,
                        });
                    }
                    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: '温馨提示'});
            }
        });
    });
}

/**
 * 供应商数据导入
 */
function supplierImport() {
    let purchaseOrgCode = $(el.purchaseOrgCode).combobox('getValue');
    if(!purchaseOrgCode){
        layer.msg("请选择采购组织");
        return false;
    }
    let companyCode = $(el.companyCode).combobox('getValue');
    if(!companyCode){
        layer.msg("请选择签约主体");
        return false;
    }

    var importDialog = openImportExcelDialog('static/excel/supplier_list.xls','供应商导入',function(file){
        let formData = new FormData();
        formData.append("file", file);
        // formData.append("purchaseOrgCode", purchaseOrgCode);
        formData.append("companyCode", companyCode);
        var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/inquiry/rest/importSupplierData',
            method: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: function (data) {
                topWin.layer.alert("导入成功", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    let ps = $(el.tbSupplier).datagrid('getRows');
                    for (let i = 0; i < data.length; i++) {
                        let supplier = data[i];
                        let sameFlag = false;
                        for (let j = 0; j < ps.length; j++) {
                            if (supplier.supplierId === ps[j].supplierId) {
                                sameFlag = true;
                                break;
                            }
                        }
                        if (sameFlag){
                            continue;
                        }
                        getSupplierEmail(supplier);
                        $(el.tbSupplier).datagrid('appendRow', {
                            supplierId: supplier.supplierId,
                            supplierCode: supplier.supplierCode,
                            supplierName: supplier.supplierName,
                            currencyCode: supplier.currencyCode,
                            supplierEmail: supplier.supplierEmail,
                            taxCode: supplier.taxCode,
                            paymentMethod: supplier.paymentMethod,
                            purchaseCategoryCode: supplier.purchaseCategoryCode,
                            purchaseCategoryName: supplier.purchaseCategoryName,
                            companyCode: supplier.companyCode,
                            joinQuoteFlag: 1,
                        });
                    }
                    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: '温馨提示'});
            }
        });
    });
}

/**
 * 选择报价供应商数据
 */
function selectSupplier() {
    let materialRows = $(el.tbMaterial).datagrid('getRows');
    if (materialRows.length === 0) {
        layer.msg(xunjia_msg.add_material_notnull, {icon: 2});
        return false;
    }

    // let supRows = $(el.tbSupplier).datagrid('getRows');
    // let supplierCodes = [];
    // for (let k = 0; k < supRows.length; k++) {
    //     supplierCodes.push(supRows[k].supplierCode);
    // }
    let purchaseOrgCode = $(el.purchaseOrgCode).combobox('getValue');
    if(!purchaseOrgCode){
        layer.msg("请选择采购组织");
        return ;
    }
    let companyCode = $(el.companyCode).combobox('getValue');
    if(!companyCode){
        layer.msg("请选择签约主体");
        return ;
    }
    let purchaseCategoryCode = $(el.purchaseCategoryCode).combobox('getValue');
    if(!purchaseCategoryCode){
        layer.msg("请选择器件分类");
        return ;
    }
    var supplierDialogElement = openDialog("supplierDialog", g.ctx + "pc/supplier/supplierSelect?companyCode="+companyCode+"&purchaseOrgCode="+purchaseOrgCode+"&single=0&state=2,3"+"&categories="+purchaseCategoryCode, {
        title: common_layer_title.select_supplier_title,
        width: '80%',
        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 (data) {
                    let old_supplier = $(el.tbSupplier).datagrid('getRows');
                    for (let i = 0; i < data.length; i++) {
                        let supplier = data[i];
                        if (!supplier.id)
                            continue;

                        let sameFlag = false;
                        for (let j = 0; j < old_supplier.length; j++) {
                            if (supplier.id === old_supplier[j].supplierId) {
                                sameFlag = true;
                                break;
                            }
                        }
                        if (sameFlag) {
                            continue;
                        }
                        getSupplierEmail(supplier);
                        // mark 为0代表新增的供应商
                        $(el.tbSupplier).datagrid('appendRow', {
                            supplierCode: supplier.supplierCode,
                            supplierName: supplier.supplierName,
                            supplierId: supplier.id,
                            supplierEmail: supplier.supplierEmail,
                            supplierContactsName: supplier.supplierContactsName,
                            currencyCode: supplier.currencyCode,
                            taxCode: supplier.taxCode,
                            paymentMethod: supplier.paymentTerms,
                            purchaseCategoryCode: supplier.purchaseCategoryCode,
                            purchaseCategoryName: supplier.purchaseCategoryName,
                            companyCode: supplier.companyCode,
                            companyName: supplier.companyName,
                            joinQuoteFlag: 1,
                        });
                    }
                    supplierDialogElement.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'icon-cancel',
            handler: function () {
                supplierDialogElement.dialog('close');
            }
        }]
    });
}

/**
 * 选择物料
 */
function selectMaterial(){
    let purchaseGroupCode = $(el.purchaseGroupCode).combobox('getValue');
    if(!purchaseGroupCode){
        layer.alert('请先选择采购组', {icon: 0});
        return false;
    }
    let companyCode =   $(el.companyCode).combobox('getValue');
    if(!companyCode){
        layer.alert('请先选择签约主体', {icon: 0});
        return false;
    }
    var selectMaterialElement = openDialog("selectMaterialDialog", g.ctx + 'pc/sys/product/select/dialog?priceFlag=1&purchaseGroupFlag=1', {
        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 (data) {
                    let ps = $(el.tbMaterial).datagrid('getRows');
                    for (let i = 0; i < data.length; i++) {
                        let product = data[i];
                        let sameFlag = false;
                        for (let j = 0; j < ps.length; j++) {
                            if (product.id === ps[j].productId) {
                                sameFlag = true;
                                break;
                            }
                        }
                        if (sameFlag){
                            continue;
                        }
                        console.log(product)
                        getSupplierByMaterialCodeAndFactoryCode(product.materialCode,product.factoryCode,companyCode);
                        $(el.tbMaterial).datagrid('appendRow', {
                            productId: product.id,
                            materialName: product.materialName,
                            materialDesc: product.materialDesc,
                            materialCode: product.materialCode,
                            productName: product.productName,
                            materialSpec: product.materialSpec,
                            materialModel: product.materialModel,
                            brand: product.brand,
                            costFlag:0,
                            stagePriceFlag:0,
                            number:0,
                            purchaseNum:1,
                            materialGroupCode: product.materialGroupCode,
                            materialGroupName: product.materialGroupName,
                            materialUnit: product.basisUnit,
                            purchaseUnit:product.orderUnit,
                            factoryCode: product.factoryCode,
                            currencyCode:'CNY',
                            targetPriceType:2,
                            targetPrice:product.lastBidPrice,
                            historyPriceId:product.historyPriceId,
                            historyPrice:product.historyPrice,
                            lastBidPriceId:product.lastBidPriceId,
                            lastBidPrice:product.lastBidPrice,
                            quoteFromDate:moment().format('YYYY-MM-DD'),
                            quoteEndDate:moment().add(12, 'month').format('YYYY-MM-DD'),
                        });
                    }
                    selectMaterialElement.dialog('close');
                });
            }
        }, {
            text: '关闭',
            iconCls: 'icon-cancel',
            handler: function () {
                selectMaterialElement.dialog('close');
            }
        }]
    });
}

/**
 * 根据物料编码和工厂编码获取配额供应商
 * @param materialCode 物料编码
 * @param factoryCode 工厂编码
 */
function getSupplierByMaterialCodeAndFactoryCode(materialCode,factoryCode,companyCode){
    var loading = top.layer.msg('正在获取配额供应商数据，请稍后', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/inquiry/rest/getSupplierByMaterialCodeAndFactoryCode',
        method: "post",
        data: {materialCode: materialCode,factoryCode:factoryCode,companyCode:companyCode},
        success: function (data) {
            let old_supplier = $(el.tbSupplier).datagrid('getRows');
            for (let i = 0; i < data.length; i++) {
                let supplier = data[i];
                if (!supplier.supplierId)
                    continue;

                let sameFlag = false;
                for (let j = 0; j < old_supplier.length; j++) {
                    if (supplier.id === old_supplier[j].supplierId) {
                        sameFlag = true;
                        break;
                    }
                }
                if (sameFlag) {
                    continue;
                }
                // mark 为0代表新增的供应商
                $(el.tbSupplier).datagrid('appendRow', {
                    supplierCode: supplier.supplierCode,
                    supplierName: supplier.supplierName,
                    supplierId: supplier.supplierId,
                    currencyCode: supplier.currencyCode,
                    taxCode: supplier.taxCode,
                    paymentMethod: supplier.paymentMethod,
                    purchaseCategoryCode: supplier.purchaseCategoryCode,
                    purchaseCategoryName: supplier.purchaseCategoryName,
                    companyCode: supplier.companyCode,
                    companyName: supplier.companyName,
                    supplierEmail: supplier.supplierEmail,
                    supplierContactsName: supplier.supplierContactsName,
                    quotaSupplierFlag: materialCode+'_'+factoryCode,
                    joinQuoteFlag: 1,
                });
            }
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}

/**
 * 根据供应商编码和业务类型获取供应商邮箱
 * @param supplierCode 供应商编码
 */
function getSupplierEmail(supplier){
    var loading = top.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.supplierEmail = data.email;
            supplier.supplierContactsName = data.contactsName;
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}

/**
 * 无物料添加
 */
function noMaterialAdd() {
    let purchaseGroupCode = $(el.purchaseGroupCode).combobox('getValue');
    if(!purchaseGroupCode){
        layer.alert("请先选择采购组", {icon: 0});
        return false;
    }
    endEditing();
    $(el.tbMaterial).datagrid('appendRow', {
        costFlag: 0,
        stagePriceFlag: 0,
        number: 0,
        purchaseNum:1,
        targetPriceType:2,
        quoteFromDate:moment().format('YYYY-MM-DD'),
        quoteEndDate:moment().add(12, 'month').format('YYYY-MM-DD'),
        // quoteFromDate: moment(new Date()).format('YYYY-MM-DD'),
        // quoteEndDate: moment(new Date()).add(7, 'days').format('YYYY-MM-DD'),
    });
    endEditing();
}

/**
 * 删除选中的物料
 */
function deleteProduct() {
    let rows = $(el.tbMaterial).datagrid('getSelections');
    if (rows.length === 0) {
        layer.msg(common_opt_msg.opt_select_one_record);
        return false;
    }
    //先关闭行编辑
    if (el.editIndex !== undefined) {
        $(el.tbMaterial).datagrid('endEdit', el.editIndex);
        el.editIndex = undefined;
    }
    layer.confirm('您确定要是删除您选中的询价物料信息吗？', {icon: 3}, function () {
        for (let i = rows.length - 1; i >= 0; i--) {
            let rowIndex = $(el.tbMaterial).datagrid('getRowIndex', rows[i]);
            $(el.tbMaterial).datagrid('deleteRow', rowIndex);
            layer.msg(common_opt_msg.opt_success_msg);
        }
    });
}

/**
 * 双击行，开启行编辑
 *
 * @param index 行索引
 */
function onClickRow(index) {

    if (el.editIndex !== index) {
        if (endEditing()) {
            el.editIndex = index;
            $(el.tbMaterial).datagrid('selectRow', index).datagrid('beginEdit', index);
            el.editIndex = index;
            // let costModuleComb = $(el.tbMaterial).datagrid('getEditor', {
            //     index: index,
            //     field: 'cost_modular_name'
            // }).target;
            // if (el.costModuleData.length > 0) {
            //     costModuleComb.combobox("loadData", el.costModuleData);
            // }
            // combboxBindEvent(index);
        } else {
            el.editIndex = index;
            $(el.tbMaterial).datagrid('selectRow', el.editIndex);
        }
    } else {
        $(el.tbMaterial).datagrid('selectRow', index).datagrid('beginEdit', index);
        el.editIndex = index;

    }
}

/**
 * 双击行，开启行编辑
 *
 * @param index 行索引
 */
function onClickSupplierRow(index) {

    if (el.editSupplierIndex !== index) {
        if (endSupplierEditing()) {
            $(el.tbSupplier).datagrid('selectRow', index).datagrid('beginEdit', index);
            el.editSupplierIndex = index;
        } else {
            $(el.tbSupplier).datagrid('selectRow', el.editSupplierIndex);
        }
    } else {
        $(el.tbSupplier).datagrid('selectRow', index).datagrid('beginEdit', index);
        el.editSupplierIndex = index;

    }
}

/**
 * 结束行编辑
 *
 * @return {boolean} 结果
 */
function endSupplierEditing() {
    if (el.editSupplierIndex === undefined) {
        return true
    }
    if ($(el.tbSupplier).datagrid('validateRow', el.editSupplierIndex)) {
        $(el.tbSupplier).datagrid('endEdit', el.editSupplierIndex);
        el.editSupplierIndex = undefined;
        return true;
    } else {
        return false;
    }


}

/**
 * 结束行编辑
 *
 * @return {boolean} 结果
 */
function endEditing() {
    if (el.editIndex === undefined) {
        return true
    }
    if ($(el.tbMaterial).datagrid('validateRow', el.editIndex)) {
        $(el.tbMaterial).datagrid('endEdit', el.editIndex);
        el.editIndex = undefined;
        return true;
    } else {
        return false;
    }
}
/**
 * 提交所有从加载或者上一次调用acceptChanges函数后更改的数据
 */
function accept() {
    if (endEditing()) {
        $(el.tbMaterial).datagrid('acceptChanges');
    }

    if (endSupplierEditing()) {
        $(el.tbSupplier).datagrid('acceptChanges');
    }
}

function uploadFilesDialog(rec){
    let rowIndex = $(rec).data('index'), value = $(rec).data('value'),fieldName = $(rec).attr('data-fieldName');
    openFileUploadDialog('uploadFilesDialog',{
        title:'附件',
        fileIds : value,
        lookFlag: false,
        height: '75%',
        callBack : function (fileIds) {
            $(el.tbMaterial).datagrid('endEdit', rowIndex);
            $(el.tbMaterial).datagrid('updateRow', {
                index: rowIndex,
                row: {
                    [fieldName]: fileIds.join(',')
                }
            });
            $(el.tbMaterial).datagrid('beginEdit', rowIndex);
        },
    });
}

/**
 * 成本构成切换
 *
 * @param data 选中的数据
 */
function requireCostChange(data) {
    // 成本构成模板 根据是否需要 进行切换
    let cellEdit = $(el.tbMaterial).datagrid('getEditor', {index: el.editIndex, field: 'costTemplateCode'});
    let $input = cellEdit.target;
    if (data === 0) {
        $input.combobox('setValue', '');
        $input.combobox('disable');
    } else {
        $input.combobox('enable');
    }
}

function copy(type) {
    endEditing();
    let allRows = $(el.tbMaterial).datagrid('getRows');
    for (let i = 0;i<allRows.length;i++){
        $(el.tbMaterial).datagrid('endEdit', i);

    }
    for (let i = 0; i < allRows.length; i++) {
        $(el.tbMaterial).datagrid('updateRow', {
            index: i,
            row: {
                [type]: allRows[0][type]
            }
        });
    }
}

/**
 * 获取成本构成模板数据
 *
 * @param purchaseGroupCode 采购组编码
 */
function getCostModuleData(purchaseGroupCode) {
    $.ajax({
        url: g.ctx + 'pc/inquiry/cost/template/rest/getAllListByPurchaseGroupCode',
        type: 'GET',
        async: false,
        data: {purchaseGroupCode: purchaseGroupCode},
        success: function (data) {
            // 清空
            tmpData.costModuleData = [];
            if (data && data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                    tmpData.costModuleData.push({
                        value: data[i].templateCode,
                        text: data[i].templateName
                    });
                }
            }
        },
        error: function (data) {
            layer.alert(JSON.parse(data.responseText).message);
        }
    });
}

/**
 * 初始化询价单物料明细列表
 */
function firstInitMaterialGrid() {
    $(el.tbMaterial).edatagrid({
        iconCls: 'icon-list',
        title: '待询价物料',
        loadMsg: '数据加载中......',
        height: 300,
        singleSelect: true,
        autoSave: true,
        rownumbers: true,
        queryParams: {},
        columns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'material_code',
                    title: '物料编码',
                    width: 100
                },
                {
                    field: 'material_name',
                    title: '物料名称',
                    width: 150
                }
            ]
        ]
    });
}


function saveOrUpdate(call){
    if($(el.form).form('validate')){
        var formData = $(el.form).serializeJson();
        var beginTime = $(el.beginTime).datetimebox('getValue'), endTime = $(el.endTime).datetimebox('getValue'),companyCode = $(el.companyCode).combobox('getValue');
        if (beginTime > endTime){
            layer.msg("结束时间必须大于或等于开始时间");
            return;
        }
        formData.id = optType===otpTypeEnum.COPY?'':$(el.id).val();
        formData.purchaseFiles = $(el.purchaseFiles).attr('data-fileIds');

        formData.files = $(el.files).attr('data-fileIds');

        accept();
        let product = $(el.tbMaterial).datagrid('getRows');
        if (product.length <= 0) {
            layer.msg(xunjia_msg.select_material_notnull, {time: 2000});
            return false;
        }
        //如果是
        // var isMroModelFlag = false;
        // debugger
        // var templateCode = $(el.templateCode).val();
        // if (templateCode === 'PLATE_PRO_M002') {
        //     isMroModelFlag = true;
        // }
        for (let i = 0 ; i < product.length ; i ++){
            let flag = false, msg = "";
            if (Number(product[i].costFlag)===1&&Number(product[i].stagePriceFlag)===1){
                layer.msg('询价物料第' + (i + 1) + '行，成本构成和阶梯报价只能选择一个');
                return false;
            }
            if (Number(product[i].costFlag)===1&&!product[i].costTemplateCode){
                layer.msg('询价物料第' + (i + 1) + '行，请选择成本构成模版');
                return false;
            }
            if (!product[i].materialName) {
                layer.msg('询价物料第' + (i + 1) + '行，物料名称不能为空');
                return false;
            }
            if (product[i].purchaseNum&&Number(product[i].purchaseNum) === 0){
                layer.msg('询价物料第' + (i + 1) + '行，采购数量不能为0');
                return;
            }
            //判断采购数量不可大于可采购数量
            // if (Number($(el.dataSource).val())===1) {
                //如果采购申请单号不为空，且行号也不为空，则需要进行以上校验
                if (product[i].purchaseBillCode && product[i].purchaseBillItemCode) {
                    if (Number(product[i].purchaseNum) > Number(product[i].enablePurchaseNum)) {
                        layer.msg('询价物料第' + (i + 1) + '行，采购数量不能大于可采购数量');
                        return;
                    }
                }
            // }


            // if (!isMroModelFlag) {
            //     if (!product[i].materialGroupCode) {
            //         layer.msg('询价物料第' + (i + 1) + '行，物料组编码不能为空');
            //         return;
            //     }
            // }
            if(product[i].quoteFromDate && product[i].quoteEndDate){
                if (product[i].quoteFromDate > product[i].quoteEndDate) {
                    layer.msg("询价物料第"+ ++i+"行，有效起始日必须小于有效结束日");
                    return;
                }
            }
            if (tmpData.templateFieldData.length > 0) {
                $.each(tmpData.templateFieldData, function (index, target) {
                    if (!product[i][target.fieldName]&&target.required === 1) {
                        msg = '询价物料第' + (i + 1) + '行，' + target.labelName + '不能为空';
                        flag = true;
                        return false;
                    }
                });
                if (flag) {
                    layer.msg(msg, {time: 2000});
                    return false;
                }
            }
            if (!product[i].materialDesc&&!product[i].materialCode){
                product[i].materialDesc = product[i].materialName;
            }
        }

        let supplier = $(el.tbSupplier).datagrid('getRows');
        if (supplier.length <= 0) {
            layer.msg(xunjia_msg.select_supplier_notnull, {time: 2000});
            return false;
        }
        if (supplier.length > 0) {
            for (let j = 0; j < supplier.length; j++) {
                if(!supplier[j].supplierEmail){
                    layer.msg("报价供应商第"+ ++j+"行供应商邮箱不能为空");
                    return false;
                }
                if(!supplier[j].purchaseCategoryCode){
                    layer.msg("报价供应商第"+ ++j+"行采购品类编码不能为空");
                    return false;
                }
                if(supplier[j].companyCode!==companyCode){
                    layer.msg("报价供应商第"+ ++j+"行签约主体与供应商公司关系不匹配");
                    return false;
                }
            }
        }
        formData.inquiryMaterialList = product;
        formData.inquirySupplierList = supplier;
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/inquiry/rest/saveOrUpdate',
            method: 'post',
            data: JSON.stringify(formData),
            contentType: 'application/json',
            success: function (data) {
                call();
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    }
}