/**
 * 对账模块-编辑预付款申请页面JS
 *
 * Created by wt on 2020/9/15.
 */
'use strict';
var el = {
    files: '#files',
    isSupplier: '#isSupplier',
    id: '#id',
    dataPanel: '#dataPanel',
    dataDiv: '#dataDiv',
    companyCode: '#companyCode',
    factoryCode: '#factoryCode',
    supplierCode: '#supplierCode',
    supplierName: '#supplierName',
    currencyCode: '#currencyCode',
    supBankCode: '#supBankCode',
    supBankName: '#supBankName',
    supBankAccount: '#supBankAccount',
    paymentWayCode: '#paymentWayCode',
    paymentWayDesc: '#paymentWayDesc',
    ptcComBoBox: '#ptcComBoBox',
    paymentTermCode: '#paymentTermCode',
    paymentTermDesc: '#paymentTermDesc',
    applyPaymentAmount: '#applyPaymentAmount',
    applyRemark: '#applyRemark',
    apApplyNo: '#apApplyNo',
    tb: '#tb',
    tb2: '#tb2',
    tbToolbar:'#tbToolbar',
    existedData: [],
    tempDelTbData: [],
    chosePoDataDialog: [],
    editIndex: undefined,
    bodyHeight: document.documentElement.clientHeight
};


/**
 * 文档就绪
 */
$(function () {
    $(el.dataPanel).panel({
        collapsible: true,
        onCollapse: function () {
            $(el.tb).datagrid('resize', {height: el.bodyHeight - 45});
        },
        onExpand: function () {
            var dataDivHeight = $(el.dataDiv).outerHeight();
            $(el.tb).datagrid('resize', {height: el.bodyHeight - dataDivHeight});
        }
    });

    initPageComBoBox();

    initPageDataGrid();

    initPageDataGrid2();

    $('#tt').tabs({
        onSelect:function(title){
            if('已申请付款信息' === title){
                var rows = $(el.tb).datagrid('getRows');
                let poCodes = [];
                for (let i = 0; i < rows.length; i++) {
                    var item = rows[i];
                    poCodes.push(item.poCode);
                }
                findPaymentDetailByPoCode(poCodes)
            }
        }
    });

});
let processName = "";

/**
 * 初始化页面下拉框
 */
