var el = {
    files: '#files',
    isSupplier: '#isSupplier',
    id: '#id',
    dataPanel: '#dataPanel',
    dataType:'#dataType',
    dataDiv: '#dataDiv',
    paymentChangeNo:'#paymentChangeNo',
    recordedAmount:'#recordedAmount',//登记金额
    reversedAmount:'#reversedAmount',//已冲账金额
    approvalOpinion:'#approvalOpinion', //$(el.approvalOpinion).val();//审批意见
    remark:'#remark',//备注(说明)
    companyCode: '#companyCode',
    factoryCode: '#factoryCode',
    supplierCode: '#supplierCode',
    supplierName: '#supplierName',
    currencyCode: '#currencyCode',
    supBankCode: '#supBankCode',
    supBankName: '#supBankName',
    bankCode: '#bankCode',
    bankInterCode: '#bankInterCode',
    supBankAccount: '#supBankAccount',
    paymentWayCode: '#paymentWayCode',
    advancePaymentFlag: '#advancePaymentFlag',
    acceptanceMethod: '#acceptanceMethod',
    faSupplier: '#faSupplier',
    faSupplierName: '#faSupplierName',
    paymentWayDesc: '#paymentWayDesc',
    ptcComBoBox: '#ptcComBoBox',
    paymentTermCode: '#paymentTermCode',
    paymentTermDesc: '#paymentTermDesc',
    applyPaymentAmount: '#applyPaymentAmount',
    applyRemark: '#applyRemark',
    apApplyNo: '#apApplyNo',
    oaHandler: '#oaHandler',
    oaHandlerCode: '#oaHandlerCode',
    tb: '#tb',
    tb2: '#tb2',
    tbToolbar:'#tbToolbar',
    existedData: [],
    tempDelTbData: [],
    chosePoDataDialog: [],
    editIndex: undefined,
    dataStatus:"#status",
    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});
        }
    });
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll,pc/sys/tax/rest/listAll')
    initDict('payment_method')
    initPageComBoBox();

    initPageDataGrid();

});

/**
 * 初始化页面表格数据
 */
