var el = {
    form : '#form',
    id : '#id',
    inquiryId : '#inquiryId',
    tb : '#tb',
    supplierFormFiles: '#supplierFormFiles',
    oldSupplierFormFiles: '#oldSupplierFormFiles',
    inquirySupplierStatus: '#inquirySupplierStatus',
    materialFileInput: '#materialFileInput',
    supplierMaterialFlag: '#supplierMaterialFlag',
    files: '#files',
    supplierFormRemark: '#supplierFormRemark',
    isView: '#isView',
    endTime: '#endTime',
    templateCode: '#templateCode',
    companyCode: '#companyCode',
    purchaseType: '#purchaseType',
    stageQuoteData: {},
    costQuoteData: {},
    costQuoteMaterial: {},
    clickRowIndex: -1,
    editIndex: undefined,
    bodyHeight: document.documentElement.clientHeight,
};
var tmpData = {
    //成本构成数组
    costModuleData: [],
    //模板字段数组
    templateFieldData: [],
    supplierLookField: [],
    supplierNotAllowEditField: [],
    //模板字段名称数组
    templateFieldNameData: [],
}
$(function () {
    initDict('currency,tax,payment_way,payment_method,unit,invoice_type');
    initNecessaryDatas('pc/sys/company/rest/listAll,pc/sys/tax/rest/listAll');
    initCombo();
    loadGrid($(el.templateCode).val());
});

function initCombo() {
    $(el.companyCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/company/rest/listAll'
    });

    //采购类型
    $(el.purchaseType).combobox({
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': '标准', 'code': '0'},
            {'name': '委外', 'code': '3'}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });
}