function initPageComBoBox() {
    // var pwCode = $(el.paymentWayCode).combobox('getValue'), paymentTermCode = $(el.paymentTermCode).val();

    // 初始化付款方式下拉框
    $(el.paymentWayCode).combobox({
        required: true,
        editable: false,
        valueField: 'dicId',
        textField: 'dicTxt',
        panelHeight: 'auto',
        data: [
            {dicTxt: '转账', dicId: "0"},
            {dicTxt: '承兑汇票', dicId: "1"},
            {dicTxt: '承兑汇票加转账', dicId: "2"}
        ],
        prompt: '--- 请选择 ---',
        onSelect: function (data) {
            $(el.paymentWayDesc).val(data.dicTxt);
        }
    });
    //季度
    $('#oaQuarter').combobox({
        valueField: 'label',
        textField: 'label',
        data: [
            {label: '一季度', value: 0},
            {label: '二季度', value: 1},
            {label: '三季度', value: 2},
            {label: '四季度', value: 3},
            {label: '一月', value: 4},
            {label: '二月', value: 5},
            {label: '三月', value: 6},
            {label: '四月', value: 7},
            {label: '五月', value: 8},
            {label: '六月', value: 9},
            {label: '七月', value: 10},
            {label: '八月', value: 11},
            {label: '九月', value: 12},
            {label: '十月', value: 13},
            {label: '十一月', value: 14},
            {label: '十二月', value: 15}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        panelWidth: 300,
    });
    //类别
    $('#oaType').combobox({
        valueField: 'label',
        textField: 'label',
        data: [
            {label: '物料采购预算', value: 0},
            {label: '工程技改预算', value: 1},
            {label: '设备购置预算', value: 2},
            {label: '设备维修预算', value: 3},
            {label: '咨询服务预算', value: 4},
            {label: '日常借款', value: 5}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        panelWidth: 300,
        onSelect: function (data) {
            let value = data.value;
            if (value === 0) {
                $('#processId').combobox('setValue',1520);
            } else if (value === 1) {
                $('#processId').combobox('setValue',1522);
            } else if (value === 2) {
                $('#processId').combobox('setValue',1523);

            } else if (value === 3) {
                $('#processId').combobox('setValue',1524);
            } else if (value === 4) {
                $('#processId').combobox('setValue',1525);
            } else if (value === 5) {
                var companyCode = $('#companyCode').val();
                if(!companyCode){
                    topWin.layer.alert('请先选择公司', {icon: 0});
                    return false;
                }
                if(companyCode&&companyCode==1100){
                    $('#processId').combobox('setValue',1499);
                }else {
                    $('#processId').combobox('setValue',1223);
                }
            }
        }
    });
    $('#isSafeProductionCost').combobox({
        valueField: 'value',
        textField: 'label',
        data: [
            {label: '否', value: 1},
            {label: '是', value: 0},
        ],
        editable: false,
        required: true,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        panelWidth: 300
    });
    //类别
    $('#processId').combobox({
        valueField: 'value',
        textField: 'label',
        data: [
            {label: '物料采购借款单', value: 1520},
            {label: '工程技改借款单', value: 1522},
            {label: '设备采购借款单', value: 1523},
            {label: '设备维修借款单', value: 1524},
            {label: '服务类借款单', value: 1525},
            {label: '借款单', value: 1223},
            {label: '借款单(金派格)', value: 1499}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        panelWidth: 300,
        onSelect:function (data) {
            let value = data.value;
        }
    });
    //付款金额计算
    $('#budInnerMoney').numberbox({
        onChange: function (value) {
            let budOutMoney = $('#budOutMoney').numberbox('getValue');
            if(!budOutMoney){
                budOutMoney = 0;
            }
            let oaBorrowMoney = accAdd(budOutMoney,value);
            $('#oaBorrowMoney').numberbox('setValue',oaBorrowMoney);
        }
    });
    $('#budOutMoney').numberbox({
        onChange: function (value) {
            let budInnerMoney = $('#budInnerMoney').numberbox('getValue');
            if(!budInnerMoney){
                budInnerMoney = 0;
            }
            let oaBorrowMoney = accAdd(budInnerMoney,value);
            $('#oaBorrowMoney').numberbox('setValue',oaBorrowMoney);
        }
    });

    var supplierId = $('#supplierId').val();
    findSupBankDataBySupplierCode(supplierId);
}


/**
 * 初始化页面表格数据
 */
function initPageDataGrid() {
    var dataDivHeight = $(el.dataDiv).outerHeight(), id = $(el.id).val();

    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/finance/paymentAdvance/apply/detail/rest/find/paa/detail',
        height: el.bodyHeight - dataDivHeight,
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        showFooter: true,
        queryParams: {
            applyId: id,
            dataShowType: 1
        },
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                // {
                //     field: 'seekPgName',
                //     title: '业务员',
                //     width: 80,
                //     sortable: true
                // },
                {
                    field: 'poCode',
                    title: '采购订单',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'poItemNo',
                    title: '订单行号',
                    width: 65,
                    sortable: true
                },
                {
                    field: 'buyer',
                    title: '采购员',
                    width: 80
                },
                {
                    field: 'poNum',
                    title: '订单数量',
                    width: 65,
                    sortable: true
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'quantityRange',
                    title: '容差',
                    hidden:true
                },
                {
                    field: 'factoryCode',
                    title: '工厂',
                    width: 80,
                    sortable: true
                },
                {
                    field: 'materialDesc',
                    title: '物料描述',
                    width: 300,
                    sortable: true
                },
                {
                    field: 'taxCodeDesc',
                    title: '税码',
                    width: 160,
                    sortable: true
                },
                // {
                //     field: 'ntPrice',
                //     title: '不含税单价',
                //     width: 100,
                //     sortable: true
                // },
                {
                    field: 'itPrice',
                    title: '含税单价',
                    width: 100,
                    sortable: true,
                    formatter:function (value) {
                        if (!value) {
                            return '';
                        }
                        return  formatNumber(value, 4, 1);
                    }
                },
                {
                    field: 'itAmount',
                    title: '订单含税金额',
                    width: 100,
                    sortable: true,
                    formatter:function (value) {
                        if (!value) {
                            return '';
                        }
                        return  formatNumber(value, 4, 1);
                    }
                },
                {
                    field: 'applyAmount',
                    title: '可申请金额',
                    width: 100,
                    sortable: true,
                    formatter:function (value) {
                        if (!value) {
                            return '';
                        }
                        return  formatNumber(value, 4, 1);
                    }
                },
                // {
                //     field: 'budInnerMoney',
                //     title: '预算内申请金额',
                //     width: 100,
                //     sortable: true,
                //     styler: function (value, row) {
                //         if(row.poCode !== '合计'){
                //             return 'background-color:#E1E1E1;';
                //         }
                //         return '';
                //     },
                //     editor: {
                //         type: 'numberbox',
                //         options: {
                //             precision: 4,
                //             onChange: function (nv) {
                //                 updateRowData(nv,'budInnerMoney');
                //             }
                //         }
                //     }
                // },
                {
                    field: 'budOutMoney',
                    title: '本次申请金额',
                    width: 100,
                    sortable: true,
                    styler: function (value, row) {
                        if(row.poCode !== '合计'){
                            return 'background-color:#E1E1E1;';
                        }
                        return '';
                    },
                    editor: {
                        type: 'numberbox',
                        options: {
                            precision: 4,
                            onChange: function (nv) {
                                updateRowData(nv,'budOutMoney');
                            }
                        }
                    }
                },
                {
                    field: 'alreadyApplyAmount',
                    title: '已申请金额',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'alreadyAdvanceAmount',
                    title: '已预付金额',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'reversalMoney',
                    title: '已冲账金额',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'pcCodeName',
                    title: '付款条件名称',
                    width: 200,
                    sortable: true
                },
                {
                    field: 'itemRemark',
                    title: '摘要',
                    width: 200,
                    styler: function (value, row) {
                        if(row.poCode !== '合计'){
                            return 'background-color:#E1E1E1;';
                        }
                        return '';
                    },
                    editor: {type: 'textbox'}
                },
                {
                    field: 'contractNo',
                    title: '合同号',
                    width:120
                },
                {
                    field: 'contractName',
                    title: '合同名称',
                    width:120
                },
                {
                    field: 'emptyColumn',
                    title: '',
                    width: 20
                }
            ]
        ],
        toolbar: el.tbToolbar,
        onLoadSuccess: function (data) {
            var rows = data.rows;
            for(var i = 0; i < rows.length; i++){
                el.existedData.push(rows[i].poKey);
            }

            $(el.tb).datagrid('clearSelections');
        },
        onClickRow: function (index) {
            if (el.editIndex !== undefined) {
                endEditor();
                $(el.tb).datagrid('beginEdit', index);
                el.editIndex = index;
            }else {
                $(el.tb).datagrid('beginEdit', index);
                el.editIndex = index;
            }
        }
    });
}