function initPageDataGrid() {
    var dataDivHeight = $(el.dataDiv).outerHeight()
    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/finance/paymentAdvanceRefundTransferApplyDetail/apply/detail/rest/find/findRefundTransferApplyDetailByRefundId',
        height: el.bodyHeight - dataDivHeight,
        singleSelect: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        showFooter: true,
        queryParams: {
            applyId: $(el.id).val(),
            dataShowType: 1
        },
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'appNo',
                    title: '预付款申请单号',
                    width: 110,
                    sortable: true
                },{
                field: 'appItemNo',
                title: '预付款申请行号',
                width: 110,
                sortable: true
            },
                {
                    field: 'poCode',
                    title: '采购订单',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'poItemNo',
                    title: '订单行号',
                    width: 60,
                    sortable: true
                },
                {field: 'dataKey', title: '联合主键', width: 120},
                {
                    field: 'createUserName',
                    title: '预付款单创建人',
                    width: 100
                },
                {
                    field: 'poNum',
                    title: '订单数量',
                    width: 60,
                    sortable: true
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'factoryCode',
                    title: '工厂',
                    width: 45,
                    sortable: true
                },
                {
                    field: 'materialCode',
                    title: '物料编码',
                    width: 90
                },
                {
                    field: 'materialDesc',
                    title: '物料描述',
                    width: 300,
                    sortable: true
                },
                {
                    field: 'taxCode',
                    title: '税码',
                    width: 40,
                    sortable: true
                },
                {
                    field: 'itPrice',
                    title: '含税单价',
                    width: 60,
                    sortable: true,
                    formatter:function (value) {
                        return formatterPrice(value);
                    }
                },
                {
                    field: 'itAmount',
                    title: '订单含税金额',
                    width: 70,
                    sortable: true,
                    formatter:function (value) {
                        return formatterPrice(value);
                    }
                },
                {
                    field: 'prepaymentAmountInclusiveTax',
                    title: '已付预付款含税金额',
                    width: 120,
                    formatter:function (value) {
                        return formatterPrice(value);
                    }
                },
                {
                    field: 'cantRegistTaxAmount',
                    title: '可登记含税金额',
                    width: 110
                },
                {
                    field: 'theRegistTaxAmount',
                    title: '本次登记含税金额',
                    width: 110,
                    sortable: true,
                    styler: function (value, row) {
                        if (row.poCode !== '合计') {
                            return 'background-color:#E1E1E1;';
                        }
                        return '';
                    },
                    editor: {
                        type: 'numberbox',
                        options: {
                            precision: priceHandle.precision,
                            onChange: function (nv) {
                                updateRowData_(nv, 'theRegistTaxAmount');
                                var rows = $(el.tb).datagrid('getRows');
                                    for (var j = 0; j < rows.length; j++) {
                                        var item = rows[j];
                                        var rowIndex = $(el.tb).datagrid('getRowIndex', item);
                                        if (rowIndex === el.editIndex) {
                                            item.theRegistTaxAmount = nv;
                                        }
                                    }

                            }
                        }
                    }
                },
                {
                    field: 'registTaxAmount',
                    title: '已登记含税金额',
                    width: 100
                },
                {
                    field: 'alreadyApplyAmount',
                    title: '已冲账含税金额',
                    width: 100
                },
                {
                    field: 'paymentConditionDesc',
                    title: '付款条件',
                    width: 70,
                },
                {
                    field: 'customsBroker',
                    title: '报关公司',
                    width: 100,
                },{
                field: 'referPurchaseOrder',
                title: '参考采购订单',
                width:120,
                editor: {type: 'textbox',
                    options: {
                        required: true, editable: false, icons: [{
                            iconCls: 'icon-search', handler: function () {
                                debugger;
                                var supplierCode;
                                if ($('#supplierCode').hasClass('easyui-textbox')) {
                                    supplierCode = $('#supplierCode').textbox('getValue'); // EasyUI 方式
                                } else {
                                    supplierCode = $('#supplierCode').val(); // 普通 input 方式
                                }
                                let productTypeName =$(el.tb).datagrid('getEditor', {
                                    index: el.editIndex,
                                    field: 'theRegistTaxAmount'
                                }).target;
                                var newAmount = productTypeName.textbox("getValue");
                                if(Number(newAmount) <= 0){
                                    topWin.layer.alert("本次登记金额不能小于等于0，请填写", {icon: 0});
                                    return;
                                }
                              //  var supplierCode = $(el.supplierCode).textbox('getValue'); //供应商编码
                                var companyCode = $(el.companyCode).combobox('getValue'); //供应商对应公司编码
                                if (!supplierCode) {
                                    topWin.layer.msg('请先选择供应商信息', {icon: 0});
                                    return ;
                                }
                                if (!companyCode) {
                                    topWin.layer.msg('请先选择公司信息', {icon: 0});
                                    return ;
                                }
                                var selectRow =  $(el.tb).datagrid('getRows')[ el.editIndex];
                                var poCodeValue = selectRow.poCode;
                                var poItemNoValue = selectRow.poItemNo;
                               //  poCode,poItemNo
                                var url = g.ctx + "pc/finance/paymentAdvance/apply/choice/searchPrepaymentOrderInfo?supplierCode="+ supplierCode +"&companyCode=" + companyCode  +"&taxAmount="+ newAmount+'&poCode='+poCodeValue+'&poItemNo='+poItemNoValue;
                                choseSupplierDialog = openDialog('choseSupplierDialog', url, {
                                    title: '采购订单选择',
                                    width: '80%',
                                    height: '70%',
                                    cache: false,
                                    modal: true,
                                    border: 'thin',
                                    onClose: function () {
                                        choseSupplierDialog.dialog('destroy');
                                    },
                                    buttons: [
                                        {
                                            text: '确定',
                                            iconCls: 'icon-ok',
                                            handler: function () {
                                                topWin.frames['choseSupplierDialog'].chooseRow(function (data) {
                                                    $(el.tb).datagrid('updateRow', {
                                                        index: el.editIndex,
                                                        row: {
                                                            referPurchaseOrderItem: data[0].orderRow,
                                                            referPurchaseOrder: data[0].orderCode
                                                        }
                                                    });
                                                    endEditor();
                                                    choseSupplierDialog.dialog('close');
                                                });
                                            }
                                        },
                                        {
                                            text: '关闭',
                                            iconCls: 'icon-cancel',
                                            handler: function () {
                                                choseSupplierDialog.dialog('close');
                                            }
                                        }
                                    ]
                                });
                            }
                        }]
                    }
                }
            },
                {
                    field: 'referPurchaseOrderItem',
                    title: '参考采购订单行',
                    width:100
                },
                {
                    field: 'summary',
                    title: '摘要',
                    width: 200,
                    styler: function (value, row) {
                        if (row.poCode !== '合计') {
                            return 'background-color:#E1E1E1;';
                        }
                        return '';
                    },
                    editor: {type: 'textbox'}
                }
            ]
        ],
        toolbar:el.tbToolbar,
        onBeforeLoad: function () {
            $(el.tb).datagrid('reloadFooter',
                [
                    {
                        poCode: '合计',
                        theRegistTaxAmount: 0, //本次登记含税金额
                        alreadyApplyAmount: 0  //已冲账含税金额
                    }
                ]
            );
        },
        onLoadSuccess: function () {
            $(el.tb).datagrid('clearSelections');
        },
        onClickRow: function (index) {
            if (optType!==2){
                if (el.editIndex !== undefined) {
                    endEditor();
                    $(el.tb).datagrid('beginEdit', index);
                    el.editIndex = index;
                } else {
                    $(el.tb).datagrid('beginEdit', index);
                    el.editIndex = index;
                }
            }
            debugger;
            var dataType = $(el.dataType).combobox('getValue');
            // 在开始编辑后，再次检查并设置只读
            if (dataType === 1) {
                var editors = $(el.tb).datagrid('getEditors', index);
                // 假设 referPurchaseOrder 是第N个编辑器，需要根据实际顺序调整
                // 这里需要根据你的列顺序确定正确的索引
                if (editors.length > 13) { // 假设 referPurchaseOrder 是第14个编辑器
                    editors[13].target.textbox('readonly');
                }
                if (editors.length > 14) { // 假设 referPurchaseOrderIte 是第15个编辑器
                    editors[14].target.textbox('readonly');
                }
            }
            $(this).datagrid('selectRow', index); // 点击行时选中该行
        }
    });
}