function loadGrid(templateCode) {
    const MRO_TEMPLATE_CODE = 'PLATE_PRO_M002';
    const isMroTemplate = templateCode === MRO_TEMPLATE_CODE;
    var frozenColumns = [];
    if (!isMroTemplate) {
        frozenColumns.push({
            field: 'materialCode',
            title: '物料编码',
            width: 100
        });
    }
     frozenColumns.push(
        {
            field: 'materialName',
            title: '物料名称',
            width: 160,
            formatter: function (value, row) {
                if (!value){
                    return '';
                }
                if (Number($(el.supplierMaterialFlag).val())===0){
                    return '<span title="'+value+'">'+value+'</span>';
                }else {
                    return '<span title="'+row.materialDesc+'">'+row.materialDesc+'</span>';
                }
            }
        },
        {
            field: 'materialSpec',
            title: '详细规格参数',
            width: 100
        },
        // {
        //     field: 'productName',
        //     title: '品名',
        //     width: 100
        // },
        {
            field: 'currencyCode',
            title: "货币",
            width: 80,
            formatter: function (value) {
                return getDicName('currency',value);
            }
        },

        {
            field: 'stagePriceFlag',
            title: '阶梯报价',
            width: 70,
            formatter: function (value, row, index) {
                accept();
                if (value === 1) {
                    var lookFlag = (inquirySupplierStatus===2||inquirySupplierStatus===6)&&Number(row.bargainFlag) === 0?1:0;
                    return '<a href="javascript:void(0);" style="color: blue;" onclick="stageQuote('+index+','+lookFlag+')" data-index="' + index + '"  data-sid="' + row.id + '" data-status="' + row.status + '">' + BJGL.BJGL__JTBJ + '</a>';
                } else if (value === 0) {
                    return '否';
                }
            }
        },
);
    if (quoteType!==0){
        frozenColumns.push({
            field: 'desirePrice',
            title: '期望价格',
            width: 60,
            formatter: function (value) {
                if (value) {
                    return '<span style="color:red;">' + value + '</span>';
                }
                return '';
            }
        });
        // frozenColumns.push({
        //     field: 'priceOpinion',
        //     title: '议价意见',
        //     width: 170
        // });
    }
    var columns = [

        {
            field: 'noTaxPrice',
            title: "未税单价",
            width: 90,
            formatter: function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'taxPrice',
            title: '含税单价<span style="color: red">*</span>',
            width: 90,
            formatter: function (value, row, index) {
                if (Number(row.costFlag) === 1) {
                    if (!value) {
                        value = '成本报价';
                    }else {
                        value = formatterPrice(value)
                    }
                    var lookFlag = (inquirySupplierStatus===2||inquirySupplierStatus===6)&&Number(row.bargainFlag) === 0?1:0;
                    el.clickRowIndex = index;
                    return '<a href="javascript:void(0);" style="color: blue;" onclick="costQuote('+index+','+lookFlag+')">' + value + '</a>';
                }
                return value;
            },
            // styler: function (value, row) {
            //     var bargainFlag = row.bargainFlag;
            //     if (Number(bargainFlag) === 0) {
            //         return 'background-color:#92b3d0;';
            //     } else if (Number(prohibitQuoteFlag) === 0){
            //         if (value) {
            //             return 'background-color:#fff;';
            //         }
            //         return 'background-color:#f8d594;';
            //     }
            // }
        },
        {
            field: 'taxTotalPrice',
            title: "行含税金额",
            width: 110,
            formatter: function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'noTaxTotalPrice',
            title: "行未税金额",
            width: 110,
            formatter: function (value) {
                return formatterPrice(value);
            }
        }
    ];
    var afterColumns = [

        // {
        //     field: 'taxCode',
        //     title: "税率",
        //     width: 200,
        //     editor: {
        //         type: 'combobox',
        //         options: {
        //             valueField: 'code',
        //             textField: 'codeWithDesc',
        //             panelHeight: '200',
        //             required: true,
        //             editable: false,
        //             data: getNecessaryDataList("pc/sys/tax/rest/listAll")
        //         }
        //     },
        //     formatter: function (value) {
        //         return getNecessaryDataName("pc/sys/tax/rest/listAll", value);
        //     }
        // },
        // {
        //     field: 'paymentMethod',
        //     title: '付款条件<button type="button" onclick="copy(\'paymentMethod\')" class="easyui-linkbutton">复制</button>',
        //     width: 200,
        //     editor: {
        //         type: 'combobox',
        //         options: {
        //             valueField: 'code',
        //             textField: 'codeWithDesc',
        //             panelHeight: '200',
        //             required: true,
        //             editable: false,
        //             data: getDictList("payment_method")
        //         }
        //     },
        //     formatter: function (value) {
        //         return getDicName("payment_method", value);
        //     }
        // },

        // {
        //     field: 'brand',
        //     title: '品牌',
        //     width: 100
        // },
        {
            field: 'invoiceType',
            title: '<span style="color: red">*</span>发票类型',
            width: 120,
            hidden: (templateCode !== 'PLATE_PRO_M002'),
            editor: {
                type: 'combobox',
                options: {
                    valueField: 'code',
                    textField: 'codeWithDesc',
                    panelHeight: 'auto',
                    required: 1,
                    editable: false,
                    disabled: (templateCode !== 'PLATE_PRO_M002'),
                    data: getDictList("invoice_type"),
                    prompt: '-- 请选择 --',
                }
            },
            formatter: function (value) {
                return getDicName("invoice_type", value);
            }
        },
        {
            field: 'remark',
            title: '备注',
            width: 120
        },
    ];

    loadSupplierTemplateFiled(templateCode, columns, afterColumns);

    var dataForm = $(el.form).outerHeight();
    var toolbar = [];
    // quoteType 报价类型；0-报价；1-议价；2查看
    if (quoteType===0){
        toolbar = [
            {
                text: '导出报价模板',
                iconCls: 'icon-download',
                handler: function () {
                    window.open(g.ctx + 'pc/inquiry/supplier/quote/rest/quote/export?inquiryId=' + $(el.inquiryId).val())
                }
            }, "-",
            {
                text: '导入报价信息',
                iconCls: 'icon-import',
                handler: function () {
                    $("#materialUpload .filebox-label").click();
                }
            }
        ];
    }else if (quoteType===1){
        toolbar = [
            {
                text: '导出议价模板',
                iconCls: 'icon-download',
                handler: function () {
                    window.open(g.ctx + 'pc/inquiry/supplier/quote/rest/quote/export?inquiryId=' + $(el.inquiryId).val())
                }
            }, "-",
            {
                text: '导入议价信息',
                iconCls: 'icon-import',
                handler: function () {
                    $("#materialUpload .filebox-label").click();
                }
            }
        ];
    }

    $(el.tb).datagrid({
        iconCls: 'icon-list',
        title: BJGL.BJGL__DBJWL,
        loadMsg: ALLCOMMON.LOADING,
        url: g.ctx + 'pc/inquiry/supplier/quote/rest/quote/foot/list',
        height: el.bodyHeight - dataForm - 60,
        singleSelect: true,
        pagination: false,
        showFooter: true,
        rownumbers: true,
        queryParams: {
            inquiryId: $(el.inquiryId).val(),
            productGroupWithCategoryFlag:1
        },
        frozenColumns: [frozenColumns],
        columns: [columns],
        toolbar: toolbar,
        onClickRow: function (index, rowData) {
            el.clickRowIndex = index;
            var costFlag = rowData.costFlag;
            var taxPrice =  $(el.tb).datagrid('getColumnOption', 'taxPrice');
            if (costFlag===1){
                taxPrice.editor = {
                };
            }else{
                taxPrice.editor = {
                    type: 'numberbox',
                    options: {
                        editable: true,
                        min: 0,
                        precision: priceHandle.precision,

                    }
                };
            }

            //如果议价
            if ((inquirySupplierStatus===2||inquirySupplierStatus===6)&&Number(rowData.bargainFlag) !== 0) {
                onClickRow(index, rowData);
                combboxBindEvent(index);
            }

            if (inquirySupplierStatus===1||inquirySupplierStatus===3) {
                onClickRow(index, rowData);
                combboxBindEvent(index);
            }

        },
        rowStyler: function (index, row) {
            //如果议价
            if ((inquirySupplierStatus===2||inquirySupplierStatus===6)&&Number(row.bargainFlag) === 0) {
                return 'background-color:#d9d9d9;color:#fff;';
            }
            //如果不允许报价
            if (Number(row.productGroupWithCategoryFlag) === 0){
                return 'background-color:#d9d9d9;color:#fff;';
            }
        },
        onLoadSuccess: function () {
            $(".note").tooltip(
                {
                    onShow: function(){
                        $(this).tooltip('tip').css({
                            width:'200',
                            boxShadow: '1px 1px 3px #292929'
                        });
                    }
                }
            );
            rowTaxPrice();
            calculationAmount();
        }
    });
}


