/**
 * 对账模块-新增预付款申请页面JS
 *
 * Created by wt on 2020/9/15.
 */
'use strict';
var el = {
    isSupplier: '#isSupplier',
    files: '#files',
    dataPanel: '#dataPanel',
    dataDiv: '#dataDiv',
    companyCode: '#companyCode',
    companyName: '#companyName',
    factoryCode: '#factoryCode',
    factoryName: '#factoryName',
    supplierCode: '#supplierCode',
    supplierName: '#supplierName',
    currencyCode: '#currencyCode',
    supBankCode: '#supBankCode',
    supBankName: '#supBankName',
    supBankAccount: '#supBankAccount',
    paymentWayCode: '#paymentWayCode',
    paymentWayDesc: '#paymentWayDesc',
    paymentTermCode: '#paymentTermCode',
    paymentTermDesc: '#paymentTermDesc',
    applyPaymentAmount: '#applyPaymentAmount',
    applyRemark: '#applyRemark',
    apApplyNo: '#apApplyNo',
    tb: '#tb',
    tb2: '#tb2',
    tbToolbar:'#tbToolbar',
    tempDelTbData: [],
    existedData: [],
    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});
        }
    });
    // initFileBox();
    initPageDataGrid();
    initPageDataGrid2();
    initPageComBoBox();


    $('#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 isSupplier = $(el.isSupplier).val();
    var companyCategory = $("#companyCategory").val();

    // 初始化公司代码下拉框
    $(el.companyCode).combobox({
        url: g.ctx + 'pc/sys/company/rest/listAll?isAuthority=' + (Number(isSupplier) === 1 ? 0 : 1),
        required: true,
        editable: false,
        valueField: 'code',
        textField: 'codeWithDesc',
        panelHeight: 'auto',
        prompt: '--- 请选择 ---',
        onSelect: function (data) {
            $(el.companyName).val(data.companyName);
            //清空表格数据
            $('#tb').datagrid('loadData', {total: 0, rows: []})
        }
    });
    //季度
    $('#oaQuarter').combobox({
        valueField: 'label',
        textField: 'label',
        data: [
            {label: '一季度', value1: 0},
            {label: '二季度', value1: 1},
            {label: '三季度', value1: 2},
            {label: '四季度', value1: 3},
            {label: '一月', value1: 4},
            {label: '二月', value1: 5},
            {label: '三月', value1: 6},
            {label: '四月', value1: 7},
            {label: '五月', value1: 8},
            {label: '六月', value1: 9},
            {label: '七月', value1: 10},
            {label: '八月', value1: 11},
            {label: '九月', value1: 12},
            {label: '十月', value1: 13},
            {label: '十一月', value1: 14},
            {label: '十二月', value1: 15}
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });
    // //类别
    // $('#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').combobox('getValue');
    //             if(!companyCode){
    //                 topWin.layer.alert('请先选择公司', {icon: 0});
    //                 return false;
    //             }
    //             if(companyCode&&companyCode==1100){
    //                 $('#processId').combobox('setValue',1499);
    //             }else {
    //                 $('#processId').combobox('setValue',1223);
    //             }
    //             //$('#processId').combobox('setValue',1499);
    //         }
    //     }
    // });
    //是否安全生产费
    $('#isSafeProductionCost').combobox({
        valueField: 'value',
        textField: 'label',
        value: 1,
        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;
        }
    });
    initDict("currency")
    // 初始化币种下拉框
    $(el.currencyCode).combobox({
        panelHeight: 'auto',
        panelWidth: 200,
        valueField: 'code',
        textField: 'codeWithDesc',
        data:getDictList("currency"),
        onSelect: function () {
            //清空表格数据
            $('#tb').datagrid('loadData', {total: 0, rows: []})
        }
    });

    // 初始化供应商开户行下拉框
    $(el.supBankCode).combobox({
        panelHeight: 'auto',
        panelWidth: 300,
        prompt: '--- 请先选择供应商 ---',
        disabled: true,
        //readonly:true,
        required: true
    });

    // 初始化供应商开户行账号下拉框
    $(el.supBankAccount).combobox({
        panelHeight: 'auto',
        panelWidth: 300,
        prompt: '--- 请先选择供应商开户行 ---',
        disabled: true,
        //readonly: true,
        required: true
    });

    //付款金额计算
    $('#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);
        }
    });

    /**
     * 初始化供应商选择
     */
    if (Number(isSupplier) === 0) {
        $(el.supplierCode).textbox({
            prompt: '请选择供应商',
            required: true,
            icons: [
                {
                    iconCls: 'icon-search',
                    handler: function () {
                        choseSupplier();
                    }
                }
            ]
        });
        $(el.supplierCode).textbox('textbox').css('cursor', 'pointer');
        $(el.supplierCode).textbox('textbox').bind('click', function () {
            choseSupplier();
        });
    }
    //初始化部门
    // $('#oaDepName').textbox({
    //     prompt: '请选择部门',
    //     required: true,
    //     icons: [
    //         {
    //             iconCls: 'icon-search',
    //             handler: function () {
    //                 choseOaDepName();
    //             }
    //         }
    //     ]
    // });
    // $('#oaDepName').textbox('textbox').css('cursor', 'pointer');
    // $('#oaDepName').textbox('textbox').bind('click', function () {
    //     choseOaDepName();
    // });
    //代码选择
    // $('#oaCode').textbox({
    //     prompt: '请选择预算数据',
    //     required: true,
    //     icons: [
    //         {
    //             iconCls: 'icon-search',
    //             handler: function () {
    //                 choseBudget();
    //             }
    //         }
    //     ]
    // });
    // $('#oaCode').textbox('textbox').css('cursor', 'pointer');
    // $('#oaCode').textbox('textbox').bind('click', function () {
    //     choseBudget();
    // });

}


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

    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        height: el.bodyHeight - dataDivHeight,
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        showFooter: true,
        queryParams: {},
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: 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: 'factoryCode',
                    title: '工厂',
                    width: 80,
                    sortable: true
                },
                {
                    field: 'materialCode',
                    title: '物料编码',
                    width: 80
                },
                {
                    field: 'materialDesc',
                    title: '物料描述',
                    width: 300,
                    sortable: true
                },
                {
                    field: 'taxCodeDesc',
                    title: '税码',
                    width: 160,
                    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) {
                        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
                },
                {
                    field: 'quantityRange',
                    title: '容差',
                    hidden:true
                }
            ]
        ],
        toolbar:el.tbToolbar,
        onBeforeLoad: function () {
            $(el.tb).datagrid('reloadFooter',
                [
                    {
                        poCode: '合计',
                        itAmount: 0,
                        budInnerMoney: 0,
                        budOutMoney: 0,
                        alreadyApplyAmount: 0,
                        alreadyAdvanceAmount: 0
                    }
                ]
            );
        },
        onLoadSuccess: function () {
            $(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;
            }
        }
    });
}
/**
 * 查询订单
 */