// function updateColumnReadonly(dataType) {
//     debugger;
//     var referPurchaseOrderCol = $(el.tb).datagrid('getColumnOption', 'referPurchaseOrder');
//     var referPurchaseOrderIteCol = $(el.tb).datagrid('getColumnOption', 'referPurchaseOrderIte');
//
//     if (dataType == 1) {
//         // 设置为只读
//         referPurchaseOrderCol.editor.options.readonly = true;
//         referPurchaseOrderIteCol.editor.options.readonly = true;
//     } else {
//         // 恢复可编辑
//         referPurchaseOrderCol.editor.options.readonly = false;
//         referPurchaseOrderIteCol.editor.options.readonly = false;
//     }
//
//     // 刷新所有行以应用样式
//     $(el.tb).datagrid('getRows').forEach(function(row, index) {
//         $(el.tb).datagrid('refreshRow', index);
//     });
// }
function endEditor() {
    $(el.tb).datagrid('endEdit', el.editIndex);
    el.editIndex = undefined;
    summaryItemAmount();
}


/**
 * 查询订单
 */
// function searchOrder() {
//     var companyCode = $(el.companyCode).combobox('getValue'),
//         supplierCode = $(el.supplierCode).val(), 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/finance/paymentAdvance/apply/choice/searchAdvanceOrder?companyCode=' + companyCode + '&supplierCode=' + supplierCode + '&currencyCode=' + currencyCode+ '&advanceFlag=1',
//         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 = [];
//                 let poIds = [];
//                 for (let i = 0; i < rows.length; i++) {
//                     if (rows[i].supplierName2){
//                         $(el.faSupplier).combobox('setValue',rows[i].customsBrokerCode);
//                         $(el.faSupplierName).val(rows[i].customsBroker);
//                     }
//                     poCodes.push(rows[i].poCode);
//                    // poIds.push(rows[i].id);
//                 }
//
//               //  findESgin(poIds) 暂时不用显示签署文件
//                 findPoData(poCodes);
//                 parent.layer.close(index);
//             });
//         }
//     });
// }

/**
 * 2025-07-27
 * 根据选择的预付款订单信息回填到页面
 *
 */


/**
 * 2025-07-26
 * 查询预付款订单数据
 */
function searchPrepaidOrder() {
    var companyCode = $(el.companyCode).combobox('getValue'),
        supplierCode = $(el.supplierCode).val(), currencyCode = $(el.currencyCode).combobox('getValue');

    var dataType = $(el.dataType).combobox('getValue');
    if(dataType === null || dataType === undefined || dataType === '' ){
        topWin.layer.msg('请先选择数据类型', {icon: 0});
        return false;
    }

    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/finance/paymentAdvance/apply/choice/searchAdvanceOrder?companyCode=' + companyCode + '&supplierCode=' + supplierCode + '&currencyCode=' + currencyCode+ '&advanceFlag=1'+'&dataType='+dataType,
        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 = [];
                let appNos =[];
                for (let i = 0; i < rows.length; i++) {
                    if (rows[i].supplierName2){
                        $(el.faSupplier).combobox('setValue',rows[i].customsBrokerCode);
                        $(el.faSupplierName).val(rows[i].customsBroker);
                    }
                    poCodes.push(rows[i].poCode);
                    //appNo //预付款申请单号
                    //itemNo //预付款申请行号
                    appNos.push(rows[i].appNo+"_"+rows[i].itemNo);

                }
                prepaidOrderData(rows,appNos);
                parent.layer.close(index);
            });
        }
    });
}

/**
 * 根据输入的采购订单号id获取签署附件
 *
 * @param poIds 采购订单号Id
 */