/**
 * 根据采购订单编号获取付款信息
 * @param poCodes
 */
function findPaymentDetailByPoCode(poCodes) {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/finance/paymentAdvance/apply/detail/rest/find/payment/detail',
        data:{
            'poCodeList': poCodes
        },
        dataType:'json',
        success: function (data) {
            $(el.tb2).datagrid('loadData', data);
        },
        error: function (data) {
            console.log(data);
            topWin.layer.alert('数据获取失败, 请联系管理员', {icon: 0});
        }
    });
}
/**
 * 初始化申请付款信息
 */
function initPageDataGrid2() {
    var dataDivHeight = $(el.dataDiv).outerHeight(),id = $(el.id).val();

    $(el.tb2).datagrid({
        loadMsg: '数据加载中......',
        //url: g.ctx + 'fin/payment/advance/apply/rest/find/payment/detail',
        height: el.bodyHeight - dataDivHeight,
        singleSelect: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        showFooter: false,
        view: detailview,
        queryParams: {
            applyId: id,
            type: 'advance_payment'
        },
        columns: [
            [
                {
                    field: 'poCode',
                    title: '采购订单',
                    width: 150
                },
                {
                    field: 'prepaid',
                    title: '已申请预付金额',
                    width: 180
                },
                {
                    field: 'actualPrepaid',
                    title: '实际预付金额',
                    width: 180
                },
                {
                    field: 'deductionPrepaid',
                    title: '已抵扣预付金额',
                    width: 180,
                    // formatter:function (value) {
                    //     if (!value) {
                    //         return 0;
                    //     }
                    //     return  formatNumber(value, 4, 1);
                    // }
                },
                {
                    field: 'ticketPrepaid',
                    title: '票到付款申请金额',
                    width: 180,
                    // formatter:function (value) {
                    //     if (!value) {
                    //         return 0;
                    //     }
                    //     return  formatNumber(value, 4, 1);
                    // }
                },
                {
                    field: 'actualTicketPrepaid',
                    title: '实际票到付款金额',
                    width: 180,
                    // formatter:function (value) {
                    //     if (!value) {
                    //         return 0;
                    //     }
                    //     return  formatNumber(value, 4, 1);
                    // }
                },
                {
                    field: 'totalPayment',
                    title: '累计已付款金额',
                    width: 180,
                    // formatter:function (value) {
                    //     if (!value) {
                    //         return 0;
                    //     }
                    //     return  formatNumber(value, 4, 1);
                    // }
                },
                {
                    field: 'remaining',
                    title: '剩余付款金额',
                    width: 180
                },
                {
                    field: 'buyer',
                    title: '采购员',
                    width: 200
                },
                // {
                //     field: 'contractNo',
                //     title: '合同号',
                //     width:120,
                //     formatter:function (value,row,index) {
                //         return "<a href='/contract/manage/examine/lookByCode?code=" + window.btoa(encodeURIComponent(value)) + "' target='_blank'>"+value+"</a>"
                //     }
                // },
            ]
        ],
        onLoadSuccess: function () {
            $(el.tb2).datagrid('clearSelections');
        },
        //构造一个满足Datagrid的div
        detailFormatter: function (index) {
            return '<div id="ddv-' + index + '" style="padding: 5px;"></div>';
        },
        onExpandRow: function (index, row) {
            //el.dateViewTotal.push(index);
            catPaymentDetail(index,row);
        },
    });
}