function materialSupplierImport() {
    var filebox = $(el.materialFileInput).filebox("files");
    if (filebox.length === 1) {
        var formData = new FormData();
        formData.append("file", filebox[0]);
        formData.append("inquiryId", $(el.inquiryId).val());
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/inquiry/supplier/quote/rest/quote/import',
            data: formData,
            type: 'post',
            contentType: false,
            processData: false,
            success: function (list) {
                $(el.materialFileInput).filebox("reset");
                $(el.materialFileInput).filebox("setValue","");
                console.log(list)
                var rows = $(el.tb).datagrid("getRows");
                var rowNum = [];
                $.each(rows, function (index, item) {
                    $.each(list, function (dataIndex, data) {
                        if (item.id === data.id){
                            var rowIndex = $(el.tb).datagrid("getRowIndex", item);
                            //如果是成本报价，不允许导入含税单价
                            if (Number(item.costFlag) === 1) {
                                rowNum.push(rowIndex+1)
                                delete data.taxPrice;
                            }
                            //排除更新固定列
                            delete data.materialCode;
                            delete data.materialName;
                            delete data.productName;
                            delete data.materialSpec;
                            delete data.brand;
                            delete data.remark;
                            $.each(tmpData.supplierLookField, function (FieldIndex, field) {
                                delete data[field];
                            });
                            $.each(tmpData.supplierNotAllowEditField, function (FieldIndex, field) {
                                delete data[field];
                            });
                            if (Number(item.productGroupWithCategoryFlag) === 1) {
                                if (data.stagePrice1&&!data.taxPrice){
                                    data.taxPrice = data.stagePrice1;
                                }
                                $(el.tb).datagrid("updateRow", {index: rowIndex, row: data});
                                rowTaxPrice();
                                calculationAmount();
                            }
                        }
                    });
                });
                if (rowNum.length>0){
                    parent.layer.alert('第'+rowNum.join('、')+'行为成本报价，无法导入含税单价，请手动填写', {
                        icon: 1,
                        shadeClose: true,
                        title: '导入成功'
                    });
                }else {
                    topWin.layer.msg('导入成功', {icon: 1});
                }
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                $(el.materialFileInput).filebox("reset");
                $(el.materialFileInput).filebox("setValue","");
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        })
    }
}

/**
 * 含税单价和税率改变监听
 * @param rowIndex
 */