function prepaidOrderData(rows,appNos) {//rows是订单的选择行
debugger;
    var query = {};
    const keyMap = {}; // 用于记录每个 Key 的出现次数
    //校验订单号是否重复
    let rows1 = $(el.tb).datagrid('getRows'); //是主页面的选择行
    for (let i = 0; i < rows1.length; i++) {
        //包含重复项
        if (appNos.indexOf(rows1[i].appNo+"_"+rows1[i].appItemNo) !== -1) {
            layer.msg("预付款单号" + rows1[i].appNo +"预付款行号"+ rows1[i].appItemNo+"重复");
            return false;
        }
    }
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    for (let i = 0; i < rows.length; i++) {
        dataGirdAddRow(rows[i]);
    };
    sumRecordedAndreversedAmount();
    summaryItemAmount();
    top.layer.close(loading);
}


/**
 * 表格添加数据
 *
 * @param item 待添加的数据
 */
function dataGirdAddRow(item) {
    debugger;
    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].dataKey === poKey) {
                rowIndex = $(el.tb).datagrid('getRowIndex', rows[i]);
                break;
            }
        }
    } else {
        el.existedData.push(poKey);
    }

    var row = {
        poKey: item.dataKey,
        appNo: item.appNo,
        appItemNo: item.itemNo,
        poCode: item.poCode,
        poItemNo: item.poItemNo,
        poNum: item.poNum,
        createUserName: item.createUserName,
        factoryCode: item.factoryCode,
        materialCode: item.materialCode,
        materialDesc: item.materialDesc,
        taxCode: item.taxCode,
        itPrice: item.itPrice,
        itAmount: item.itAmount,
        cantRegistTaxAmount: item.cantRegistTaxAmount,
        registTaxAmount: item.registTaxAmount,
        theRegistTaxAmount:item.cantRegistTaxAmount,
        prepaymentAmountInclusiveTax:item.budOutMoney,
        paymentConditionCode: item.paymentConditionCode,
        customsBroker: item.customsBroker,
        customsBrokerCode: item.customsBrokerCode,
        supplierCode1: item.supplierCode,
        supplierName1: item.supplierName,
        currencyCode: item.currencyCode
    };
    if (-1 === rowIndex) {
        row.summary = '';
        $(el.tb).datagrid('appendRow', row);
    } else {
        $(el.tb).datagrid('updateRow', {
            index: rowIndex,
            row: row
        });
    }
}

function getAName(){
    return "alreadyAdvanceAmount_new";
}

function summaryItemAmount() {
    debugger;
    var rows = $(el.tb).datagrid('getRows');
    var theRegistTaxAmount = new BigNumber(0);//本次登记金额
    var alreadyApplyAmount = new BigNumber(0) ;//已冲账金额
    for (var j = 0; j < rows.length; j++) {
        var item = rows[j], rowIndex = $(el.tb).datagrid('getRowIndex', item);
        if(el.editIndex !== undefined && rowIndex === el.editIndex){
            var editors = $(el.tb).datagrid('getEditors', el.editIndex);
            var edittheRegistTaxAmount = $(editors[0].target).numberbox('getValue');

            theRegistTaxAmount = theRegistTaxAmount.plus(edittheRegistTaxAmount?edittheRegistTaxAmount:0);
            var editalreadyApplyAmount = $(editors[1].target).numberbox('getValue');
            alreadyApplyAmount = alreadyApplyAmount.plus(editalreadyApplyAmount?editalreadyApplyAmount:0);
        } else {
            theRegistTaxAmount = theRegistTaxAmount.plus(item.theRegistTaxAmount);
            alreadyApplyAmount = alreadyApplyAmount.plus(item.alreadyApplyAmount);
        }

    }
    if(theRegistTaxAmount.isNegative()&&theRegistTaxAmount.isZero()&&theRegistTaxAmount.isPositive()){
        console.log("进入方法判断1");
    }
    if(alreadyApplyAmount.isNegative()&&alreadyApplyAmount.isZero()&&alreadyApplyAmount.isPositive()){
        console.log("进入方法判断2");
    }

    // 更新页脚行的值并刷新
    var footers = $(el.tb).datagrid('getFooterRows');
    footers[0]['theRegistTaxAmount'] = theRegistTaxAmount.toFixed(2);
    footers[0]['alreadyApplyAmount'] = alreadyApplyAmount.toFixed(2);
    $(el.tb).datagrid('reloadFooter');
    $('#recordedAmount').numberbox('setValue', theRegistTaxAmount.toFixed(2));
    $('#reversedAmount').numberbox('setValue', alreadyApplyAmount.toFixed(2));
}