/**
 * 查看每个订单下的付款详细数据
 * @param index 行索引
 * @param row 行数据
 */
function catPaymentDetail(index, row) {
    $('#ddv-' + index).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/finance/paymentAdvance/apply/detail/rest/find/payment/detailBypoCode',
        singleSelect: false,
        height: 'auto',
        pagination: false,
        width: screenWidth - 10,
        page: 1,
        pageSize: 1000,
        queryParams: {
            poCode: row.poCode
        },
        columns: [[
            {
                field: 'status',
                title: '付款状态',
                width: 120,
                formatter: function (value, row, index) {
                    switch (value){
                        case 3:
                            return '审批中';
                        case 5:
                            return '付款完成';
                    }
                }
            },
            {
                field: 'amountType',
                title: '付款类型',
                width: 120,
                formatter: function (value, row, index) {
                    // if (value == undefined) {
                    //     value = "";
                    // }
                    // if (Number(row.is_require_cost) === 1) {
                    //     return '<a href="javascript:void(0);" style="color: blue;" onclick="costBaoJia(this)" data-index="' + index + '" data-value="' + row.taxfree_quote + '" data-sid="' + row.id + '" data-mc="' + row.material_code + '" data-mn="' + row.material_name + '">' + value + '</a>';
                    // }
                    // return value;
                    switch (value) {
                        case 'Z001':
                            return '预付款';
                        case 'Z003':
                            return '票到付款';
                    }
                }
            },
            {
                field: 'paymentNo',
                title: '付款单号',
                width: 150
            },
            {
                field: 'poCode',
                title: '订单号',
                width: 150
            },
            {
                field: 'itemNo',
                title: '订单行号',
                width: 150
            },
            {
                field: 'contractNo',
                title: '合同号',
                width: 170
            },
            {
                field: 'invoiceNo',
                title: '发票号',
                width: 170
            },
            {
                field: 'invoiceItemNo',
                title: '发票行号',
                width: 150,
                // formatter: function (value, row, rec) {
                //     var desc = BJGL.BJGL__SHANGC;
                //     if (row.supplier_annex) {
                //         value = row.supplier_annex;
                //         var supplierAnnexNum = row.supplier_annex.split(',');
                //         desc = BJGL.BJGL__YSC + supplierAnnexNum.length + '个';
                //     } else {
                //         value = -100;
                //     }
                //     if (row.material_name != "<b>合计</b>") {
                //
                //         return '<a href="javascript:void(0);" style="color: blue;" onclick="uploadRequireFileUI(this)" data-index="' + rec + '" data-value="' + value + '">' + desc + '</a>';
                //     }
                // },
                // styler: function (value, row) {
                //     var prohibitQuoteFlag = row.prohibit_quote_flag;
                //     if (Number(prohibitQuoteFlag) === 1) {
                //         return 'background-color:#92b3d0;';
                //     } else {
                //         if (value) {
                //             return 'background-color:#fff;';
                //         }
                //         return 'background-color:#f8d594;';
                //     }
                // }
            },
            {
                field: 'prepaid',
                title: '申请付款金额',
                width: 100
            },
            {
                field: 'actualPrepaid',
                title: '实际付款金额',
                width: 100,
            },
            {
                field: 'deductionPrepaid',
                title: '抵扣预付金额',
                width: 100
            },
            {
                field: 'buyer',
                title: '采购员',
                width: 100
            }
        ]],
        onLoadSuccess: function (data) {
            $(el.tb2).datagrid('fixDetailRowHeight', index);
            var buyer = row.buyer;
            var rows = data.rows;
            for (let i = 0; i < rows.length; i++) {
                $('#ddv-' + index).datagrid('updateRow',{
                    index: i,
                    row: {
                        buyer: buyer,
                    }
                });
            }
            //$('#supplierTb').datagrid('fixDetailRowHeight', index);
        },
        // onClickRow: function (detailIndex, rowData) {
        //     if (supplierEditIndex === undefined) {
        //         el.tableDom = '#ddv-' + index;
        //         $(el.tableDom).datagrid('beginEdit', detailIndex);
        //         supplierEditIndex = detailIndex;
        //     } else {
        //         supplierEndEditor();
        //         el.tableDom = '#ddv-' + index;
        //         $(el.tableDom).datagrid('beginEdit', detailIndex);
        //         supplierEditIndex = detailIndex;
        //     }
        // },
        onResize: function () {
            $(el.tb2).datagrid('fixDetailRowHeight', index);
        }
        // onCheck: function (rowIndex, rowData) {
        //     $(el.tb).datagrid('unselectAll');
        // },
        // onCheckAll: function (rows) {
        //     $(el.tb).datagrid('unselectAll');
        // }
    });
}