function combboxBindEvent(rowIndex) {
    var ed = $(el.tb).datagrid('getEditor', {index: rowIndex, field: 'taxPrice'});
    if (ed) {
        $(ed.target.next().find("input")).bind("blur", function () {
            endEditing();
            rowTaxPrice();
            calculationAmount();
        });
    }

    var edTax = $(el.tb).datagrid('getEditor', {index:rowIndex,field:'taxCode'});
    if (edTax) {
        $(edTax.target.next().find("input")).bind("blur", function(){
            endEditing();
            rowTaxPrice();
            calculationAmount();
        });
    }
}

/**
 * 加载供应商询价模板设置字段
 *
 * @param templateCode 询价模板编码
 * @param fieldGroup 模板字段分组；0-基础字段；1-基础扩展；2-阶梯报价；3-自定义扩展字段
 * @param existColumns 固定列
 * @param afterColumns 追加列
 */
function loadSupplierTemplateFiled(templateCode,existColumns,afterColumns){
    var loading = top.layer.msg('加载中', {icon: 16, shade: [0.1, '#000'], time: false});
    // 先从afterColumns中提取发票类型列，并移除原位置的该列
    let invoiceTypeColumn = null;
    let invoiceTypeIndex = -1;
    for (let i = 0; i < afterColumns.length; i++) {
        if (afterColumns[i].field === 'invoiceType') {
            invoiceTypeColumn = afterColumns[i];
            invoiceTypeIndex = i;
            break;
        }
    }
    // 移除原afterColumns中的发票类型列
    if (invoiceTypeIndex !== -1) {
        afterColumns.splice(invoiceTypeIndex, 1);
    }
    $.ajax({
        url: g.ctx + 'pc/inquiry/template/rest/getSupplierFieldByTemplateCode',
        type: 'GET',
        data: {templateCode: templateCode},
        async: false,
        complete: function() {
            top.layer.close(loading);
        },
        success: function (data) {
            if (data){
                tmpData.templateFieldData = [];
                //先加载供应商可见但不可编辑的列
                for (let i = 0; i < data.length; i++) {
                    let item = data[i];
                    if (item.supplierLookFlag===1){
                        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 (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 (item.allowEditFlag===0){

                        tmpData.supplierNotAllowEditField.push(item.fieldName);
                    }
                }
                //如果报价类型为议价或查看，则追加期望价格和议价意见
                if (quoteType!==0){
                    // existColumns.push({
                    //     field: 'desirePrice',
                    //     title: '期望价格',
                    //     width: 60,
                    //     formatter: function (value) {
                    //         if (value) {
                    //             return '<span style="color:red;">' + value + '</span>';
                    //         }
                    //         return '';
                    //     }
                    // });
                    existColumns.push({
                        field: 'priceOpinion',
                        title: '议价意见',
                        width: 170
                    });
                }
                for (let i = 0; i < data.length; i++) {
                    let item = data[i];
                    if (item.supplierLookFlag===0){
                        tmpData.templateFieldNameData.push(item.fieldName);
                        let title = (item.required === 1&&!lookFlag?'<span style="color:red">*</span>':'')
                            +(item.fieldAlias?item.fieldAlias:item.labelName)
                            +(item.copyFlag&&!lookFlag?'<button type="button" onclick="copy(\'' + item.fieldName + '\')" class="easyui-linkbutton">复制</button>':'')

                        let editor = {};
                        if (item.fieldType === 'dict'){
                            initDict(item.dictTypeCode);
                        }
                        if (item.fieldType === 'data'){
                            initNecessaryDatas(item.sqlSentence);
                        }
                        if (!lookFlag){
                            if (item.fieldType === 'varchar'&&item.allowEditFlag===1){
                                editor = {
                                    type: 'textbox',
                                    editable: true,
                                    // required:item.required === 1,
                                }
                            }else if (item.fieldType === 'init'&&item.allowEditFlag===1){
                                editor = {
                                    type: 'numberbox',
                                    options: {
                                        editable: true,
                                        panelHeight: 'auto',
                                        min:0,
                                        precision:0
                                    }
                                }
                            }else if (item.fieldType === 'number'&&item.allowEditFlag===1){
                                editor = {
                                    type: 'numberbox',
                                    options: {
                                        editable: true,
                                        panelHeight: 'auto',
                                        min:0,
                                        // required:item.required === 1,
                                        precision:2
                                    }
                                }
                            }else if (item.fieldType === 'decimal'&&item.allowEditFlag===1){
                                editor = {
                                    type: 'numberbox',
                                    options: {
                                        editable: true,
                                        panelHeight: 'auto',
                                        min:0,
                                        precision:priceHandle.precision
                                    }
                                }
                            }else if (item.fieldType === 'date'&&item.allowEditFlag===1){
                                editor = {
                                    type: 'datebox',
                                    options: {
                                        editable: false,
                                        panelHeight: 'auto',
                                        // required:item.required === 1
                                    }
                                }
                            }else if (item.fieldType === 'dateTime'&&item.allowEditFlag===1){
                                editor = {
                                    type: 'datetimebox',
                                    options: {
                                        editable: false,
                                        panelHeight: 'auto',
                                        // required:item.required === 1
                                    }
                                }
                            }else if (item.fieldType === 'dict'&&item.allowEditFlag===1){

                                editor = {
                                    type: 'combobox',
                                    options: {
                                        data: getDictList(item.dictTypeCode),
                                        editable: true,
                                        limitToList: 'true',
                                        panelHeight: 'auto',
                                        // required:item.required === 1,
                                        prompt: '-- 请选择 --',
                                        method: 'GET',
                                        valueField: 'code',
                                        textField: 'codeWithDesc',
                                    }
                                }
                            }else if (item.fieldType === 'data'&&item.allowEditFlag===1){
                                editor = {
                                    type: 'combobox',
                                    options: {
                                        url: g.ctx + item.sqlSentence,
                                        editable: true,
                                        limitToList: 'true',
                                        panelHeight: 'auto',
                                        // required:item.required === 1,
                                        prompt: '-- 请选择 --',
                                        method: 'GET',
                                        valueField: 'code',
                                        textField: 'codeWithDesc',
                                    }
                                }
                            }else {
                                editor = {}
                            }
                        }
                        existColumns.push({
                            field: item.fieldName,
                            title: title,
                            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 === 'decimal') {
                                    return formatterPrice(value);
                                }
                                if (value&&item.fieldType === 'dict') {
                                    return getDicName(item.dictTypeCode,value)
                                }
                                if (value&&item.fieldType === 'data') {
                                    return getNecessaryDataName(item.sqlSentence,value)
                                }
                                if (!lookFlag&&item.fieldType === 'files') {
                                    return '<a href="#" onclick="uploadFilesDialog(this)" data-index="' + rec + '" data-value="' + value + '">上传/下载</a>';
                                }
                                if (lookFlag&&item.fieldType === 'files') {
                                    return '<a href="#" onclick="uploadFilesDialog(this)" data-index="' + rec + '" data-value="' + value + '">查看</a>';
                                }
                                return value;
                            },
                            editor:editor
                        });
                        tmpData.templateFieldData.push({
                            fieldName: item.fieldName,
                            labelName: item.fieldAlias?item.fieldAlias:item.labelName,
                            required: item.required,
                            fieldId: item.fieldId,
                            fieldType: item.fieldType
                        });
                    }
                }
                // ===== 核心改动：将发票类型列插入到税率列前面 =====
                if (invoiceTypeColumn) {
                    // 查找税率列（taxCode）在existColumns中的索引
                    let taxCodeIndex = -1;
                    for (let i = 0; i < existColumns.length; i++) {
                        if (existColumns[i].field === 'taxCode') {
                            taxCodeIndex = i;
                            break;
                        }
                    }
                    // 如果找到税率列，插入到它前面；否则追加到existColumns末尾
                    if (taxCodeIndex !== -1) {
                        existColumns.splice(taxCodeIndex, 0, invoiceTypeColumn);
                    } else {
                        existColumns.push(invoiceTypeColumn);
                    }
                }

                // 追加剩余的afterColumns（如备注）
                existColumns.push.apply(existColumns,afterColumns)
            }
        },
        error: function (data) {
            layer.alert(JSON.parse(data.responseText).message);
        }
    });
}

