$(function () {
    initDict('currency,po_type,contract_pay_boot_item,contractCategory,invoice_type,sign_order,sign_type,payment_way,payment_stage,contractContentLink,contract_item_subject,contract_item_subject_sap');
    initColumns();
    loadGrid();

});


function  initColumns() {

    $("#contractCover").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('contractContentLink')
    })


    //货币编码
    $("#contractCurrency").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('currency')
    })


    //发票类型
    $("#contractInvoiceCode").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('invoice_type')
    })


    //订单类型
    $("#contractOrderType").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('po_type')
    })


    //采购组织
    $("#contractPurchaseGroupCode").combobox({
        valueField: 'purchaseOrgCode',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseOrg/rest/listAll',
    });


    //采购组
    $("#contractPurchaseGroup").combobox({
        valueField: 'purchaseGroupCode',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll',
    });

    //付款方式
    $("#contractPaymentWay").combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('payment_way')
    });


    $("#contractAmount").textbox({
        onChange:function (newValue, oldValue) {
            $('#contractAmountCapital').textbox('setValue',number_chinese(newValue));
        }
    })


    $('#contractCompanyName').textbox({
        buttonText:'选择',
        iconCls:'icon-man',
        iconAlign:'left',
        onClickButton:function () {
            layer.open({
                title: "我方公司选择",
                type: 2,
                area: ['600px', '550px'],
                content: '/pc/contract/manage/page/choseSupplier?type=1',
                btn: ['选择','关闭'],
                yes: function (index, layero) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']];
                    var name = $(layero).find("iframe")[0].contentWindow.document.getElementById("name").value;
                    var code = $(layero).find("iframe")[0].contentWindow.document.getElementById("code").value;
                    if(name!=undefined&&code!=''){
                        $('#contractCompanyName').textbox('setValue',name);
                        $('#contractCompanyCode').val(code);
                        layer.close(index);
                    }else{
                        layer.alert("未选择",{icon:2})
                    }
                },
            });
        }
    });


    $('#contractSupplierName').textbox({
        buttonText:'选择',
        iconCls:'icon-man',
        iconAlign:'left',
        onClickButton:function () {
            layer.open({
                title: "供应商选择",
                type: 2,
                area: ['650px', '550px'],
                content: '/pc/contract/manage/page/choseSupplier?type=2',
                btn: ['选择','关闭'],
                yes: function (index, layero) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']];
                    var name = $(layero).find("iframe")[0].contentWindow.document.getElementById("name").value;
                    var code = $(layero).find("iframe")[0].contentWindow.document.getElementById("code").value;
                    if(name!=undefined&&code!=''){
                        $('#contractSupplierName').textbox('setValue',name);
                        $('#contractSupplierCode').val(code);
                        layer.close(index);
                    }else{
                        layer.alert("未选择",{icon:2})
                    }
                },
            });
        }
    });


    $('#contractSealType').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('sign_type')
    });


    $('#contractSignOrder').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: getDictList('sign_order')
    });


    $('#isMro').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: [
            {"code":1,"name":"是"},
            // {"code":2,"name":"否"}
        ],
        onSelect:function (d){
            let mro_flag = 0
            if(d.code == 1){
                mro_flag = 1
                $("#tbdsetMro").hide();
                $("#tbdsetOrder").show();
                $("#mroDisplay").text('MRO数据展示');
            }else{
                $("#tbdsetMro").show();
                $("#tbdsetOrder").hide();
                $("#mroDisplay").text('数据展示');
            }

            $.ajax({
                url: '/pc/contract/manage/rest/getContractCategory',
                type: 'POST',
                async: false,
                data: {"mroFlag":mro_flag},
                success: function (res) {
                    $("#contractType").combobox({
                        valueField: 'code',
                        textField: 'name',
                        editable: false,
                        panelHeight: 'auto',
                        data: res
                    })
                },
                error: function (res) {
                    topWin.layer.alert(res.responseJSON.message, {icon: 2});
                }
            })
        }
    });


    $('#isSap').combobox({
        valueField: 'code',
        textField: 'name',
        panelHeight: 'auto',
        editable: false,
        data: [
            {"code":1,"name":"是"},
            {"code":2,"name":"否"}
        ], onLoadSuccess: function () {
            var id = $("#id").val();
            if (id == '') {
                $("#isSap").combobox('select',1);
            }
        }
    });


    $('#associationContract').textbox({
        buttonText:'选择',
        iconAlign:'left',
        onClickButton:function () {
            layer.open({
                title: "合同选择",
                type: 2,
                area: ['650px', '550px'],
                content: '/pc/contract/manage/page/choseContract',
                btn: ['选择','关闭'],
                yes: function (index, layero) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = window[layero.find('iframe')[0]['name']];
                    var name = $(layero).find("iframe")[0].contentWindow.document.getElementById("name").value;
                    var code = $(layero).find("iframe")[0].contentWindow.document.getElementById("code").value;
                    if(name!=undefined&&code!=''){
                        $('#associationContract').textbox('setValue',code);
                        layer.close(index);
                    }else{
                        layer.alert("未选择",{icon:2})
                    }
                },
            });
        }
    });


    var newValue = $("#contractAmount").numberbox('getValue');
    if(newValue){
        $('#contractAmountCapital').textbox('setValue',number_chinese(newValue));
    }

}