/**
 * 百分比计算
 */
function percentageCalculation() {
    endEditor();
    let rows = $('#tb').datagrid('getSelections');
    if(rows.length === 0){
        layer.msg("请选择行数据");
        return;
    }
    let innerInput = $('#budInnerInput').numberbox('getValue');
    let outInput = $('#budOutInput').numberbox('getValue');
    let budOutMoney = new BigNumber(0),budInnerMoney = new BigNumber(0);
    for(let i =0;i<rows.length;i++){
        let rowIndex = $('#tb').datagrid('getRowIndex',rows[i]);
        if(innerInput){
            rows[i].budInnerMoney = new BigNumber(rows[i].itAmount).multipliedBy(new BigNumber(innerInput)).dividedBy(100).toFixed(4);
            budInnerMoney = budInnerMoney.plus( rows[i].budInnerMoney);
        }
        if(outInput){
            rows[i].budOutMoney = new BigNumber(rows[i].itAmount).multipliedBy(new BigNumber(outInput)).dividedBy(100).toFixed(4);
            budOutMoney = budOutMoney.plus(rows[i].budOutMoney);
        }
        $('#tb').datagrid('refreshRow', rowIndex);
        var footers = $(el.tb).datagrid('getFooterRows');
        footers[0]['budOutMoney'] = budOutMoney.toFormat(2);
        footers[0]['budInnerMoney'] = budInnerMoney.toFormat(2);
        $(el.tb).datagrid('reloadFooter');
        $('#budInnerMoney').numberbox('setValue', budInnerMoney.toFixed(2));
        $('#budOutMoney').numberbox('setValue', budOutMoney.toFixed(2));
    }

}

/**
 * 查询订单
 */
function searchOrder() {
    var companyCode = $(el.companyCode).val(),
        supplierCode = $(el.supplierCode).val(), currencyCode = $(el.currencyCode).textbox('getValue');
    if(!companyCode){
        topWin.layer.msg('请先选择公司信息', {icon: 0});
        return false;
    }
    if(!supplierCode){
        topWin.layer.msg('请先选择供应商信息', {icon: 0});
        return false;
    }
    if(!currencyCode){
        topWin.layer.msg('请先选择币种信息', {icon: 0});
        return false;
    }
    parent.layer.open({
        title: '选择订单',
        content: g.ctx + 'pc/order/purchaseOrder/page/choice/order?companyCode='+companyCode+'&supplierCode='+supplierCode+'&currencyCode='+currencyCode,
        area: ['85%', '85%'],
        type: 2,
        size: 1024,
        btn: [buttonI18n.select, buttonI18n.close],
        yes: function (index, layero) {
            let iframeWin = parent.window[layero.find('iframe')[0]['name']];
            iframeWin.chooseRow(function (rows) {
                endEditor();
                let poCodes = [];
                for (let i = 0; i < rows.length; i++) {
                    poCodes.push(rows[i].orderCode);
                }
                findPoData(poCodes);
                parent.layer.close(index);
            });
        }
    });
}


/**
 * 删除
 */