/**
 * 计算行含税金额
 */
function rowTaxPrice() {
    var rows = $(el.tb).datagrid('getRows');
    for (var i = 0 ; i <  rows.length ; i ++){
        if (rows[i].taxPrice) {
            //算未税
            var noTaxPrice = getTaxPrice(rows[i].taxCode,rows[i].taxPrice,0,priceHandle.precision,priceHandle.cutType);
            $(el.tb).datagrid('updateRow', {
                index: i,
                row: {
                    noTaxPrice: noTaxPrice,
                    taxTotalPrice: new BigNumber(rows[i].taxPrice).multipliedBy(new BigNumber(rows[i].purchaseNum)).decimalPlaces(priceHandle.precision, priceHandle.cutType===0?BigNumber.ROUND_HALF_UP:BigNumber.ROUND_DOWN).toNumber(),
                    noTaxTotalPrice: new BigNumber(noTaxPrice).multipliedBy(new BigNumber(rows[i].purchaseNum)).decimalPlaces(priceHandle.precision, priceHandle.cutType===0?BigNumber.ROUND_HALF_UP:BigNumber.ROUND_DOWN).toNumber(),
                }
            });
        }
    }

}

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)
        },
    });
}

function calculationAmount(){
    var rows = $(el.tb).datagrid('getRows');
    var taxTotalPrice =  new BigNumber(0);
    var noTaxTotalPrice =  new BigNumber(0);
    for (var i = 0 ; i <  rows.length ; i ++){
        taxTotalPrice = new BigNumber(taxTotalPrice).plus(rows[i].taxTotalPrice).decimalPlaces(priceHandle.precision, priceHandle.cutType===0?BigNumber.ROUND_HALF_UP:BigNumber.ROUND_DOWN).toNumber()
        noTaxTotalPrice = new BigNumber(noTaxTotalPrice).plus(rows[i].noTaxTotalPrice).decimalPlaces(priceHandle.precision, priceHandle.cutType===0?BigNumber.ROUND_HALF_UP:BigNumber.ROUND_DOWN).toNumber()
    }
    // 更新页脚行的值并刷新
    var footers = $(el.tb).datagrid('getFooterRows');
    // 结算税额
    footers[0]['taxTotalPrice'] = taxTotalPrice;
    footers[0]['noTaxTotalPrice'] = noTaxTotalPrice;
    // footers[0]['material_code'] = '<b>合计</b>';
    footers[0]['remark'] = '';
    $(el.tb).datagrid('reloadFooter');
}
/**
 * 成本报价
 */