function sumRecordedAndreversedAmount() {
    debugger;
    var rows = $(el.tb).datagrid('getRows');
    var theRegistTaxAmount = new BigNumber(0);//本次登记金额
    var alreadyApplyAmount = new BigNumber(0) ;//已冲账金额
    for (var j = 0; j < rows.length; j++) {
            theRegistTaxAmount = theRegistTaxAmount.plus(rows[j].theRegistTaxAmount ? rows[j].theRegistTaxAmount : 0);
            alreadyApplyAmount = alreadyApplyAmount.plus(rows[j].alreadyApplyAmount ? rows[j].theRegistTaxAmount : 0);
        }
    if(theRegistTaxAmount.isNegative()&&theRegistTaxAmount.isZero()&&theRegistTaxAmount.isPositive()){
        console.log("进入方法判断1");
    }
    if(alreadyApplyAmount.isNegative()&&alreadyApplyAmount.isZero()&&alreadyApplyAmount.isPositive()){
        console.log("进入方法判断2");
    }
    //更新页脚行的值并刷新
    var footers = $(el.tb).datagrid('getFooterRows');
    footers[0]['theRegistTaxAmount'] = theRegistTaxAmount.toFixed(2);
    footers[0]['alreadyApplyAmount'] = alreadyApplyAmount.toFixed(2);
    $(el.tb).datagrid('reloadFooter');
    $('#recordedAmount').numberbox('setValue', theRegistTaxAmount.toFixed(2));
    $('#reversedAmount').numberbox('setValue', alreadyApplyAmount.toFixed(2));
}





/**
 * 删除
 */
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: '预付款申请明细'
    });
}

/**
 * 初始化页面下拉框
 */
function initPageComBoBox() {
    var isSupplier = $(el.isSupplier).val();
    // 初始化公司代码下拉框
    $(el.companyCode).combobox({
        url: g.ctx + 'pc/sys/company/rest/listAll?isAuthority=' + (Number(isSupplier) === 1 ? 0 : 1),
        required: true,
        editable: false,
        valueField: 'companyCode',
        textField: 'codeWithDesc',
        panelHeight: 'auto',
        prompt: '--- 请选择 ---',
        onSelect: function (data) {
            $(el.companyName).val(data.companyName);
            //清空表格数据
            var oriCc = $(el.companyCode).combobox('getValue');
            if(oriCc !== data.companyCode){
                $('#tb').datagrid('loadData', {total: 0, rows: []})
            }
        }
    });
    $(el.advancePaymentFlag).combobox({
        required: false,
        editable: false,
        valueField: 'dicId',
        textField: 'dicTxt',
        panelHeight: 'auto',
        data: [
            {dicTxt: '是', dicId: "1"},
            {dicTxt: '否', dicId: "0"}
        ],
        onLoadSuccess: function(data){
            if(optType===0){
                $(this).combobox('setValue', "0");
            }
        }
    });

    $(el.acceptanceMethod).combobox({
        required: false,
        url: g.ctx + 'pc/sys/dict/getDicByType?type=supplier_accetp_deadline',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '--- 请选择 ---',
        editable: false
    });
    $(el.faSupplier).combobox({
        required: false,
        url: g.ctx + 'pc/sys/dict/getDicByType?type=customs_broker',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '--- 请选择 ---',
        editable: false,
        onSelect: function (data) {
            $(el.faSupplierName).val(data.name);
        }
    });


    initDict("currency")
    // 初始化币种下拉框
    $(el.currencyCode).combobox({
        required: true,
        panelHeight: 'auto',
        valueField: 'code',
        textField: 'codeWithDesc',
        data:getDictList("currency"),
        onSelect: function (data) {
            //清空表格数据
            var oriCc = $(el.currencyCode).combobox('getValue');
            if(oriCc !== data.code){
                $('#tb').datagrid('loadData', {total: 0, rows: []})
            }
            if (data.code==='CNY'){
                $(el.supBankCode).combobox({ required: true });
                $(el.bankInterCode).combobox({ required: false });
            }else {
                $(el.supBankCode).combobox({ required: false });
                $(el.bankInterCode).combobox({ required: true });
            }
        }
    });

    //经办人  -- 采购组
    $(el.oaHandlerCode).combobox({
        required: true,
        url: g.ctx + 'pc/sys/dict/getDicByType?type=statement_apply_list',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '--- 请选择 ---',
        editable: false,
        onSelect: function (data) {
            $(el.oaHandler).val(data.name);
        }
    });




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

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

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

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

    initDict("status")
    initDict("data_type")

    // 初始化状态下拉框
    $(el.dataType).combobox({
        required: true,
        panelHeight: 'auto',
       /* url: g.ctx + 'pc/sys/dict/getDicByType?type=data_type',*/
        // method: 'GET',
        valueField: 'code',
        textField: 'codeWithDesc',
        data:getDictList("data_type"),
        // prompt: '--- 请选择 ---',
        // editable: false,
        onSelect: function (data) {
            // $(el.dataType).val(data.name);


        }
    });

    $(el.dataStatus).combobox({
        required: true,
        panelHeight: 'auto',
        valueField: 'code',
        textField: 'codeWithDesc',
        data:getDictList("status"),
        editable: false,
        readonly: true,
        onSelect: function (data) {
            // $(el.dataType).val(data.name);
        },onLoadSuccess: function() {
            // 当数据加载完成后检查是否有值，没有则设置默认值
            var currentValue = $(this).combobox('getValue');
            if (!currentValue) {
                $(this).combobox('setValue', 0); // 设置默认值 0
            }
        }
    });

    /**
     * 初始化供应商选择
     */
    $(el.supplierName).textbox({
        prompt: '请选择供应商',
        required: true,
        icons: [
            {
                iconCls: 'icon-search',
                handler: function () {
                    if (optType!==2){
                        choseSupplier();
                    }
                }
            }
        ]
    });
    // $(el.supplierName).textbox('textbox').css('cursor', 'pointer');
    // $(el.supplierName).textbox('textbox').bind('click', function () {
    //     if (optType!==2){
    //         choseSupplier();
    //     }
    // });


    var supplierId = $('#supplierId').val();
    if(supplierId !== ''){
        findSupBankDataBySupplierCode(supplierId,$(el.currencyCode).combobox('getValue'));
    }

}