function delItem() {
    var rows = $(el.tb).datagrid('getSelections');
    if(rows.length === 0){
        topWin.layer.alert('请选择您要删除的行数据', {icon: 0});
        return false;
    }

    for(var i = 0; i < rows.length; i++){
        var row = rows[i];
        if(row.id !== 0){
            el.tempDelTbData.push(row.id);
        }
        var rowIndex = $(el.tb).datagrid('getRowIndex', row);
        $(el.tb).datagrid('deleteRow', rowIndex);
    }

    summaryItemAmount();
}


/**
 * 明细数据导出
 */
function itemDataExport() {
    var rows = $(el.tb).datagrid('getRows');
    for(var i = 0; i < rows.length; i++){
        var item = rows[i];
        var rowIndex = $(el.tb).datagrid('getRowIndex', item);
        $(el.tb).datagrid('endEdit', rowIndex);
    }

    $(el.tb).datagrid('toExcel', {
        filename: '预付款申请明细数据.xls',
        rows: rows,
        worksheet: '预付款申请明细'
    });
}


/**
 * 根据输入的采购订单号获取采购订单信息
 *
 * @param poCodes 采购订单号
 * @param editIndex 当前编辑的行
 */
function findPoData(poCodes) {
    var rows = $(el.tb).datagrid('getRows'), existedItemIds = [];
    for(var i = 0; i < rows.length; i++){
        if(rows[i].id !== 0){
            existedItemIds.push(rows[i].id);
        }
    }
    existedItemIds = existedItemIds.concat(el.tempDelTbData);
    for (let i = 0; i < rows.length; i++) {
        //包含重复项
        if(poCodes.indexOf(rows[i].poCode) !== -1){
            layer.msg("订单号"+rows[i].poCode+"重复");
            return false;
        }
    }

    var query = {};
    query.existedItemIds = existedItemIds.join(',');
    query.morePoQuery = JSON.stringify(poCodes);
    query.applyId = $(el.id).val();

    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/finance/paymentAdvance/apply/detail/rest/find/po/data/by/po/code',
        data: query,
        success: function (data) {
            if(data.length > 0){
                // $(el.tb).datagrid('deleteRow', editIndex);
                for(var i = 0; i < data.length; i++){
                    dataGirdAddRow(data[i]);
                }
            }else {

                topWin.layer.alert('未获取到订单数据, 请检查', {icon: 0});
                return false;
            }

            summaryItemAmount();
        },
        error: function (data) {
            console.log(data);
            topWin.layer.alert('数据获取失败, 请联系管理员', {icon: 0});
        }
    });
}


/**
 * 表格添加数据
 *
 * @param item 待添加的数据
 */
function dataGirdAddRow(item) {
    var poKey = item.poCode + '_' + item.poItemNo, rowIndex = -1;
    if($.inArray(poKey, el.existedData) >= 0){
        var rows = $(el.tb).datagrid('getRows');
        for(var i = 0; i < rows.length; i++){
            if(rows[i].poKey === poKey){
                rowIndex = $(el.tb).datagrid('getRowIndex', rows[i]);
                break;
            }
        }
    }else {
        el.existedData.push(poKey);
    }

    var row = {
        poKey: item.poKey,
        poCode: item.poCode,
        poItemNo: item.poItemNo,
        poNum: item.poNum,
        seekPgCode: item.seekPgCode,
        seekPgName: item.seekPgName,
        factoryCode: item.factoryCode,
        materialCode: item.materialCode,
        materialDesc: item.materialDesc,
        materialUnit: item.materialUnit,
        taxCodeDesc: item.taxCodeDesc,
        taxValue: item.taxValue,
        taxCode: item.taxCode,
        taxDesc: item.taxDesc,
        ntPrice: item.ntPrice,
        ntAmount: item.ntAmount,
        itPrice: item.itPrice,
        itAmount: item.itAmount,
        dtAmount: item.dtAmount,
        alreadyApplyAmount: item.alreadyApplyAmount,
        alreadyAdvanceAmount: item.alreadyAdvanceAmount,
        applyAmount: item.applyAmount,
        budInnerMoney: item.budInnerMoney,
        budOutMoney: item.budOutMoney,
        paymentConditionCode: item.paymentConditionCode,
        paymentConditionName: item.paymentConditionName,
        pcCodeName: item.pcCodeName,
        paymentWayCode: item.paymentWayCode,
        paymentWayDesc: item.paymentWayDesc,
        pwCodeDesc: item.pwCodeDesc,
        contractNo:item.contractNo,
        contractName:item.contractName,
        buyer:item.buyer
    };
    if(-1 === rowIndex){
        row.id = 0;
        row.itemRemark = '';
        $(el.tb).datagrid('appendRow', row);
    }else {
        $(el.tb).datagrid('updateRow', {
            index: rowIndex,
            row: row
        });
    }
}