function loadGrid(){

    let check = $("#check").val();

    var toolbar = [];
    if(check==1){
        toolbar = [
            {
                text: '新增',
                id: 'btn_add',
                iconCls: 'icon-add',
                handler: function () {
                    addPay();
                }
            },
            {
                text: '编辑',
                id: 'btn_edit',
                iconCls: 'icon-edit',
                handler: function () {
                    editPay();
                }
            },
            {
                text: '删除',
                id: 'btn_order',
                iconCls: 'icon-filter',
                handler: function (d) {
                    delPay();
                }
            },
        ];
    }


    //加载列表数据
    $("#table_pay").datagrid({
        iconCls: 'icon-list',
        url: '/pc/contract/manage/rest/selectPayListPage?conId='+$("#id").val(),
        height: 350,
        fitColumns:true,
        singleSelect: true,
        pagination: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        striped: true,
        page: 1,
        pageSize: 10,
        toolbar: toolbar,
        columns: [[
            {field: 'paymentStage', title: '付款阶段',width:'120',
                exportEnum:getDictList('payment_stage'),
                formatter: function (value) {
                    return getDicName('payment_stage',value);
                }},
            {field: 'paymentTime', title: '付款日期',width:'120',
                formatter: function (value) {
                    if (!value) {
                        return;
                    }
                    return moment(new Date(value)).format('YYYY-MM-DD');
                }},
            {field: 'paymentRatio', title: '付款比例',width:'120'},
            {field: 'paymentAmount', title: '付款金额',width:'120'},
           /* {field: 'paymentAlreadyAmount', title: '已付款金额',width:'120'},*/
            {field: 'remark', title: '付款描述',width:'220'},
        ]] ,
    });


    var columns = [
        {field: 'subjectCode', title: '科目<button type="button" onclick="copy(\'subjectCode\')" class="easyui-linkbutton">复制</button>',width:'120',
            formatter: function (value, row) {
                if($("#isSap").textbox('getValue') == 1){
                    return getDicName('contract_item_subject_sap',value)
                }else{
                    return getDicName('contract_item_subject',value)
                }

            }},
        //{field: 'materialCode', title: '物料编码',width:'120'},
        {field: 'materialName', title: '物料名称',width:'120'},
        {field: 'materialSpec', title: '详细规格参数',width:'120'},
        {field: 'warrantyPeriod', title: '质保期(月)',width:'120'},
        {field: 'materialBrand', title: '品牌',width:'120'},
        // {field: 'materialGroupCode', title: '物料组编码',width:'120',hidden:true},
        {field: 'materialGroupName', title: '物料组',width:'120'},
        {field: 'materialCategory', title: '品类',width:'120'},
        //{field: 'materialSpec/materialModel/materialBrand', title: '规格/型号/品牌',width:'120',hidden:true},
        // {field: 'materialSpec', title: '规格',width:'120',hidden:true},
        // {field: 'materialModel', title: '型号',width:'120',hidden:true},
        // {field: 'materialBrand', title: '品牌',width:'120',hidden:true},
        {field: 'basisUnit', title: '单位',width:'120 '},
        {field: 'price', title: '单价',width:'120 ' },
        {field: 'num', title: '数量',width:'120'},
        {field: 'amount', title: '总金额',width:'120',formatter: function (value, row) {
                if (row.price !=null && row.num) {
                    return (parseFloat(row.price) * parseFloat(row.num)).toFixed(2);
                }
            }},
        // {field: 'taxRateCode', title: '税码',width:'120',hidden:true},
        // {field: 'currencyCode', title: '币别',width:'120',hidden:true},
        {field: 'purchaseCode', title: '采购申请单编码',width:'260'},
        {field: 'costCenterName', title: '成本中心',width:'220'},
        {field: 'teamName', title: '请购部门',width:'220'},
        {field: 'requireName', title: '请购人',width:'120'},
        // {field: 'itemCode', title: '采购申请行号',width:'120',hidden:true},
        // {field: 'factoryCode', title: '工厂编码',width:'120',hidden:true},
        {field: 'factoryName', title: '工厂名称',width:'220'},
        // {field: 'customerCode', title: '服务客户代码',width:'120',hidden:true},
        {field: 'customerName', title: '服务客户名称',width:'120'},
        {field: 'driverAsset', title: '驱动因素',width:'120',
            formatter: function (value, row) {
                return getDicName('contract_pay_boot_item',value)

            }},
        {field: 'taxRateName', title: '税率',width:'120'},
        {field: 'cardNumber', title: '固定资产卡号',width:'120'},
        {field: 'bz', title: '备注',width:'200'},
    ] ;

    var columnsMro = [
        {field: 'name', title: '文件名称',width:'120'},
        {field: 'num', title: '份数',width:'120'},
        {field: 'signTime', title: '签约日期',width:'120'},
        {field: 'ourPeople', title: '我方负责人',width:'120'},
        {field: 'otherPeople', title: '对方负责人',width:'120 '},
        {field: 'amount', title: '合同金额',width:'120 ' },
        {field: 'fileName', title: '附件',width:'120'},
    ] ;

    $("#table_tb").datagrid({
        iconCls: 'icon-list',
        //url: '/pc/contract/manage/rest/selectContractDetailListPage?conId='+$("#id").val(),
        data: eval(items),
        height: 350,
        fitColumns:true,
        singleSelect: true,
        pagination: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        striped: true,
        page: 1,
        pageSize: 10,
        toolbar: [
            {
                text: '新增',
                id: 'btn_add',
                iconCls: 'icon-add',
                handler: function () {
                    addDetail();
                }
            },
            {
                text: '编辑',
                id: 'btn_edit',
                iconCls: 'icon-edit',
                handler: function () {
                    editDetail();
                }
            },
            {
                text: '删除',
                id: 'btn_del',
                iconCls: 'icon-remove',
                handler: function (d) {
                    delDetail();
                }
            },
        ],
        columns: [columns] ,

    });


    $("#table_mro").datagrid({
        iconCls: 'icon-list',
        url: '/pc/contract/manage/rest/selectContractMroListPage?conId='+$("#id").val(),
        height: 350,
        fitColumns:true,
        singleSelect: true,
        pagination: true,
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        striped: true,
        page: 1,
        pageSize: 10,
        toolbar: [
            {
                text: '新增',
                id: 'btn_add',
                iconCls: 'icon-add',
                handler: function () {
                    addDetailMro();
                }
            },
            {
                text: '删除',
                id: 'btn_del',
                iconCls: 'icon-remove',
                handler: function (d) {
                    delDetailMro();
                }
            },
        ],
        columns: [columnsMro] ,

    });

}
function copy(type) {
    let allRows = $('#table_tb').datagrid('getRows');
    for (let i = 0; i < allRows.length; i++) {
        $('#table_tb').datagrid('updateRow', {
            index: i,
            row: {
                [type]: allRows[0][type]
            }
        });
    }
}
/**
 * 将金额转化为大写的方法
 * @param str 金额
 * @return {string} 汉字大写
 */