function costQuote(index,lookFlag){
    var row = $(el.tb).datagrid('getRows')[index];
    if (Number(row.productGroupWithCategoryFlag) === 0){
        return false;
    }
    // 当前成本报价的物料信息
    el.costQuoteMaterial.materialCode = row.materialCode;
    el.costQuoteMaterial.materialName = row.materialName;
    el.costQuoteMaterial.taxTotalPrice = row.taxPrice;
    var buttons = [];
    if (lookFlag===0){
         buttons = [
            {
                text: BJGL.BJGL__BC,
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['costQuoteDialog'].saveCostQuote(function (data) {
                        el.costQuoteData[row.id] = data.rows;
                        updateCostBaoJia(index, data.taxTotalPrice);
                        costQuoteDialog.dialog('close');
                    });
                }
            },
            {
                text: BJGL.BJGL__GB,
                iconCls: 'icon-cancel',
                handler: function () {
                    costQuoteDialog.dialog('close');
                }
            }
        ];
    }else {
        buttons = [
            {
                text: BJGL.BJGL__GB,
                iconCls: 'icon-cancel',
                handler: function () {
                    costQuoteDialog.dialog('close');
                }
            }
        ];
    }
    var costQuoteDialog = openDialog('costQuoteDialog', g.ctx + "pc/inquiry/supplier/cost/quote/detail/dialog?inquiryMaterialSupplierId="+row.id+"&lookFlag="+lookFlag+"&parentFrameName=quoteDialog"+"&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: buttons
    });
}

/**
 * 阶梯报价
 */