/**
 * 选择供应商
 */
function choseSupplier() {
    var url = g.ctx + "pc/supplier/purchaseCategory/page/selector?single=1";
    var userOrgyDialog = openDialog('userOrgyDialog', url, {
        title: "选择供应商",
        width: '80%',
        height: '70%',
        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.supplierName).textbox('setValue', cbox[0].supplierName);
                        $(el.supplierCode).val(cbox[0].supplierCode);
                        $(el.companyCode).combobox('setValue',cbox[0].companyCode);
                        $(el.currencyCode).combobox('setValue',cbox[0].currencyCode);
                        $(el.paymentWayCode).combobox('setValue',cbox[0].paymentMethod);
                        // findFaSupplierBySupplierCode(cbox[0].supplierCode);
                        findSupBankDataBySupplierCode(cbox[0].supplierId,cbox[0].currencyCode);
                        //清空表格数据
                        $('#tb').datagrid('loadData', {total: 0, rows: []})
                        userOrgyDialog.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                handler: function () {
                    userOrgyDialog.dialog('close');
                }
            }
        ]
    });
}
/**
 * 根据采购订单编号获取付款信息
 * @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 findFaSupplierBySupplierCode(supplierCode) {
    $.ajax({
        url: g.ctx + 'pc/supplier/supRelationBid/rest/getBySupplierCode?supplierCode=' + supplierCode,
        type: 'POST',
        success: function (res) {
            $(el.faSupplier).val(res.faSupplier);
            $(el.faSupplierName).textbox('setValue',res.faSupplierName);
        }
    });
}
/**
 * 根据供应商编码获取供应商开户行信息
 *
 * @param supplierId 供应商id
 */
function findSupBankDataBySupplierCode(supplierId,currencyCode) {
    console.log(5555555555555555)
    console.log(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',
                editable: false,
                disabled: false,
                required: currencyCode==='CNY',
                onLoadSuccess: function (data) {
                    // if (data.length === 1) {
                    if (optType===0){
                        $(el.supBankCode).combobox('setValue', data[0].supBankCode);
                        $(el.supBankName).val(data[0].supBankName);
                    }


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

/**
 * 获取供应商开户行对应的银行账号
 *
 * @param data 供应商银行账号信息
 * @param bankCode 供应商开户行编码
 */
function findSupplierBankAccount(data, bankCode,currencyCode) {
    var baData = [], eba = [], bankCodeData = [], bankInterCodeData = [];
    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);

            var obj1 = {};
            obj1.bankCode = data[i].bankCode;
            bankCodeData.push(obj1);

            var obj2 = {};
            obj2.bankInterCode = data[i].bankInterCode;
            bankInterCodeData.push(obj2);

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

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

            // }
        }
    });

    $(el.bankCode).combobox({
        data: bankCodeData,
        valueField: 'bankCode',
        textField: 'bankCode',
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        editable: false,
        disabled: false,
        required: currencyCode==='CNY',
        onLoadSuccess: function (data) {
            // if (data.length === 1) {
            if (optType===0){
                $(el.bankCode).combobox('setValue', data[0].bankCode);
            }

            // }
        }
    });

    $(el.bankInterCode).combobox({
        data: bankInterCodeData,
        valueField: 'bankInterCode',
        textField: 'bankInterCode',
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        editable: false,
        disabled: false,
        required: currencyCode!=='CNY',
        onLoadSuccess: function (data) {
            // if (data.length === 1) {
            if (optType===0){
                $(el.bankInterCode).combobox('setValue', data[0].bankInterCode);
            }

            // }
        }
    });
}


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

    var rows = $(el.tb).datagrid('getRows');
    if (rows.length === 0) {
        topWin.layer.alert('请添加采购订单数据', {icon: 0});
        return false;
    }
    var paymentChangeNo = rows[0].paymentChangeNumber;
    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});

    $.ajax({
        url: g.ctx + 'pc/finance/paymentAdvanceRefundTransferApply/apply/rest/refundTransferApply/confirm',
        type: 'POST',
        data:{paymentChangeNo:paymentChangeNo,approvalOpinion:$(el.approvalOpinion).val(),status:3},
        success: function () {
            topWin.layer.close(loading);
            callback();
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });

}