function number_chinese(str) {
    let num = parseFloat(str);
    let strOutput = "",
        strUnit = '仟佰拾亿仟佰拾万仟佰拾元角分';
    num += "00";
    let intPos = num.indexOf('.');
    if (intPos >= 0) {
        num = num.substring(0, intPos) + num.substr(intPos + 1, 2);
    }
    strUnit = strUnit.substr(strUnit.length - num.length);
    for (let i = 0; i < num.length; i++) {
        strOutput += '零壹贰叁肆伍陆柒捌玖拾'.substr(num.substr(i, 1), 1) + strUnit.substr(i, 1);
    }
    return strOutput.replace(/零角零分$/, '整').replace(/零[仟佰拾]/g, '零')
        .replace(/零{2,}/g, '零').replace(/零([亿|万])/g, '$1')
        .replace(/零+元/, '元').replace(/亿零{0,3}万/, '亿')
        .replace(/^元/, "零元")
}


function submitContractForm(type,call){
    let isMro = $("#isMro").combobox('getValue');
    let b ;
    let rows = $('#table_pay').datagrid('getRows');
    let rowsTableTb = $('#table_tb').datagrid('getRows');
    //新增判断如果mro合同，则校验两个明细表都要必填，非mro合同时合同数据必填
    if(isMro === "1"){//mro
        //table_tb  table_pay rowsTableTb rows明细对象

        if (rowsTableTb.length === 0) {
            // DataGrid明细表为空
            console.log('table_tb为空');
            topWin.layer.msg("明细数据展示列表不能为空！");
            return false;
        }
        if (rows.length === 0 ) {
            // DataGrid明细表为空
            console.log('table_pay为空');
            topWin.layer.msg("付款阶段明细表不能为空！");
            return false;
        }
    }
    let totalAmoutnt = 0;
    //保存前重新计算价格数据
    // 明细表
    if(rowsTableTb && rowsTableTb.length>0) {
        for (var i = 0; i < rowsTableTb.length; i++) {
            totalAmoutnt = totalAmoutnt + parseFloat(rowsTableTb[i].price * rowsTableTb[i].num);//明细数据金额计算
        }
        $("#contractAmount").textbox('setValue', totalAmoutnt.toFixed(2));// 合同金额小写
        $('#contractAmountCapital').textbox('setValue', number_chinese(totalAmoutnt.toFixed(2)));
    }
    //付款阶段表
    let je = new BigNumber(0);
    if(rows && rows.length>0) {

        let bl = 0;
        rows.forEach(function (v,n) {
            bl += parseFloat(v.paymentRatio);
        });
        console.log('paymentRatio',bl.toFixed(2));
        if(parseFloat(bl.toFixed(2))>1 || parseFloat(bl.toFixed(2))<1){
            topWin.layer.alert("付款比例总和不为1",{icon:2});
            return ;
        }
        for (var i = 0; i < rows.length; i++) {
            rows[i].paymentAmount = new BigNumber(rows[i].paymentRatio).multipliedBy( new BigNumber(totalAmoutnt)).decimalPlaces(2,  BigNumber.ROUND_HALF_UP)   ;
            console.log('paymentAmount',rows[i].paymentAmount);
            if(i< rows.length-1){
                je = je.plus(new BigNumber(rows[i].paymentAmount) );
            }
        }
        // 最后一行 = 总金额 - 前 N-1 项和
        rows[rows.length - 1].paymentAmount = new BigNumber(totalAmoutnt).minus(je)
            .decimalPlaces(2, BigNumber.ROUND_HALF_UP);
        console.log('总和totalAmoutnt',new BigNumber(totalAmoutnt));
        console.log('最后一行paymentAmount',rows[rows.length - 1].paymentAmount);
        rows.forEach(function (v,n) {
            $("#table_pay").datagrid('updateRow',{index:n,row:rows[n]})
            $('#table_pay').datagrid('refreshRow',n);
        });

    }
    let formData = $("#form").serializeJson();
    let dlist = JSON.stringify(rows);
    let rowsTableTblist = JSON.stringify(rowsTableTb);
    formData.contractState = type ;
    var attachData1 = $("#contractFiles").attr('data-fileIds')
    if(!attachData1){
        topWin.layer.alert('请上传合同附件!', {icon: 0});
        return false;
    }
    formData.contractFiles = attachData1;
    var attachData2 = $("#contractSignFiels").attr('data-fileIds')
    formData.contractSignFiels = attachData2
    formData.dlist = dlist;
    formData.rowsTableTblist = rowsTableTblist;
    if ($("#form").form('validate')) {
        $.ajax({
            url: '/pc/contract/manage/rest/form/save',
            type: 'POST',
            async: false,
            data: formData,
            success: function (res) {
                topWin.layer.alert("保存成功!", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    call()
                });
            },
            error: function (res) {
                topWin.layer.alert(res.responseJSON.message, {icon: 2});
            }
        });
    }
    return b ;
}