function searchOrder() {
    var companyCode = $(el.companyCode).combobox('getValue'),
        supplierCode = $(el.supplierCode).textbox('getValue'), currencyCode = $(el.currencyCode).combobox('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: '/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];
        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 采购订单号
 */
function findPoData(poCodes) {

    var query = {};
    //校验订单号是否重复
    let rows = $(el.tb).datagrid('getRows');
    for (let i = 0; i < rows.length; i++) {
        //包含重复项
        if (poCodes.indexOf(rows[i].poCode) !== -1) {
            layer.msg("订单号" + rows[i].poCode + "重复");
            return false;
        }
    }
    query.morePoQuery = JSON.stringify(poCodes);
    query.applyId = 0;

    $.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) {
                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 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()

    $(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: 0,
            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.tb).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');
        // }
    });
}


/**
 * 表格添加数据
 *
 * @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,
        itPrice: item.itPrice,
        itAmount: item.itAmount,
        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,
        quantityRange: item.quantityRange,
        contractNo:item.contractNo,
        contractName:item.contractName,
        buyer:item.buyer
    };
    if (-1 === rowIndex) {
        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++) {
        let 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;
            // }
            if (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;
            // }
            if (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.supBankAccount) {
        topWin.layer.alert('请选择开户行账号信息', {icon: 0});
        return false;
    }
    // if (!mainData.paymentWayCode) {
    //     topWin.layer.alert('请选择付款方式信息', {icon: 0});
    //     return false;
    // }
    // let isOa = $('#isOa').combobox('getValue');
    // let oaCode = $('#oaCode').textbox('getValue');
    // if(Number(mainData.budInnerMoney) > Number(mainData.oaBalance)){
    //     topWin.layer.alert('预算内申请金额不得大于预算内余额', {icon: 0});
    //     return false;
    // }
    // if(!mainData.oaSubKey && Number(isOa) === 0){
    //     topWin.layer.alert('请获取oa数据', {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').combobox('getValue');
    // var oaType = $('#oaType').combobox('getValue');
    // if(oaType&&'日常借款' === oaType){
    //     var processId = $('#processId').combobox('getValue');
    //     //金派格的日常借款类型，流程是1499
    //     if(companyCode&&companyCode == 1100&&processId!=1499){
    //         layer.alert("流程不正确");
    //         return ;
    //     }else if(processId == 1499 && companyCode&&companyCode !=1100 ){
    //         layer.alert("流程不正确");
    //         return ;
    //     }
    // }


    mainData.saveType = 1;
    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 headData = {};
    if ($('#headForm').form('validate') ) {
        let headForm = $('#headForm').serializeJson();
        headForm.id = 0;
        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 = 0;
        obj.appNo = '';
        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 = '';

    return headData;
}

//获取oa数据
// function syncOAData() {
//     let oaSubName = $('#oaSubName').textbox('getValue');
//     let oaCode = $('#oaCode').textbox('getValue');
//     let oaDepName = $('#oaDepName').textbox('getValue');
//     let oaQuarter = $('#oaQuarter').combobox('getValue');
//     let oaType = $('#oaType').combobox('getValue');
//     let companyName = $('#companyName').val();
//     let oaXm = $('#oaXm').combobox('getValue');
//     let oaYwkm = $('#oaYwkm').combobox('getValue');
//     let llkzj = $('#llkzj').val();
//     if (!oaSubName || !oaCode || !oaDepName || !oaQuarter || !oaType || !companyName) {
//         layer.alert("请先填写【预算科目】【代码】【申请部门】【季度】【类别】【公司】信息");
//         return;
//     }
//     let obj = {
//         gsx: companyName,
//         departmentname: oaDepName,
//         lbx: oaType,
//         dm: oaCode,
//         jdx: oaQuarter,
//         xm: oaXm,
//         ywkm: oaYwkm,
//         llkzj: llkzj
//     };
//
//     var loading = topWin.layer.msg('同步OA数据中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
//     $.ajax({
//         url: g.ctx + 'fin/payment/advance/apply/rest/oa/sync',
//         type: 'POST',
//         data: {param: JSON.stringify(obj)},
//         success: function (data) {
//             topWin.layer.close(loading);
//             $('#oaSubKey').val(data[0].llkzj);
//             $('#oaDepKey').val(data[0].bmid);
//             $('#oaYear').val(data[0].nf);
//             $('#' + processName + 'oaDemandDep').val(data[0].xqbm);
//             $('#oaAleradyPayMoney').numberbox('setValue', data[0].yfky);
//             $('#oaPlantArea').combobox('setValue', data[0].cqdd);
//             $('#' + processName + 'oaContract').textbox('setValue', data[0].hthmc);
//             $('#' + processName + 'oaSpecs').textbox('setValue', data[0].gg);
//             $('#' + processName + 'oaUnit').textbox('setValue', data[0].dw);
//             $('#' + processName + 'oaNum').numberbox('setValue', data[0].sl);
//             $('#oaQuaeterBud').numberbox('setValue', data[0].byzjzcysy);
//             $('#oaBudInnerMoney').numberbox('setValue', data[0].ysn);
//             $('#oaBudOutMoney').numberbox('setValue', data[0].ysw);
//             //余额根据 总额-预算内已支出
//             $('#oaBalance').numberbox('setValue', accSub($('#oaQuaeterBud').numberbox('getValue'), $('#oaBudInnerMoney').numberbox('getValue')));
//             $('#' + processName + 'oaContractMoney').numberbox('setValue', data[0].htzje);
//             $('#' + processName + 'oaDeviceName').textbox('setValue', data[0].wxyy);
//         },
//         error: function (data) {
//             topWin.layer.close(loading);
//             topWin.layer.alert(data.responseJSON, {icon: 2});
//         }
//     });
// }
//
// //获取oa数据
// function onChangeSyncOA() {
//     let oaXm = $('#oaXm').combobox('getValue');
//     let oaYwkm = $('#oaYwkm').combobox('getValue');
//     if(oaXm&&oaYwkm){
//         let oaSubName = $('#oaSubName').textbox('getValue');
//         let oaCode = $('#oaCode').textbox('getValue');
//         let oaDepName = $('#oaDepName').textbox('getValue');
//         let oaQuarter = $('#oaQuarter').combobox('getValue');
//         let oaType = $('#oaType').combobox('getValue');
//         let companyName = $('#companyName').val();
//         let llkzj = $('#llkzj').val();
//         if(!oaSubName || !oaCode || !oaDepName || !oaQuarter || !oaType || !companyName){
//             layer.alert("请先填写【预算科目】【代码】【部门】【季度】【类别】【公司】信息");
//             return;
//         }
//         let obj = {
//             gsx:companyName,
//             departmentname:oaDepName,
//             lbx:oaType,
//             dm:oaCode,
//             jdx:oaQuarter,
//             xm: oaXm,
//             ywkm: oaYwkm,
//             llkzj: llkzj
//         };
//
//         var loading = topWin.layer.msg('同步OA数据中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
//         $.ajax({
//             url: g.ctx + 'fin/payment/advance/apply/rest/oa/sync',
//             type: 'POST',
//             data: {param:JSON.stringify(obj)},
//             success: function (data) {
//                 topWin.layer.close(loading);
//                 $('#oaSubKey').val(data[0].llkzj);
//                 $('#oaDepKey').val(data[0].bmid);
//                 $('#oaYear').val(data[0].nf);
//                 $('#'+processName+'oaDemandDep').val(data[0].xqbm);
//                 $('#oaAleradyPayMoney').numberbox('setValue',data[0].yfky);
//                 $('#oaPlantArea').combobox('setValue',data[0].cqdd);
//                 $('#'+processName+'oaContract').textbox('setValue',data[0].hthmc);
//                 $('#'+processName+'oaSpecs').textbox('setValue',data[0].gg);
//                 $('#'+processName+'oaUnit').textbox('setValue',data[0].dw);
//                 $('#'+processName+'oaNum').numberbox('setValue',data[0].sl);
//                 $('#oaQuaeterBud').numberbox('setValue',data[0].byzjzcysy);
//                 $('#oaBudInnerMoney').numberbox('setValue',data[0].ysn);
//                 $('#oaBudOutMoney').numberbox('setValue',data[0].ysw);
//                 //余额根据 总额-预算内已支出
//                 $('#oaBalance').numberbox('setValue', accSub($('#oaQuaeterBud').numberbox('getValue'), $('#oaBudInnerMoney').numberbox('getValue')));
//                 $('#'+processName+'oaContractMoney').numberbox('setValue',data[0].htzje);
//                 $('#'+processName+'oaDeviceName').textbox('setValue',data[0].wxyy);
//             },
//             error: function (data) {
//                 topWin.layer.close(loading);
//                 $('#oaQuaeterBud').numberbox('setValue',0);
//                 $('#oaBudInnerMoney').numberbox('setValue',0);
//                 $('#oaBudOutMoney').numberbox('setValue',0);
//                 //余额根据 总额-预算内已支出
//                 $('#oaBalance').numberbox('setValue',0);
//             }
//         });
//     }
// }
/**
 * 选择供应商
 */