function stageQuote(index,lookFlag){
    accept();
    var row = $(el.tb).datagrid('getRows')[index];
    if (Number(row.productGroupWithCategoryFlag) === 0){
        return false;
    }
    el.stageQuoteData[row.id] = row;
    var buttons = [];
    if (lookFlag===0){
        buttons = [
            {
                text: BJGL.BJGL__BC,
                iconCls: 'icon-save',
                handler: function () {
                    topWin.frames['stageQuoteDialog'].saveStageQuote(function (data) {
                        $(el.tb).datagrid('updateRow', {
                            index: index,
                            row: {
                                //算未税
                                noTaxPrice: Number(row.costFlag)===1?row.noTaxPrice:getTaxPrice(row.taxCode,data.stagePrice1,0,precision,cutType),
                                taxPrice: Number(row.costFlag)===1?row.taxPrice:data.stagePrice1,
                                stageNum1: data.stageNum1,
                                stageNum2: data.stageNum2,
                                stageNum3: data.stageNum3,
                                stageNum4: data.stageNum4,
                                stageNum5: data.stageNum5,
                                stagePrice1: data.stagePrice1,
                                stagePrice2: data.stagePrice2,
                                stagePrice3: data.stagePrice3,
                                stagePrice4: data.stagePrice4,
                                stagePrice5: data.stagePrice5
                            }
                        });
                        rowTaxPrice();
                        calculationAmount();
                        el.stageQuoteData[row.id] = data;
                        stageQuoteDialog.dialog('close');
                    });
                }
            },
            {
                text: BJGL.BJGL__GB,
                iconCls: 'icon-cancel',
                handler: function () {
                    stageQuoteDialog.dialog('close');
                }
            }
        ];
    }else {
        buttons = [
            {
                text: BJGL.BJGL__GB,
                iconCls: 'icon-cancel',
                handler: function () {
                    stageQuoteDialog.dialog('close');
                }
            }
        ];
    }
    var stageQuoteDialog = openDialog('stageQuoteDialog', g.ctx + "pc/inquiry/supplier/quote/stage/quote/dialog?templateCode="+$(el.templateCode).val()+"&lookFlag="+lookFlag+"&parentFrameName=quoteDialog&inquiryMaterialSupplierId="+row.id, {
        title: BJGL.BJGL__JTBJ,
        width: '900px',
        height: '70%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            stageQuoteDialog.dialog('destroy');
        },
        buttons: buttons
    });
}

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

/**
 * 更新物料的成本报价
 *
 * @param rowIndex 更新的行索引
 * @param taxTotalPrice 结果
 */
function updateCostBaoJia(rowIndex, taxTotalPrice) {
    accept();
    $(el.tb).datagrid('updateRow', {
        index: rowIndex,
        row: {
            taxPrice: taxTotalPrice,
            remark: ''
        }
    });
    rowTaxPrice();
    calculationAmount();
}

/**
 * 提交所有从加载或者上一次调用acceptChanges函数后更改的数据
 */
function accept() {
    if (endEditing()) {
        $(el.tb).datagrid('acceptChanges');
    }
}

/**
 * 单击行，启用行编辑
 *
 * @param index 单击的行索引
 * @param rowData 行数据
 */