function addPay(){

    var addPayDialog = openDialog('addPay', g.ctx+'pc/contract/manage/page/formPay?conId='+$("#id").val()+"&payId=", {
        title: '编辑',
        width: '550px',
        height:'70%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            addPayDialog.dialog('destroy');
        },
        buttons: [
            {
                text:'保存',
                iconCls:'icon-save',
                handler:function() {
                    topWin.frames['addPay'].savePayDetail(function (data) {

                        var d = $("#table_pay").datagrid('getRows');
                        let je = new BigNumber(0);
                        let bl = 0;
                        d.forEach(function (v,n) {
                            bl += parseFloat(v.paymentRatio);
                        });
                        if((parseFloat(bl.toFixed(2))+parseFloat(data.paymentRatio))>1){
                            topWin.layer.alert("付款比例超出",{icon:2});
                            return ;
                        }else{
                            let contractAmount = $("#contractAmount").textbox('getValue');
                            data.paymentAmount = new BigNumber(data.paymentRatio).multipliedBy( new BigNumber(contractAmount)).decimalPlaces(2,  BigNumber.ROUND_HALF_UP)   ;
                            $("#table_pay").datagrid('appendRow',data);
                            d = $("#table_pay").datagrid('getRows');
                            d.forEach(function (v,n) {
                                je = new BigNumber(je).plus(new BigNumber(v.paymentAmount) );
                                //v.paymentAlreadyAmount = je.toFixed(4)  ;
                                $("#table_pay").datagrid('updateRow',{index:n,row:d[n]})
                                $('#table_pay').datagrid('refreshRow',n);
                            });

                            addPayDialog.dialog('close');
                            $('#tb').datagrid('reload');
                        }
                    });
                }
            },
            {
                text:'关闭',
                iconCls:'icon-cancel',
                handler:function() {
                    addPayDialog.dialog('close');
                }
            }
        ]
    });

}