function refuse(callback) {
    debugger;
    var rows = $(el.tb).datagrid('getRows');
    if (rows.length === 0) {
        topWin.layer.alert('请添加采购订单数据', {icon: 0});
        return false;
    }
    var paymentChangeNo = rows[0].paymentChangeNumber;
    var approvalOpinion = $(el.approvalOpinion).val();//审批意见

    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({

        url: g.ctx + 'pc/finance/paymentAdvanceRefundTransferApply/apply/rest/refundTransferApply/confirm',
        type: 'POST',
        data:{paymentChangeNo:paymentChangeNo,approvalOpinion:$(el.approvalOpinion).val(),status:2},
        success: function () {
            topWin.layer.close(loading);
            callback();
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });

}

/**
 * 处理待保存数据
 *
 * @param rows 明细数据
 * @returns {boolean} 结果
 */
function handleWaitSaveData(rows) {
    var headData = {};
    var  paymentChangeNo = $(el.paymentChangeNo).val();
    if ($('#headForm').form('validate') ) {
        headData = $('#headForm').serializeJson();
        headData.files = $(el.files).attr('data-fileIds');
    } else {
        layer.msg("红色框为必输项，请填写！");
        return false;
    }
    debugger;
    var itemList = [];
    for (var i = 0; i < rows.length; i++) {
        var obj = {}, item = rows[i];
        if (optType===0){
            obj.appId = 0;
            obj.paymentChangeNo = '';
        }else {
            obj.id = item.id;
            obj.appId = $(el.id).val();
            obj.paymentChangeNo = paymentChangeNo;
        }
        //头信息
        headData.paymentChangeNo = paymentChangeNo;//付款变更单号
        headData.appNo = $(el.supplierName).val();//供应商名称
        headData.supplierCode = $(el.supplierCode).val(); //供应商编码
        headData.companyCode = $('#companyCode').combobox('getValue'); //公司
        headData.dataType = $('#dataType').combobox('getValue'); //$(el.dataType).val();//数据类型
        headData.status = $('#status').combobox('getValue'); //$(el.status).val();//数据状态
        headData.recordedAmount = $(el.recordedAmount).val();//登记金额
        headData.reversedAmount = $(el.reversedAmount).val();//已冲账金额
        //headData.approvalOpinion = $(el.approvalOpinion).val();//审批意见
        headData.remark = $(el.remark).val();//备注(说明)

        //明细信息
        obj.paymentChangeNo = paymentChangeNo;
        obj.appNo = item.appNo;//预付款申请单号
        obj.appItemNo = item.appItemNo;//预付款申请行号
        obj.poCode= item.poCode;//采购订单号
        obj.poItemNo= item.poItemNo;//采购订单行号
        obj.dataKey = item.dataKey;//联合主键
        obj.createUserName = item.createUserName;//预付款单创建人
        obj.poNum = item.poNum;//订单数量
        obj.factoryCode = item.factoryCode;//工厂代码
        obj.materialCode = item.materialCode;//物料代码
        obj.materialDesc = item.materialDesc;//物料描述
        obj.taxCode = item.taxCode;//税率代码
        obj.itPrice = item.itPrice;//含税单价
        obj.itAmount = item.itAmount;//含税金额
        obj.prepaymentAmountInclusiveTax = item.prepaymentAmountInclusiveTax;//已付预付款含税金额
        obj.cantRegistTaxAmount = item.cantRegistTaxAmount;//可登记含税金额
        obj.theRegistTaxAmount = item.theRegistTaxAmount;//本次登记含税金额
        obj.registTaxAmount = item.registTaxAmount;//已登记含税金额
        obj.alreadyApplyAmount = item.alreadyApplyAmount;//已冲账含税金额
        obj.paymentWayCode = item.paymentWayCode;//付款方式代码
        obj.paymentWayDesc = item.paymentWayDesc;//付款方式描述
        obj.paymentConditionDesc = item.paymentConditionDesc;//付款条件
        obj.customsBroker = item.customsBroker;//报关公司
        obj.referPurchaseOrder = item.referPurchaseOrder;//参考采购订单
        obj.referPurchaseOrderItem = item.referPurchaseOrderItem;//参考采购订单行
        obj.summary = item.summary;//摘要
        itemList.push(obj);
    }
    headData.itemList = itemList;
    headData.delItemIdList = '';

    return headData;
}

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

    var rows = $(el.tb).datagrid('getRows');
    if (rows.length === 0) {
        topWin.layer.alert('请添加采购订单数据', {icon: 0});
        return false;
    }
    var attachData1 = $("#files").attr('data-fileIds')
    if(!attachData1){
        topWin.layer.alert('请上传合同附件!', {icon: 0});
        return false;
    }
    var dataType = $('#dataType').combobox('getValue');
    for (var i = 0; i < rows.length; i++) {
        debugger;
        let item = rows[i];
        var referPurchaseOrdeValue =  item.referPurchaseOrder;
        var  referPurchaseOrderItemValue  = item.referPurchaseOrderItem;
        if ((referPurchaseOrdeValue === undefined || item.referPurchaseOrder == "") && dataType == 0) {
            topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '是转单类型，参考采购订单必填，请填写！', {icon: 0});
            return false;
        }
        if ((referPurchaseOrderItemValue === undefined || item.referPurchaseOrderItem) == "" && dataType == 0) {
            topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '是转单类型，参考采购订单行必填，请填写', {icon: 0});
            return false;
        }
        if (dataType != 0) {
            if(referPurchaseOrdeValue !== undefined){
                if(item.referPurchaseOrder != "" ){
                    topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '不是转单类型不允许填写参考采购订单，请清空!', {icon: 0});
                    return false;
                }
            }
            if(referPurchaseOrderItemValue !== undefined){
                if (item.referPurchaseOrderItem != "") {
                    topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '不是转单类型不允许填写参考采购订单行，请清空！', {icon: 0});
                    return false;
                }
            }
        }