/**
 * 数据保存-暂存
 *
 * @param callback 回调函数
 */
function dataSave(callback) {
    // 结束行编辑
    endEditor();
    summaryItemAmount();

    var rows = $(el.tb).datagrid('getRows');
    if(rows.length === 0){
        topWin.layer.alert('请添加采购订单数据', {icon: 0});
        return false;
    }
    for(var i = 0; i < rows.length; i++) {
        var item = rows[i];
        if(item.quantityRange){
            let quantityRange = new BigNumber(item.quantityRange.replace("%","")).dividedBy(100);
            if(!item.applyAmount){
                item.applyAmount = 0;
            }
            let applyAmount = new BigNumber(item.applyAmount).multipliedBy(quantityRange).plus(item.applyAmount);
            // 预算内金额+预算外金额 不能大于本次可申请金额
            if (Number(item.budInnerMoney).add(Number(item.budOutMoney)) > applyAmount.toFixed(4)) {
                topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的预算内金额和预算外金额合计不能大于本次可申请金额(包含容差)', {icon: 0});
                return false;
            }
        }else{
            // 预算内金额+预算外金额 不能大于本次可申请金额
            if (Number(item.budInnerMoney).add(Number(item.budOutMoney)) > Number(item.applyAmount.toFixed(4))) {
                topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的预算内金额和预算外金额合计不能大于本次可申请金额', {icon: 0});
                return false;
            }
        }
        // 本次申请金额不能小于等于0
        if (Number(item.budInnerMoney).add(Number(item.budOutMoney)) <= 0) {
            topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的申请金额不能小于等于零', {icon: 0});
            return false;
        }
    }
    let budInnerMoney = $('#budInnerMoney').numberbox('getValue');
    let budOutMoney = $('#budOutMoney').numberbox('getValue');
    if (Number(budInnerMoney).add(Number(budOutMoney)) <=0 || Number(budInnerMoney) <0 || Number(budOutMoney) <0) {
        topWin.layer.alert('预付款单预算金额不能小于等于零', {icon: 0});
        return false;
    }
    var mainData = handleWaitSaveData(rows);
    if(!mainData){
        return false;
    }
    // 数据校验
    if(!mainData.supBankCode){
        topWin.layer.alert('请选择供应商开户行信息', {icon: 0});
        return false;
    }
    // if(!mainData.paymentWayCode){
    //     topWin.layer.alert('请选择付款方式信息', {icon: 0});
    //     return false;
    // }
    // if(Number(mainData.budInnerMoney) > Number(mainData.oaBalance)){
    //     topWin.layer.alert('预算内申请金额不得大于预算内余额', {icon: 0});
    //     return false;
    // }

    // if(Number(mainData.processId) === 1223 &&
    //     Number(mainData.oaTransferMoney) != Number(mainData.budInnerMoney).add(Number(mainData.budOutMoney)).toFixed(2)){
    //     layer.alert("转账金额需等于预算外金额和预算内金额总和");
    //     return ;
    // }
    // var companyCode = $('#companyCode').val();
    // var oaType = $('#oaType').combobox('getValue');
    //
    // var transferMoney = 0;
    // var oaBorrowMoney = $('#oaBorrowMoney').numberbox('getValue');
    // if(oaType&&'物料采购预算' !==oaType){
    //     if(oaBorrowMoney&&transferMoney){
    //         if(Number(oaBorrowMoney)!==Number(transferMoney)){
    //             layer.alert("转账金额与付款金额必须相同");
    //             return;
    //         }
    //     }else {
    //         layer.alert("转账金额和付款金额必须填值");
    //         return;
    //     }
    // }
    mainData.saveType = 2;
    mainData.isPushOa = 0;
    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'pc/finance/paymentAdvance/apply/rest/dave/save',
        type: 'POST',
        data: JSON.stringify(mainData),
        contentType: 'application/json',
        success: function () {
            topWin.layer.close(loading);
            callback();
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}

function getAName(){
    return "alreadyAdvanceAmount";
}


/**
 * 处理待保存数据
 *
 * @param rows 明细数据
 * @returns {boolean} 结果
 */
function handleWaitSaveData(rows) {
    var  apApplyNo = $(el.apApplyNo).val();
    var headData = {};

    if ($('#headForm').form('validate') ) {
        let headForm = $('#headForm').serializeJson();
        headForm.files = $(el.files).attr('data-fileIds');
        headData = headForm;
    }else{
        layer.msg("红色框为必输项，请填写！");
        return false;
    }


    var itemList = [];
    for(var i = 0; i < rows.length; i++){
        var obj = {}, item = rows[i];
        obj.id = item.id;
        obj.appId = $(el.id).val();
        obj.appNo = apApplyNo;
        obj.poCode = item.poCode;
        obj.poItemNo = item.poItemNo;
        obj.poNum = item.poNum;
        obj.materialCode = item.materialCode;
        obj.materialDesc = item.materialDesc;
        obj.materialUnit = item.materialUnit;
        obj.taxCode = item.taxCode;
        obj.taxDesc = item.taxDesc;
        obj.taxValue = item.taxValue;
        obj.ntPrice = item.ntPrice;
        obj.itPrice = item.itPrice;
        obj.ntAmount = item.ntAmount;
        obj.itAmount = item.itAmount;
        obj.dtAmount = item.dtAmount;
        obj.budInnerMoney = item.budInnerMoney;
        obj.budOutMoney = item.budOutMoney;
        obj.itemRemark = item.itemRemark;
        obj.seekPgCode = item.seekPgCode;
        obj.seekPgName = item.seekPgName;
        obj.factoryCode = item.factoryCode;
        obj.paymentWayCode = item.paymentWayCode;
        obj.paymentWayDesc = item.paymentWayDesc;
        obj.paymentConditionCode = item.paymentConditionCode;
        obj.paymentConditionDesc = item.paymentConditionName;
        obj.contractNo = item.contractNo;
        obj.contractName = item.contractName;
        itemList.push(obj);
    }
    headData.itemList = itemList;
    headData.delItemIdList = el.tempDelTbData.length === 0 ? '' : el.tempDelTbData;

    return headData;
}

/**
 * 子级页面获取数据
 */
function childrenPageFindData() {
    return el.existedData;
}


/**
 * 根据供应商编码获取供应商开户行信息
 *
 * @param supplierId 供应商id
 */
function findSupBankDataBySupplierCode(supplierId) {
    $.ajax({
        url: g.ctx + 'pc/supplier/rest/find/bank?supplierId=' + supplierId,
        type: 'POST',
        success: function (res) {
            var bankData = [], bankCodes = [];
            for (var i = 0; i < res.length; i++) {
                if(bankCodes.indexOf(res[i].bankCode) < 0){
                    var obj = {};
                    obj.supBankCode = res[i].bankCode;
                    obj.supBankName = res[i].openingBankName;
                    bankData.push(obj);

                    bankCodes.push(res[i].bankCode);
                }
            }

            $(el.supBankCode).combobox({
                data: bankData,
                valueField: 'supBankCode',
                textField: 'supBankName',
                prompt: '--- 请选择 ---',
                panelHeight: 'auto',
                panelWidth: 300,
                editable: false,
                disabled: false,
                required: true,
                onLoadSuccess: function(data){
                    if(data.length === 1){
                        $(el.supBankCode).combobox('setValue', data[0].supBankCode);
                        $(el.supBankName).val(data[0].supBankName);

                        findSupplierBankAccount(res,  data[0].supBankCode);
                    }
                },
                onSelect: function (data) {
                    $(el.supBankName).val(data.supBankName);
                    findSupplierBankAccount(res, data.supBankCode);
                }
            });
        }
    });
}


/**
 * 获取供应商开户行对应的银行账号
 *
 * @param data 供应商银行账号信息
 * @param bankCode 供应商开户行编码
 */
function findSupplierBankAccount(data, bankCode) {
    var baData = [], eba = [];
    for (var i = 0; i < data.length; i++) {
        if(data[i].bankCode === bankCode && eba.indexOf(data[i].bankAccount) < 0){
            var obj = {};
            obj.supBankAccount = data[i].bankAccount;
            baData.push(obj);

            eba.push(data[i].bankAccount)
        }
    }

    $(el.supBankAccount).combobox({
        data: baData,
        valueField: 'supBankAccount',
        textField: 'supBankAccount',
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        panelWidth: 300,
        editable: false,
        disabled: false,
        required: true,
        onLoadSuccess: function(data){
            if(data.length === 1){
                $(el.supBankAccount).combobox('setValue', data[0].supBankAccount);
            }
        }
    });
}