function editPay(){

    let row = $("#table_pay").datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return;
    }
    let indexRow = $("#table_pay").datagrid('getRowIndex',row);
    var editPayDialog = openDialog('editPay', '/pc/contract/manage/page/formPay?conId='+$("#id").val()+"&rowId="+row.id+"&paymentStage="+row.paymentStage+"&paymentTime="+row.paymentTime+"&paymentRatio="+row.paymentRatio, {
        title: '编辑',
        width: '550px',
        height:'70%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            editPayDialog.dialog('destroy');
        },
        buttons: [
            {
                text:'保存',
                iconCls:'icon-save',
                handler:function() {
                    topWin.frames['editPay'].savePayDetail(function (data) {

                        var d = $("#table_pay").datagrid('getRows');
                        let je = new BigNumber(0);
                        let bl = 0;
                        d.forEach(function (v,n) {
                            if(n!=indexRow){
                                bl += parseFloat(v.paymentRatio);
                            }
                        });
                        if((parseFloat(bl.toFixed(2))+parseFloat(data.paymentRatio))>1){
                            //还原
                            topWin.layer.alert("付款比例超出",{icon:2});
                            return ;
                        }else{
                            let contractAmount = $("#contractAmount").textbox('getValue');
                            data.paymentAmount = new BigNumber(data.paymentRatio).multipliedBy( new BigNumber(contractAmount)).decimalPlaces(2,  BigNumber.ROUND_HALF_UP)  ;
                            //更新行数据
                            $("#table_pay").datagrid('updateRow',{index:indexRow,row:data })
                            d = $("#table_pay").datagrid('getRows');
                            d.forEach(function (v,n) {
                                je = new BigNumber(je).plus(new BigNumber(v.paymentAmount) );
                                //v.paymentAlreadyAmount = je.toFixed(4)  ;
                                $("#table_pay").datagrid('updateRow',{index:n,row:d[n]})
                                $('#table_pay').datagrid('refreshRow',n);
                            });

                            editPayDialog.dialog('close');
                            $('#tb').datagrid('reload');
                        }
                    });
                }
            },
            {
                text:'关闭',
                iconCls:'icon-cancel',
                handler:function() {
                    editPayDialog.dialog('close');
                }
            }
        ]
    });

}