function choseSupplier() {
    var supplierCode = $(el.supplierCode).textbox('getValue');
    var userOrgyDialog = openDialog('userOrgyDialog', g.ctx + 'pc/supplier/supplierSelect?single=1', {
        title: "选择供应商",
        width: '800px',
        height: '500px',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            userOrgyDialog.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.confirm,
                handler: function () {
                    topWin.frames['userOrgyDialog'].chooseRow(function (cbox) {console.log(cbox)
                        $(el.supplierCode).textbox('setValue', cbox.supplierCode);
                        $(el.supplierName).val(cbox.supplierName);
                        findSupBankDataBySupplierCode(cbox.id);
                        //清空表格数据
                        $('#tb').datagrid('loadData', {total: 0, rows: []})
                        userOrgyDialog.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                handler: function () {
                    userOrgyDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 选择供应商弹框主动关闭弹框(重要)
 *
 * @param data 选中的结果
 */
function choseSupDialogConfirm(data) {
    $(el.supplierCode).textbox('setValue', data.supplierCode);
    $(el.supplierName).val(data.supplierName);
    el.choseSupplierDialog.dialog('close');

    // findCurrencyDataBySupplierCode(data.supplierCode);
    findSupBankDataBySupplierCode(data.supplierId);
    //清空表格数据
    $('#tb').datagrid('loadData', {total: 0, rows: []})
}


/**
 * 根据公司编码获取工厂代码下拉框数据
 *
 * @param companyCode 公司编码
 * @param isSupplier 是否供应商账号 0:否 1是
 */
function findFactoryDataByCompanyCode(companyCode, isSupplier) {
    var factoryDataUrl = g.ctx + 'pc/sys/factory/rest/listAll?isAuthority=1&companyCode=' + companyCode;
    if (Number(isSupplier) === 1) {
        factoryDataUrl = g.ctx + 'pc/sys/factory/rest/listAll?isAuthority=0&companyCode=' + companyCode;
    }

    $(el.factoryCode).combobox({
        url: factoryDataUrl,
        valueField: 'factory',
        textField: 'name',
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        panelWidth: 260,
        editable: false,
        disabled: false,
        required: true,
        onLoadSuccess: function (data) {
            if (data.length === 1) {
                $(el.factoryCode).combobox('setValue', data[0].factory);
                $(el.factoryName).val(data[0].name);
            }
        },
        onSelect: function (data) {
            $(el.factoryName).val(data.name);
            //清空表格数据
            $('#tb').datagrid('loadData', {total: 0, rows: []})
        }
    });
}


/**
 * 根据供应商编码获取供应商开户行信息
 *
 * @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);
            }
        }
    });
}