function onClickRow(index, rowData) {
    if (Number(rowData.productGroupWithCategoryFlag) === 0){
        topWin.layer.alert('该项为非供应商品类对应物料组的物料，不允许报价',{icon: 2, shadeClose: true, title: '温馨提示'});
        return false;
    }
    var prohibitQuoteFlag = rowData.prohibitQuoteFlag;

    if (Number(prohibitQuoteFlag) === 0) {
        // if (isRequireCost === 1 || isStagePrice === 1) {
        //     sup_quote.editor = {};
        // } else {
        //     sup_quote.editor = {readonly: true, type: 'numberbox', options: {min: 0, precision: 4}};
        // }

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

}

/**
 * 获取成本报价数据
 *
 * @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;
}

/**
 * 结束行编辑
 *
 * @return {boolean} 结果
 */
function endEditing() {
    if (el.editIndex === undefined) {
        return true
    }
    if ($(el.tb).datagrid('validateRow', el.editIndex)) {
        $(el.tb).datagrid('endEdit', el.editIndex);
        el.editIndex = undefined;
        rowTaxPrice();
        calculationAmount();
        return true;
    } else {
        return false;
    }
}

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

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

/**
 * 查看报价须知
 */
function viewNotes() {
    layer.open({
        title: '<<' + BJGL.BJGL__BJXZ + '>>',
        type: 2,
        scrollbar: false,
        move: false,
        area: ['90%', '70%'],
        content: g.ctx + 'pc/inquiry/supplier/quote/quote/note',
        btn: [BJGL.BJGL__TY, BJGL.BJGL__FH],
        yes: function (index) {
            document.getElementById('isView').checked = true;
            layer.close(index);
        }
    });
}

/**
 * 报价保存
 * @param call
 * @returns {boolean}
 */
function saveQuote(call){
    accept();
    var formData = {};
    formData.id = $(el.id).val();
    formData.supplierFormFiles = $(el.supplierFormFiles).attr('data-fileIds');
    let rows = $(el.tb).datagrid('getRows');
    if (!$(el.tb).datagrid('validateRow', el.editIndex)) {
        const ed = $(el.tb).datagrid('getEditor', {
            index: el.editIndex,
            field: 'invoiceType'
        });

        if (ed && !$(ed.target).combobox('isValid')) {
            layer.msg('报价物料第' + (el.editIndex + 1) + '行，发票类型不能为空');
            return false;
        }
    }
    //供应商是否报价标记，如果都没有报价不允许提交
    var quoteFlag = false;
    var costQuoteList = [];
    console.log(rows)
    var desireMsg = '';
    for (let i = 0 ; i < rows.length ; i ++){
        let flag = false, msg = "";
        if (tmpData.templateFieldData.length > 0 && Number(rows[i].productGroupWithCategoryFlag)===1) {
            $.each(tmpData.templateFieldData, function (index, target) {
                if (target.fieldType === 'number') {
                    if (!rows[i][target.fieldName] && String(rows[i][target.fieldName]) !== '0'&&target.required === 1) {
                        msg = '报价物料第' + (i + 1) + '行，' + target.labelName + '不能为空';
                        flag = true;
                        return false;
                    }
                }else {
                    if (!rows[i][target.fieldName]&&target.required === 1) {
                        msg = '报价物料第' + (i + 1) + '行，' + target.labelName + '不能为空';
                        flag = true;
                        return false;
                    }
                }

            });
            if (flag) {
                topWin.layer.alert(msg,{icon: 2, shadeClose: true, title: '温馨提示'});
                return false;
            }
        }
        if (rows[i].countryName==='america'&&!rows[i].eccn) {
            debugger
            topWin.layer.alert('报价物料第' + (i + 1) + '行，ECCN码不能为空',{icon: 2, shadeClose: true, title: '温馨提示'});
            return false;
        }
        console.log("模板代码："+$(el.templateCode).val());
        if($(el.templateCode).val() ==="default" ){
            if (!rows[i].countryName) {
                debugger
                topWin.layer.alert('报价物料第' + (i + 1) + '行，国系不能为空',{icon: 2, shadeClose: true, title: '温馨提示'});
                return false;
            }
        }
        if (rows[i].taxPrice) {
            quoteFlag = true;
        }
        if (rows[i].stagePrice1) {
            quoteFlag = true;
        }
        if (rows[i].currencyCode==='USD') {
            rows[i].logisticsAgencyFee = 0.3;
        }
        if (rows[i].stagePrice1&&!rows[i].taxPrice) {
            //算未税
            rows[i].taxPrice = rows[i].stagePrice1;
            rows[i].noTaxPrice = getTaxPrice(rows[i].taxCode,rows[i].stagePrice1,0,precision,cutType);
        }

        //如果是议价且有期望价格
        if (quoteType!==0&&rows[i].taxPrice&&rows[i].desirePrice&&rows[i].taxPrice>rows[i].desirePrice){
            desireMsg+='报价物料第' + (i + 1) + '行，含税单价大于期望价格<br>'
        }
        costQuoteList.push.apply(costQuoteList,el.costQuoteData[rows[i].id])
    }

    if (!quoteFlag) {
        topWin.layer.alert(BJGL.BJGL__DQWLMYRHBJXXBYXTJ,{icon: 2, shadeClose: true, title: '温馨提示'});
        return false;
    }
    if (!$(el.isView).is(':checked')) {
        topWin.layer.alert(BJGL.BJGL__CBJXZ,{icon: 2, shadeClose: true, title: '温馨提示'});
        return false;
    }
    var supplierFormFiles = $(el.supplierFormFiles).attr('data-fileIds');
    if (!supplierFormFiles) {
        topWin.layer.alert("请上传供应商附件",{icon: 2, shadeClose: true, title: '温馨提示'});
        return false;
    }
    //如果是议价中
    if (Number($(el.inquirySupplierStatus).val())===2&&$(el.oldSupplierFormFiles).val()){
        formData.supplierFormFiles = $(el.oldSupplierFormFiles).val()+','+$(el.supplierFormFiles).attr('data-fileIds');
    }
    formData.supplierFormRemark = $(el.supplierFormRemark).val();
    formData.inquiryMaterialSupplierList = rows;
    formData.costQuoteList = costQuoteList;

    if (desireMsg){
        layer.confirm(desireMsg+'是否继续报价？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            layer.closeAll()
            var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
            $.ajax({
                url: g.ctx + 'pc/inquiry/supplier/quote/rest/saveQuote',
                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: '温馨提示'});
                }
            });
            return false;
        }, function(){
            layer.closeAll()
            return false;
        });
    }else {
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/inquiry/supplier/quote/rest/saveQuote',
            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: '温馨提示'});
            }
        });
    }
}