function addDetail(){
    var isSap =$("#isSap").val();
        if (!isSap) {
            layer.msg("是否传输SAP下拉框不能为空");
            return;
        }
    let isMro = $("#isMro").combobox('getValue');
    if (!isMro){
        layer.msg("请选择是否MRO合同");
        return;
    }
    var addDetailsDialog = openDialog('addDetails', g.ctx+'pc/contract/manage/page/formDetail?detailId='+'&isSap='+isMro+'&isSap='+isMro, {
        title: '新增',
        width: '70%',
        height:'80%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            addDetailsDialog.dialog('destroy');
        },
        buttons: [
            {
                text:'保存',
                iconCls:'icon-save',
                handler:function() {
                    topWin.frames['addDetails'].saveContractDetail(function (data) {
                        $("#table_tb").datagrid('appendRow',data);
                        addDetailsDialog.dialog('close');
                        $('#tb').datagrid('reload');
                    });
                }
            },
            {
                text:'关闭',
                iconCls:'icon-cancel',
                handler:function() {
                    addDetailsDialog.dialog('close');
                }
            }
        ]
    });
}


function editDetail(){
    var isSap =$("#isSap").val();
    if (!isSap) {
        layer.msg("是否传输SAP下拉框不能为空！");
        return;
    }
    let isMro = $("#isMro").combobox('getValue');
    if (!isMro){
        layer.msg("请选择是否MRO合同");
        return;
    }
    let row = $("#table_tb").datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return;
    }


    let indexRow = $("#table_tb").datagrid('getRowIndex',row);

    var editDetailsDialog = openDialog('editDetails', g.ctx+'pc/contract/manage/page/formDetail?detailId='+row.id+'&isSap='+isSap+'&isMro='+isMro+'&subjectCode='+row.subjectCode+'&costCenterCode='+row.costCenterCode+'&costCenterName='+row.costCenterName+'&materialName='+row.materialName+'&materialGroupCode='+row.materialGroupCode+'&materialGroupName='+row.materialGroupName+'&materialCategory='+row.materialCategory+'&materialSpec='+row.materialSpec+'&warrantyPeriod='+(row.warrantyPeriod?row.warrantyPeriod:'')+'&materialModel='+row.materialModel+'&materialBrand='+row.materialBrand+'&basisUnit='+row.basisUnit+'&price='+row.price+'&num='+row.num+'&taxRateName='+row.taxRateName+'&taxRateCode='+row.taxRateCode+'&cardNumber='+row.cardNumber+'&bz='+row.bz+'&currencyCode='+row.currencyCode+'&purchaseCode='+row.purchaseCode+'&factoryCode='+row.factoryCode+'&factoryName='+row.factoryName+'&itemCode='+row.itemCode+'&customerCode='+row.customerCode+'&customerName='+row.customerName+'&driverAsset='+row.driverAsset+'&teamName='+row.teamName+'&requireName='+row.requireName, {
        title: '编辑',
        width: '70%',
        height:'80%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            editDetailsDialog.dialog('destroy');
        },
        buttons: [
            {
                text:'保存',
                iconCls:'icon-save',
                handler:function() {
                    topWin.frames['editDetails'].saveContractDetail(function (data) {
                        $("#table_tb").datagrid('updateRow',{ index:indexRow ,row:data});
                        editDetailsDialog.dialog('close');
                        $('#tb').datagrid('reload');
                    });
                }
            },
            {
                text:'关闭',
                iconCls:'icon-cancel',
                handler:function() {
                    editDetailsDialog.dialog('close');
                }
            }
        ]
    });
}

function delPay() {

    let row = $("#table_pay").datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return;
    }
    topWin.layer.confirm("是否删除", function (index) {
        var rowIndex = $("#table_pay").datagrid('getRowIndex', row);
        $("#table_pay").datagrid('deleteRow', rowIndex);
        var ds = $("#table_pay").datagrid('getRows');
        let je = 0;
        ds.forEach(function (v,n) {
            je = (je + v.paymentAmount );
            //v.paymentAlreadyAmount = je.toFixed(4) ;
            $("#table_pay").datagrid('updateRow',{index:n,row:ds[n]})
            $('#table_pay').datagrid('refreshRow',n);
        });
        topWin.layer.close(index);
    })
}

function delDetail() {
    let row = $("#table_tb").datagrid('getSelected');
    if (!row) {
        layer.msg("请选中一条记录");
        return;
    }
    topWin.layer.confirm("是否删除", function (index) {
        var rowIndex = $("#table_tb").datagrid('getRowIndex', row);
        $("#table_tb").datagrid('deleteRow', rowIndex);
        topWin.layer.close(index);
    })
}