debugger;

        if(Number(item.theRegistTaxAmount) <= 0){
            topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '本次登记金额不能小于等于0，请填写', {icon: 0});
            return false;
        }

        if(Number(item.theRegistTaxAmount)  > Number(item.cantRegistTaxAmount)){
            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);
    mainData.files =  attachData1;
    if (!mainData) {
        return false;
    }
    mainData.saveType = optType===0?1:2
    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'pc/finance/paymentAdvanceRefundTransferApply/apply/rest/refundTransferApply/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});
        }
    });
}

/**
 * 更新申请金额登记金额和已冲账金额
 *
 * @param data
 * @param key 节点
 */
function updateRowData_(data,key) {
    debugger;
    var rows = $(el.tb).datagrid('getRows');
    if(key == "theRegistTaxAmount"){//本次登记含税金额
        let theRegistTaxAmount = new BigNumber(0);
        for (var j = 0; j < rows.length; j++) {
            var item = rows[j];
            var rowIndex = $(el.tb).datagrid('getRowIndex', item);
            if(rowIndex === el.editIndex){
                theRegistTaxAmount = theRegistTaxAmount.plus(data);
            }else {
                theRegistTaxAmount = theRegistTaxAmount.plus(item.theRegistTaxAmount);
            }
        }
        var footers = $(el.tb).datagrid('getFooterRows');
        footers[0]['theRegistTaxAmount'] = theRegistTaxAmount.toFixed(priceHandle.precision)?theRegistTaxAmount.toFixed(priceHandle.precision):0;
        $(el.tb).datagrid('reloadFooter');
        $('#recordedAmount').numberbox('setValue', theRegistTaxAmount.toFixed(priceHandle.precision));
    }else if(key == "alreadyApplyAmount"){//已冲账含税金额
        let alreadyApplyAmount = new BigNumber(0);
        for (var j = 0; j < rows.length; j++) {
            var item = rows[j];
            var rowIndex = $(el.tb).datagrid('getRowIndex', item);
            if(rowIndex === el.editIndex){
                alreadyApplyAmount = alreadyApplyAmount.plus(data);
            }else {
                alreadyApplyAmount = alreadyApplyAmount.plus(item.alreadyApplyAmount);
            }
        }
        var footers = $(el.tb).datagrid('getFooterRows');
        footers[0]['alreadyApplyAmount'] = alreadyApplyAmount.toFixed(priceHandle.precision)?alreadyApplyAmount.toFixed(priceHandle.precision):0;
        $(el.tb).datagrid('reloadFooter');
        $('#reversedAmount').numberbox('setValue', alreadyApplyAmount.toFixed(priceHandle.precision));
    }
    summaryItemAmount();
}