var el = {
    files: '#files',
    isSupplier: '#isSupplier',
    id: '#id',
    tb3: '#tb3',
    dataPanel: '#dataPanel',
    dataDiv: '#dataDiv',
    companyCode: '#companyCode',
    refundAmount: '#refundAmount',
    businessCodes: [],
    businessPurchaseCodeAndDeliveryCode: [],
    factoryCode: '#factoryCode',
    supplierCode: '#supplierCode',
    paymentSupplierCode: '#paymentSupplierCode',
    supplierName: '#supplierName',
    poSatisfyFlag: '#poSatisfyFlag',
    imgCode: '#imgCode',
    poImgCode: '#poImgCode',
    paymentSupplierName: '#paymentSupplierName',
    paymentFilesTr: '#paymentFilesTr',
    paymentFiles: '#paymentFiles',
    collectionFlag: '#collectionFlag',
    currencyCode: '#currencyCode',
    tbAttachment: '#tbAttachment',
    tbAttachmentCheck: '#tbAttachmentCheck',
    paymentCompanyCode: '#paymentCompanyCode',
    paymentCompanyName: '#paymentCompanyName',
    bankAddress: '#bankAddress',
    overdueAmount: '#overdueAmount',
    dueAmount: '#dueAmount',
    accountsPayableBalance: '#accountsPayableBalance',
    provisionalBalance: '#provisionalBalance',
    originalSignRows: [],
    supBankCode: '#supBankCode',
    supBankName: '#supBankName',
    bankCode: '#bankCode',
    bankInterCode: '#bankInterCode',
    supBankAccount: '#supBankAccount',
    paymentWayCode: '#paymentWayCode',
    advancePaymentFlag: '#advancePaymentFlag',
    acceptanceMethod: '#acceptanceMethod',
    faSupplier: '#faSupplier',
    businessType: '#businessType',
    feePayer: '#feePayer',
    advanceType: '#advanceType',
    urgentFlag: '#urgentFlag',
    faSupplierName: '#faSupplierName',
    paymentWayDesc: '#paymentWayDesc',
    ptcComBoBox: '#ptcComBoBox',
    paymentTermCode: '#paymentTermCode',
    paymentTermDesc: '#paymentTermDesc',
    applyPaymentAmount: '#applyPaymentAmount',
    applyRemark: '#applyRemark',
    apApplyNo: '#apApplyNo',
    oaHandler: '#oaHandler',
    payPlanMoney: '#payPlanMoney',
    oaHandlerCode: '#oaHandlerCode',
    paymentPurpose: '#paymentPurpose',
    paymentPurposeDesc: '#paymentPurposeDesc',
    tb: '#tb',
    tb2: '#tb2',
    tbLog: '#tbLog',
    tbToolbar:'#tbToolbar',
    existedData: [],
    tempDelTbData: [],
    chosePoDataDialog: [],
    editIndex: undefined,
    bodyHeight: document.documentElement.clientHeight
};
$(function () {
    $(el.dataPanel).panel({
        collapsible: true,
        onCollapse: function () {
            $(el.tb).datagrid('resize', {height: el.bodyHeight - 45});
        },
        onExpand: function () {
            var dataDivHeight = $(el.dataDiv).outerHeight();
            $(el.tb).datagrid('resize', {height: el.bodyHeight - dataDivHeight});
        }
    });
    if (optType === 2) {
        editInitFlag = true;
    }
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll,pc/sys/tax/rest/listAll')
    initDict('payment_method')
    initDictName('businessFileType')
    initPageComBoBox();

    initPageDataGrid();

    initPageDataGrid2();
    loadReceiptGrid();
    if ($(el.tbAttachment).length>0){
        loadTbAttachmentGrid();
    }
    initTbAttachmentCheck();
    iniTtbLog();
    $('#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)
            }
        }
    });
});

/**
 * 初始化页面表格数据
 */
function initPageDataGrid() {
    var dataDivHeight = $(el.dataDiv).outerHeight();
    var columns =
        [
            {
                field: 'factoryCode',
                title: '工厂',
                width: 80,
                sortable: true
            },
            {
                field: 'paymentExpireDate',
                title: '付款到期日',
                width: 100,
                exportDateFormatter:'date',
                formatter: function (value, row) {
                    if (!value) {
                        return '';
                    }
                    return '<span style="color: red;">' + moment(value).format('YYYY-MM-DD') + '</span>';
                }
            },
            {
                field: 'expectationPaymentDate',
                title: '期望付款日',
                width: 120,
                exportDateFormatter:'date',
                editor: {
                    type: 'datebox',
                },
                formatter: function (value, row) {
                    if (!value) {
                        return '';
                    }
                    return '<span style="color: red;">' + moment(value).format('YYYY-MM-DD') + '</span>';
                }
            },
            {
                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) {
                    return formatterPrice(value);
                }
            },
            {
                field: 'itAmount',
                title: '订单含税金额',
                width: 100,
                sortable: true,
                formatter:function (value) {
                    return formatterPrice(value);
                }
            },
            {
                field: 'applyAmount',
                title: '可申请金额',
                width: 100,
                sortable: true,
                formatter:function (value) {
                    return formatterPrice(value);
                }
            },
            // {
            //     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: priceHandle.precision,
                        onChange: function (nv) {
                            updateRowData(nv, 'budOutMoney');
                        }
                    }
                }
            },
            {
                field: 'storeAmount',
                title: '入库金额',
                width: 100,
                sortable: true,
                formatter:function (value) {
                    return formatterPrice(value);
                }
            },
            {
                field: 'discountMoney',
                title: '折扣金额',
                width: 100,
                sortable: true,
                editor: {
                    type: 'numberbox',
                    options: {
                        precision: priceHandle.precision,
                        onChange: function (nv) {
                            updateRowData(nv, 'discountMoney');
                        }
                    }
                }
            },
            {
                field: 'actualityPayMoney',
                title: '实际应付金额',
                width: 100,
                sortable: true,
                // formatter:function (value,row) {
                //     return formatterPrice(row.budOutMoney-row.discountMoney);
                // }
            },
            {
                field: 'alreadyApplyAmount',
                title: '已申请金额',
                width: 100,
                sortable: true,
                formatter:function (value) {
                    return formatterPrice(value);
                }
            },
            {
                field: 'alreadyAdvanceAmount',
                title: '已预付金额',
                width: 100,
                sortable: true,
                formatter:function (value) {
                    return formatterPrice(value);
                }
            },
            {
                field: 'poReversalMoney',
                title: '订单行冲账总金额',
                width: 120,
                sortable: true,
                formatter:function (value) {
                    return formatterPrice(value);
                }
            },
            {
                field: 'reversalMoney',
                title: '已冲账金额',
                width: 100,
                sortable: true,
                formatter:function (value) {
                    return formatterPrice(value);
                }
            },
            {
                field: 'alreadyAccountAmount',
                title: '已对账金额',
                width: 100,
                sortable: true,
                formatter:function (value) {
                    return formatterPrice(value);
                }
            },
            {
                field: 'alreadyOutAmount',
                title: '转出金额',
                width: 100,
                sortable: true,
                formatter:function (value) {
                    return formatterPrice(value);
                }
            },
            {
                field: 'alreadyIntoAmount',
                title: '转入金额',
                width: 100,
                sortable: true,
                formatter:function (value) {
                    return formatterPrice(value);
                }
            },
            {
                field: 'paymentConditionCode',
                title: '付款条件',
                width: 200,
                // editor: {
                //     type: 'combobox',
                //     options: {
                //         required: false,
                //         valueField: "code",
                //         textField: "codeWithDesc",
                //         data: getDictList('payment_method'),
                //         editable: false,
                //         panelHeight: '150'
                //     }
                // },
                formatter: function (value) {
                    return getDicName('payment_method',value);
                }
            },
            {
                field: 'supplierName1',
                title: '报关公司',
                width: 100,
                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
            // }
        ]

    //查看不能看到的字段
    if (optType===2){
        columns = columns.filter(obj => obj.field !== 'storeAmount');
        columns = columns.filter(obj => obj.field !== 'alreadyAccountAmount');
    }

    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/finance/paymentAdvance/apply/detail/rest/find/paa/detail',
        height: el.bodyHeight - dataDivHeight,
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        showFooter: true,
        queryParams: {
            applyId: $(el.id).val(),
            dataShowType: 1,
            optType: optType
        },
        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: [
            columns
        ],
        toolbar:el.tbToolbar,
        onBeforeLoad: function () {
            $(el.tb).datagrid('reloadFooter',
                [
                    {
                        poCode: '合计',
                        itAmount: 0,
                        budInnerMoney: 0,
                        budOutMoney: 0,
                        alreadyApplyAmount: 0,
                        alreadyAdvanceAmount: 0
                    }
                ]
            );
        },
        onLoadSuccess: function (data) {
            $(el.tb).datagrid('clearSelections');

            //业务编码集合
            var businessCodes = [];
            var purchaseCodeAndDeliveryCode = [];
            var detail = data.rows;
            for(var ii = 0; ii < detail.length; ii++){
                if (detail[ii].poCode){
                    businessCodes.push(detail[ii].poCode);
                }
                if (detail[ii].deliveryOrderCode){
                    purchaseCodeAndDeliveryCode.push(detail[ii].poCode+'_'+detail[ii].deliveryOrderCode.split(','));
                }
            }
            el.businessPurchaseCodeAndDeliveryCode= purchaseCodeAndDeliveryCode
            //businessCodes中去重
            if (businessCodes.length > 0){
                businessCodes = businessCodes.filter(function(item, index, self) {
                    return self.indexOf(item) === index;
                })
                purchaseCodeAndDeliveryCode = purchaseCodeAndDeliveryCode.filter(function(item, index, self) {
                    return self.indexOf(item) === index;
                })
                el.businessCodes = businessCodes;
                if ($(el.tbAttachment).length>0){
                    $(el.tbAttachment).datagrid('options').loadFilter = pagerSignFilter;

                    var attachmentTypeCreateConfigList = ($(el.currencyCode).combobox('getValue') === "CNY"&&$(el.advanceType).combobox('getValue') === "0")?
                        eval(attachmentTypeCreateConfigs):($(el.currencyCode).combobox('getValue') === "CNY"&&$(el.advanceType).combobox('getValue') === "1")?
                            eval(deliveryAttachmentTypeCreateConfigs):eval(overseasAttachmentTypeCreateConfigs);
                    //取attachmentTypeCreateConfigList中的code,逗号隔开
                    var attachmentTypeCreateConfigCodes = attachmentTypeCreateConfigList.map(function(item){
                        return item.code;
                    })
                    let url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes?businessIds='+$(el.id).val()+'&businessTypeCodes=payment_advance_apply';
                    if (optType===0||optType===1){
                        url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes?businessCodes='+businessCodes.join(',')+'&businessTypeCodes=purchase_order,purchase_order_sign,purchase_to_delivery_order'+'&types='+attachmentTypeCreateConfigCodes.join(',')+'&purchaseCodeAndDeliveryCodes='+purchaseCodeAndDeliveryCode.join('*');
                    }
                    $(el.tbAttachment).datagrid('options').url = url;
                    $(el.tbAttachment).datagrid('load');
                }
                // 销毁现有的表格
                try {
                    $(el.tbAttachmentCheck).datagrid('destroy');
                } catch (error) {
                    console.warn('发生异常，已忽略:', error.message);
                    // 或发送到错误监控系统
                }
                initTbAttachmentCheck();
            }
        },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;
                }
            }
        },onDeleteRow: function () {
            // 删除一行后同步刷新附件校验
            refreshAttachmentRelatedGrids();
        }

    });
}

function loadTbAttachmentGrid(){
    let toolbar = [];
    // if (optType === 0 || optType === 1 ) {
    // toolbar = [
    // {
    //     text: BJGL.BJGL__SC, iconCls: 'icon-add', hidden: true, handler: uploadAttachmentFile
    // }, "-", {
    //     text: BJGL.BJGL__SHANC, iconCls: 'icon-remove', handler: deleteAttachmentFile
    // // }, "-",
    // {
    //     text: "设置备注", iconCls: 'icon-remove', handler: remarkAttachmentFile
    // }
    // ];

    toolbar = [
        {
            text: '导出',
            iconCls: 'icon-download',
            handler: function () {
                detailRelationFileExport();
            }
        }
    ];
    // }

    // const url = g.ctx + 'pc/finance/paymentAdvance/apply/attachment/rest/list?appId=' + $(el.id).val()+'&reloadFlag='+(optType === 1?1:0)+'&businessTypeCodes=purchase_order';
    $(el.tbAttachment).datagrid({
        loadMsg: '数据加载中......',
        // url: url,
        height: '460px',
        width: '98%',
        pagination: true,
        autoRowHeight: true,
        remoteSort:false,
        fitColumns: true,
        checkbox: true,
        rownumbers: false,
        singleSelect: true,
        queryParams: {},
        columns: [[
            {
                field: 'type', title: "附件类型", sortable: true,width: '10%',  formatter: function (value) {
                    return getDicName('businessFileType',value)
                }
            },
            {
                field: 'imageCode', title: "影像编码", width: '10%'
            },
            {
                field: 'businessCode', title: "单据编号",sortable: true, width: '10%'
            },
            {
                field: 'fileId',
                title: '附件名称',
                width: '20%',
                formatter: function (value, row, index) {
                    return '<div class="supplier-file-form custom-file-form-style" data-options=\'{"deleteEnable":false, "previewEnable":true, "uploadEnable": false, "moreFileUploadEnable": true, "fileSize": 50, "fileTypes": ".xls,.doc,.txt,.pdf"}\' data-fileIds = "'+value+'"></div>';
                }
            },
            {
                field: 'signStatus',
                title: '签章状态',
                sortable: true,
                width: '5%',
                formatter: function (value) {
                    switch (value) {
                        case 0:
                            return '<span style="color: grey;">草稿</span>';
                        case 1:
                            return '<span style="color: blue;">签署中</span>';
                        case 2:
                            return '<span style="color: green;">完成</span>';
                        case 3:
                            return '<span style="color: orange;">已过期</span>';
                        case 4:
                            return '<span style="color: red;">已拒签</span>';
                        case 5:
                            return '<span style="color: dimgrey;">已作废</span>';
                        case 6:
                            return '<span style="color: blue;">作废中</span>';
                        case 7:
                            return '<span style="color: red;">已删除</span>';
                        default:
                            return '';
                    }
                }
            },
            {
                field: 'signOrder',
                title: '签章顺序',
                sortable: true,
                width: '5%',
                formatter: function (value) {
                    return getDicName('sign_order',value)
                }
            },
            {
                field: 'signatureType',
                title: '签章类别',
                sortable: true,
                width: '5%',
                formatter: function (value) {
                    return getDicName('sign_type',value)
                }
            },
            {
                field: 'remark', title: "备注", width: '10%'
            },
            {
                field: 'createTime', title: "上传时间"
            },
            {
                field: 'updateUser', title: "最近修改人"
            },
            {
                field: 'updateTime', title: "最近修改时间"
            }
        ]],
        toolbar: toolbar,
        loadFilter: pagerSignFilter,
        onLoadSuccess: async function (data) {
            if (data.rows.length>0){
                initFileForm('supplier-file-form');
            }
            const allRows = await getAllBusinessData(data.rows);
            if (el.businessCodes.length>0){
                var checkRows = [];
                var attachmentTypeCreateConfigList = ($(el.currencyCode).combobox('getValue') === "CNY"&&$(el.advanceType).combobox('getValue') === "0")?
                    eval(attachmentTypeCreateConfigs):($(el.currencyCode).combobox('getValue') === "CNY"&&$(el.advanceType).combobox('getValue') === "1")?
                        eval(deliveryAttachmentTypeCreateConfigs):eval(overseasAttachmentTypeCreateConfigs);
                var attachmentTypeCheckConfigList = ($(el.currencyCode).combobox('getValue') === "CNY"&&$(el.advanceType).combobox('getValue') === "0")?
                    eval(attachmentTypeCheckConfigs):($(el.currencyCode).combobox('getValue') === "CNY"&&$(el.advanceType).combobox('getValue') === "1")?
                        eval(deliveryAttachmentTypeCheckConfigs):eval(overseasAttachmentTypeCheckConfigs);
                el.businessCodes.forEach(function (item) {
                    var obj = {};
                    obj.purchaseOrderNo = item;
                    attachmentTypeCreateConfigList.forEach(function (attachmentTypeCreateConfig) {
                        var exist = allRows.find(function (item2) {
                            return item2.businessCode === item && item2.type === attachmentTypeCreateConfig.code;
                        });
                        obj[attachmentTypeCreateConfig.code] = exist?1:0;

                        //物流供应商-invoice和物流供应商-packing list取值如果为空，再取这个附件类型，如果这个类型有附件，就代表物流供应商-invoice和物流供应商-packing list都有值
                        if (attachmentTypeCreateConfig.code==='agent_supplier_invoice'){
                            if (obj[attachmentTypeCreateConfig.code]===0){
                                var exist1 = allRows.find(function (item2) {
                                    return item2.businessCode === item && item2.type === 'invoice_and_packing_list';
                                });
                            }
                            obj[attachmentTypeCreateConfig.code] = exist1?1:0;
                        }
                        if (attachmentTypeCreateConfig.code==='agent_supplier_packing_list'){
                            if (obj[attachmentTypeCreateConfig.code]===0){
                                var exist2 = allRows.find(function (item2) {
                                    return item2.businessCode === item && item2.type === 'invoice_and_packing_list';
                                });
                            }
                            obj[attachmentTypeCreateConfig.code] = exist2?1:0;
                        }

                        //加强采购订单关联送货单附件逻辑
                        if (attachmentTypeCreateConfig.code==='delivery_order'){
                            el.businessPurchaseCodeAndDeliveryCode.forEach(function (purchaseCodeAndDeliveryCode) {
                                console.log(purchaseCodeAndDeliveryCode)
                                if (purchaseCodeAndDeliveryCode.includes(item)) {
                                    const result = purchaseCodeAndDeliveryCode.split('_')[1];
                                    console.log(result)
                                    // 判断是否包含
                                    var exist1 = allRows.find(function (item2) {
                                        return result.includes(item2.businessCode) && item2.type === 'delivery_order';
                                    });
                                    exist = exist1
                                    obj[attachmentTypeCreateConfig.code] = exist1?1:0;
                                }
                            });
                        }

                        //是否存在校验
                        var checkExist = false;
                        attachmentTypeCheckConfigList.forEach(function (attachmentTypeCheckConfig) {
                            if (attachmentTypeCheckConfig.code === attachmentTypeCreateConfig.code){
                                checkExist = true;
                            }
                        });
                        //如果不存在校验，但是文件也不存在，则文件状态为无需校验
                        if (!checkExist && !exist){
                            obj[attachmentTypeCreateConfig.code] = 2;
                        }
                        //存在校验，但是文件也不存在，则满足状态为不满足
                        if (checkExist && !exist){
                            obj.satisfyFlag = 0;
                            $(el.poSatisfyFlag).val(0)
                        }else {
                            obj.satisfyFlag = 1;
                        }

                    });
                    checkRows.push(obj);
                });

                // //allRows
                // el.businessCodes.forEach(function (item) {
                //     //判断allRows中是否存在businessCode和item相同且type为purchase_order的数据
                //     var purchase_order_exist = allRows.find(function (item2) {
                //         return item2.businessCode === item && item2.type === 'purchase_order';
                //     });
                //
                //     var obj = {
                //         "purchaseOrderNo": item,
                //         "purchaseOrderFile": purchase_order_exist?1:0,
                //         "satisfyFlag": (!purchase_order_exist)?0:1
                //     }
                //     checkRows.push(obj);
                // });
                // 销毁现有的表格
                debugger
                try {
                    $(el.tbAttachmentCheck).datagrid('destroy');
                } catch (error) {
                    console.warn('发生异常，已忽略:', error.message);
                    // 或发送到错误监控系统
                }
                initTbAttachmentCheck();
                $(el.tbAttachmentCheck).datagrid('loadData', {total: checkRows.length, rows: checkRows});
            }
        },
    });
}

function detailRelationFileExport() {

    var rows = $(el.tbAttachment).datagrid('getRows');
    $(el.tbAttachment).datagrid('toExcel', {
        filename: '附件清单数据.xls',
        rows: rows,
        worksheet: '附件清单'
    });
}

function initTbAttachmentCheck(){
    if (!$(el.currencyCode).combobox('getValue')){
        return false;
    }
    let toolbar = [];
    var attachmentTypeCreateConfigList = ($(el.currencyCode).combobox('getValue') === "CNY"&&$(el.advanceType).combobox('getValue') === "0")?
        eval(attachmentTypeCreateConfigs):($(el.currencyCode).combobox('getValue') === "CNY"&&$(el.advanceType).combobox('getValue') === "1")?
            eval(deliveryAttachmentTypeCreateConfigs):eval(overseasAttachmentTypeCreateConfigs);

    let columns = [
        {
            field: 'purchaseOrderNo', title: "采购订单号", sortable: true,width: attachmentTypeCreateConfigList.length>1?50:100
        }
    ];

    attachmentTypeCreateConfigList.forEach(function (attachmentTypeCreateConfig) {
        columns.push(
            {
                field: attachmentTypeCreateConfig.code, title: attachmentTypeCreateConfig.name+'附件', width: attachmentTypeCreateConfigList.length>1?50:100,sortable: true,
                formatter: function (value) {
                    if (value===1) {
                        return '<span style="color:green;">存在</span>';
                    }else if (value===0) {
                        return '<span style="color:red;">不存在</span>';
                    }else{
                        return '<span style="color:green;">无需校验</span>';
                    }
                }
            }
        );
    });
    columns.push(
        {
            field: 'satisfyFlag', title: "是否满足", width: attachmentTypeCreateConfigList.length>1?50:100,sortable: true,
            formatter: function (value) {
                if (value===1) {
                    return '<span style="color:green;">满足</span>';
                }
                return '<span style="color:red;">不满足</span>';
            }
        }
    )
    $(el.tbAttachmentCheck).datagrid({
        loadMsg: '数据加载中......',
        height: '460px',
        width: '98%',
        pagination: true,
        autoRowHeight: true,
        remoteSort:false,
        fitColumns: true,
        checkbox: true,
        rownumbers: false,
        singleSelect: true,
        columns: [columns],
        toolbar: toolbar,
    });
}

function pagerSignFilter(data) {
    if (typeof data.length == 'number' && typeof data.splice == 'function')     {   // is array
        data = {
            total: data.length,
            rows: data
        }
    }
    var dg = $(this);
    var opts = dg.datagrid('options');
    var pager = dg.datagrid('getPager');
    pager.pagination({
        onSelectPage: function (pageNum, pageSize) {
            opts.pageNumber = pageNum;
            opts.pageSize = pageSize;
            pager.pagination('refresh', {
                pageNumber: pageNum,
                pageSize: pageSize
            });
            dg.datagrid('loadData', data);
        }
    });
    if (!data.originalSignRows) {
        data.originalSignRows = (data.rows);
        el.originalSignRows = (data.rows);
    }
    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalSignRows.slice(start, end));
    return data;
}

/**
 * 查询订单
 */
function searchOrder() {
    var companyCode = $(el.companyCode).combobox('getValue'),advanceType = $(el.advanceType).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;
    }
    if (!advanceType) {
        topWin.layer.msg('请先选择预付方式', {icon: 0});
        return false;
    }
    parent.layer.open({
        title: '选择订单',
        content: '/pc/order/purchaseOrder/page/choice/order?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) {
                if (endEditor() === false) return;

                if (!isDatagridReady(el.tb)) {
                    console.warn('tb not ready, skip order bind');
                    return;
                }
                endEditor();
                let poCodes = [];
                let poIds = [];
                for (let i = 0; i < rows.length; i++) {
                    if (rows[i].supplierName2){
                        $(el.faSupplier).combobox('setValue',rows[i].supplierCode1);
                        $(el.faSupplierName).val(rows[i].supplierName1);
                    }
                    poCodes.push(rows[i].orderCode);
                    poIds.push(rows[i].id);
                }
                // findESgin(poIds)
                findPoData(poCodes);

                parent.layer.close(index);
            });
        }
    });
}


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

    var query = {};
    query.morePoQuery = JSON.stringify(poIds);
    query.applyId = 0;
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/sys/esign/rest/file/status/list?businessIds=' + poIds + '&businessTypeCode=purchase_order&signStatus=2',
        data: query,
        success: function (data) {
            if (data.length > 0) {
                let fileIdList = [];
                for (var i = 0; i < data.length; i++) {
                    fileIdList.push(data[i].fileId)
                }
                $('#files').attr('data-fileIds', fileIdList.join(','))
                $('#files').html('')
                initFileForm('custom-file-form')
            }
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}

/**
 * 根据输入的采购订单号获取采购订单信息
 *
 * @param poCodes 采购订单号
 */
function findPoData(poCodes) {
    if (!isDatagridReady(el.tb)) {
        console.warn('tb datagrid not ready, skip findPoData');
        return;
    }
    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;
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.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;
            }
            setTbAttachment();
            summaryItemAmount();

        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}

function setTbAttachment(){
    if (!isDatagridReady(el.tb)) {
        return;
    }
    //业务编码集合
    var businessCodes = [];
    var detail = $(el.tb).datagrid('getRows');;
    if(detail.length === 0){
        return;
    }
    var purchaseCodeAndDeliveryCode = [];
    for(var ii = 0; ii < detail.length; ii++){
        if (detail[ii].poCode){
            businessCodes.push(detail[ii].poCode);
        }
        if (detail[ii].deliveryOrderCode){
            purchaseCodeAndDeliveryCode.push(detail[ii].poCode+'_'+detail[ii].deliveryOrderCode.split(','));
        }
    }
    el.businessPurchaseCodeAndDeliveryCode= purchaseCodeAndDeliveryCode
    if (businessCodes.length > 0){
        businessCodes = businessCodes.filter(function(item, index, self) {
            return self.indexOf(item) === index;
        })
        purchaseCodeAndDeliveryCode = purchaseCodeAndDeliveryCode.filter(function(item, index, self) {
            return self.indexOf(item) === index;
        })
        el.businessCodes = businessCodes;
        if ($(el.tbAttachment).length>0){
            $(el.tbAttachment).datagrid('options').loadFilter = pagerSignFilter;

            var attachmentTypeCreateConfigList = ($(el.currencyCode).combobox('getValue') === "CNY"&&$(el.advanceType).combobox('getValue') === "0")?
                eval(attachmentTypeCreateConfigs):($(el.currencyCode).combobox('getValue') === "CNY"&&$(el.advanceType).combobox('getValue') === "1")?
                    eval(deliveryAttachmentTypeCreateConfigs):eval(overseasAttachmentTypeCreateConfigs);
            //取attachmentTypeCreateConfigList中的code,逗号隔开
            var attachmentTypeCreateConfigCodes = attachmentTypeCreateConfigList.map(function(item){
                return item.code;
            })
            let url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes?businessIds='+$(el.id).val()+'&businessTypeCodes=payment_advance_apply';
            if (optType===0||optType===1){
                url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes?businessCodes='+businessCodes.join(',')+'&businessTypeCodes=purchase_order,purchase_order_sign,delivery_order,purchase_to_delivery_order'+'&types='+attachmentTypeCreateConfigCodes.join(',')+'&purchaseCodeAndDeliveryCodes='+purchaseCodeAndDeliveryCode.join('*');
            }
            $(el.tbAttachment).datagrid('options').url = url;
            $(el.tbAttachment).datagrid('load');
        }
    }

}
/**
 * 表格添加数据
 *
 * @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 expectationPaymentDate = item.paymentExpireDate;
    if (isBlank(expectationPaymentDate)){
        //赋值今天
        expectationPaymentDate = moment().format('YYYY-MM-DD');
    }else {
        //如果expectationPaymentDate小于今天，则赋值今天
        if (moment(expectationPaymentDate).isBefore(moment())){
            expectationPaymentDate = moment().format('YYYY-MM-DD');
        }
    }
    var row = {
        poKey: item.poKey,
        poCode: item.poCode,
        poItemNo: item.poItemNo,
        poNum: item.poNum,
        seekPgCode: item.seekPgCode,
        seekPgName: item.seekPgName,
        factoryCode: item.factoryCode,
        deliveryOrderCode: item.deliveryOrderCode,
        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,
        poReversalMoney: item.poReversalMoney,
        applyAmount: item.applyAmount,
        budInnerMoney: item.budInnerMoney,
        storeAmount: item.storeAmount,
        budOutMoney: item.applyAmount,
        discountMoney: 0,
        reversalMoney: item.reversalMoney,
        paymentConditionCode: item.paymentConditionCode,
        paymentConditionName: item.paymentConditionName,
        pcCodeName: item.pcCodeName,
        paymentWayCode: item.paymentWayCode,
        paymentWayDesc: item.paymentWayDesc,
        quantityRange: item.quantityRange,
        supplierCode1: item.supplierCode1,
        supplierName1: item.supplierName1,
        supplierCode2: item.supplierCode2,
        supplierName2: item.supplierName2,
        contractNo:item.contractNo,
        contractName:item.contractName,
        paymentExpireDate:item.paymentExpireDate,
        expectationPaymentDate:expectationPaymentDate,
        alreadyAccountAmount:item.alreadyAccountAmount,
        alreadyOutAmount:item.alreadyOutAmount,
        alreadyIntoAmount:item.alreadyIntoAmount,
        buyer:item.buyer
    };
    if (-1 === rowIndex) {
        row.itemRemark = '';
        $(el.tb).datagrid('appendRow', row);
    } else {
        $(el.tb).datagrid('updateRow', {
            index: rowIndex,
            row: row
        });
    }
}

function getAName(){
    return "alreadyAdvanceAmount";
}
/**
 * 删除
 */
// 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();
//     $(el.tb).datagrid('clearSelections');
// }


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

    // 先拿到索引，倒序删，避免多行删除时索引位移
    var indexArr = rows.map(function (r) {
        return $(el.tb).datagrid('getRowIndex', r);
    }).filter(function (i) { return i !== -1; })
        .sort(function (a, b) { return b - a; });

    indexArr.forEach(function (idx) {
        $(el.tb).datagrid('deleteRow', idx);
    });
// 关键：刷新附件列表 & 附件校验，使 tbAttachmentCheck 与 tb 明细一致
    refreshAttachmentRelatedGrids();
    summaryItemAmount();
    $(el.tb).datagrid('clearSelections');


}

/**
 * 数据导出
 */
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 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: '20%'
                },
                {
                    field: 'prepaid',
                    title: '已申请预付金额',
                    width: '20%'
                },
                {
                    field: 'actualPrepaid',
                    title: '实际预付金额',
                    width: '20%',
                    formatter:function (value) {
                        return formatterPrice(value);
                    }
                },
                // {
                //     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: '20%',
                    formatter:function (value) {
                        return formatterPrice(value);
                    }
                    // formatter:function (value) {
                    //     if (!value) {
                    //         return 0;
                    //     }
                    //     return  formatNumber(value, 4, 1);
                    // }
                },
                {
                    field: 'remaining',
                    title: '剩余付款金额',
                    width: '19%',
                    formatter:function (value) {
                        return formatterPrice(value);
                    }
                },
                // {
                //     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);
        },
    });
}
function loadReceiptGrid(){
    $(el.tb3).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/finance/payment/receipt/rest/list?mainId=' + $(el.id).val()+'&businessType=202',
        height: '460px',
        width: '98%',
        pagination: true,
        autoRowHeight: false,
        remoteSort:false,
        fitColumns: true,
        checkbox: true,
        rownumbers: false,
        queryParams: {},
        columns: [[
            {
                field: 'receiptCode',
                title: '回执单编号',
                width: 310
            },
            {
                field: 'fileIds',
                title: '文件',
                width: 310,
                formatter: function (value, row, index) {
                    return '<div class="supplier-file-form custom-file-form-style" data-options=\'{"deleteEnable":false, "previewEnable":true, "uploadEnable": false, "moreFileUploadEnable": true, "fileSize": 50, "fileTypes": ".xls,.doc,.txt,.pdf"}\' data-fileIds = "'+value+'"></div>';
                }
            },
            {
                field: 'createTime',
                title: '创建时间',
                width: 200,
                align: 'center',
                formatter: function (value) {
                    if (value) {
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                    return '';
                }
            },
            {
                field: 'updateTime',
                title: '更新时间',
                width: 200,
                align: 'center',
                formatter: function (value) {
                    if (value) {
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                    return '';
                }
            },
            {
                field: 'deleteFlag',
                title: '删除标记',
                width: 200,
                sortable: true,
                exportEnum:[
                    {code:0,codeWithDesc:'未删除'},
                    {code:1,codeWithDesc:'已删除'}
                ],
                formatter:function (value) {
                    if(value === 0){
                        return "未删除"
                    }else{
                        return "<span style='color: red;'>已删除</span>"
                    }
                }
            },

        ]],
        // toolbar:[{
        //     text: "一键下载",
        //     iconCls: 'icon-remove',
        //     handler: function () {
        //         let rows = $(el.supplierFileTb).datagrid("getRows");
        //         var fileIdsArr = [];
        //         $.each(rows, function (idx, itm) {
        //             var files = itm.supplierFormFiles;
        //             fileIdsArr.push(files)
        //         });
        //         batchDownload(fileIdsArr.join(','))
        //     }
        // }],
        onLoadSuccess: function (data) {
            initFileForm('supplier-file-form');
        },
    });
}

/**
 * 删除/新增订单后，刷新附件列表(tbAttachment) + 附件校验(tbAttachmentCheck)
 * 原理：更新 businessCodes → 重新 load tbAttachment → 其 onLoadSuccess 会重建 tbAttachmentCheck
 */
function refreshAttachmentRelatedGrids() {
    // 从 tb 明细重新计算 businessCodes / purchaseCodeAndDeliveryCode
    var detail = $(el.tb).datagrid('getRows') || [];
    if (detail.length === 0) {
        // tb 没有任何订单：清空附件列表和校验表
        el.businessCodes = [];
        if ($(el.tbAttachment).length > 0) {
            $(el.tbAttachment).datagrid('loadData', { total: 0, rows: [] });
        }
        if ($(el.tbAttachmentCheck).length > 0) {
            // currencyCode 不存在时 initTbAttachmentCheck 会 return，这里直接清空即可
            try { $(el.tbAttachmentCheck).datagrid('loadData', { total: 0, rows: [] }); } catch (e) {}
        }
        return;
    }

    var businessCodes = [];
    var purchaseCodeAndDeliveryCode = [];

    for (var i = 0; i < detail.length; i++) {
        if (detail[i].poCode) {
            businessCodes.push(detail[i].poCode);
        }
        if (detail[i].deliveryOrderCode) {
            purchaseCodeAndDeliveryCode.push(detail[i].poCode + '_' + detail[i].deliveryOrderCode.split(','));
        }
    }

    // 去重
    businessCodes = businessCodes.filter(function (item, idx, self) { return self.indexOf(item) === idx; });
    purchaseCodeAndDeliveryCode = purchaseCodeAndDeliveryCode.filter(function (item, idx, self) { return self.indexOf(item) === idx; });

    el.businessCodes = businessCodes;

    // 触发附件列表重新加载（tbAttachment 的 onLoadSuccess 会重建 tbAttachmentCheck）
    if ($(el.tbAttachment).length > 0) {
        $(el.tbAttachment).datagrid('options').loadFilter = pagerSignFilter;

        var attachmentTypeCreateConfigList =
            ($(el.currencyCode).combobox('getValue') === "CNY" && $(el.advanceType).combobox('getValue') === "0") ? eval(attachmentTypeCreateConfigs) :
                ($(el.currencyCode).combobox('getValue') === "CNY" && $(el.advanceType).combobox('getValue') === "1") ? eval(deliveryAttachmentTypeCreateConfigs) :
                    eval(overseasAttachmentTypeCreateConfigs);

        var attachmentTypeCreateConfigCodes = attachmentTypeCreateConfigList.map(function (item) { return item.code; });

        // 默认 url
        let url =
            g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes?businessIds=' + $(el.id).val()
            + '&businessTypeCodes=payment_advance_apply';

        // 新增/编辑状态：按订单维度加载附件
        if (optType === 0 || optType === 1) {
            url =
                g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes?businessCodes=' + businessCodes.join(',')
                + '&businessTypeCodes=purchase_order,purchase_order_sign,delivery_order,purchase_to_delivery_order'
                + '&types=' + attachmentTypeCreateConfigCodes.join(',')
                + '&purchaseCodeAndDeliveryCodes=' + purchaseCodeAndDeliveryCode.join('*');
        }
        $(el.tbAttachment).datagrid('options').url = url;
        $(el.tbAttachment).datagrid('load');
    }
}


/**
 * 查看每个订单下的付款详细数据
 * @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: 150,
                formatter: function (value, row, index) {
                    switch (value){
                        case 3:
                            return '审批中';
                        case 5:
                            return '付款完成';
                    }
                }
            },
            {
                field: 'amountType',
                title: '付款类型',
                width: 150,
                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: 150,
                formatter:function (value) {
                    return formatterPrice(value);
                }
            },
            {
                field: 'actualPrepaid',
                title: '实际付款金额',
                width: 150,
                formatter:function (value) {
                    return formatterPrice(value);
                }
            },
            {
                field: 'reversalMoney',
                title: '已冲账金额',
                width: 150,
                formatter:function (value) {
                    return formatterPrice(value);
                }
            },
            // {
            //     field: 'buyer',
            //     title: '采购员',
            //     width: 100
            // }
        ]],
        onLoadSuccess: function (data) {
            $(el.tb2).datagrid('fixDetailRowHeight', index);
            var buyer = row.buyer;
            var rows = data.rows;
            for (let i = 0; i < rows.length; i++) {
                $('#ddv-' + index).datagrid('updateRow',{
                    index: i,
                    row: {
                        buyer: buyer,
                    }
                });
            }
            //$('#supplierTb').datagrid('fixDetailRowHeight', index);
        },
        // onClickRow: function (detailIndex, rowData) {
        //     if (supplierEditIndex === undefined) {
        //         el.tableDom = '#ddv-' + index;
        //         $(el.tableDom).datagrid('beginEdit', detailIndex);
        //         supplierEditIndex = detailIndex;
        //     } else {
        //         supplierEndEditor();
        //         el.tableDom = '#ddv-' + index;
        //         $(el.tableDom).datagrid('beginEdit', detailIndex);
        //         supplierEditIndex = detailIndex;
        //     }
        // },
        onResize: function () {
            $(el.tb2).datagrid('fixDetailRowHeight', index);
        }
        // onCheck: function (rowIndex, rowData) {
        //     $(el.tb).datagrid('unselectAll');
        // },
        // onCheckAll: function (rows) {
        //     $(el.tb).datagrid('unselectAll');
        // }
    });
}

/**
 * 初始化页面下拉框
 */
function 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: []})
            }

            if (optType === 0) {
                getReturnVoucherRefundAmount(data.companyCode,$(el.supplierCode).val());
                findSupplierPaymentPlanSummary($(el.supplierCode).val(), data.companyCode);
                payablePayment(data.companyCode,$(el.currencyCode).combobox('getValue'),$(el.supplierCode).val());

            }
        }
    });
    $(el.paymentCompanyCode).combobox({
        url: g.ctx + 'pc/sys/company/rest/listAll',
        required: true,
        editable: false,
        valueField: 'companyCode',
        textField: 'codeWithDesc',
        panelHeight: 'auto',
        prompt: '--- 请选择 ---'
    });
    // 初始化付款方式下拉框
    // $(el.paymentWayCode).combobox({
    //     required: true,
    //     editable: false,
    //     valueField: 'dicId',
    //     textField: 'dicTxt',
    //     panelHeight: 'auto',
    //     data: [
    //         {dicTxt: '转账', dicId: "0"},
    //         {dicTxt: '承兑汇票', dicId: "1"},
    //         {dicTxt: '承兑汇票加转账', dicId: "2"}
    //     ],
    //     prompt: '--- 请选择 ---',
    //     onSelect: function (data) {
    //         $(el.paymentWayDesc).val(data.dicTxt);
    //     }
    // });

    // $(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);
            if ($(el.currencyCode).combobox('getValue')!=="CNY"&&data.code!=="10810"){
                $(el.paymentCompanyCode).combobox('setValue', "1300");
            }else {
                $(el.paymentCompanyCode).combobox('setValue', $(el.companyCode).combobox('getValue'));
            }
        }
    });
    $(el.businessType).combobox({
        required: true,
        url: g.ctx + 'pc/sys/dict/getDicByType?type=business_type',
        method: 'GET',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        editable: false,
    });
    $(el.feePayer).combobox({
        required: true,
        url: g.ctx + 'pc/sys/dict/getDicByType?type=fee_payer',
        method: 'GET',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        editable: false,
    });
    $(el.advanceType).combobox({
        required: true,
        editable: false,
        valueField: 'dicId',
        textField: 'dicTxt',
        panelHeight: 'auto',
        data: [
            {dicTxt: '预付款', dicId: "0"},
            {dicTxt: '货到付款', dicId: "1"}
        ],
        onSelect: function (data) {
            if(optType===0||optType===1){
                setTbAttachment();
            }
        }
    });
    $(el.urgentFlag).combobox({
        required: true,
        editable: false,
        valueField: 'dicId',
        textField: 'dicTxt',
        panelHeight: 'auto',
        data: [
            {dicTxt: '一般', dicId: "0"},
            {dicTxt: '紧急', dicId: "1"}
        ]
    });
    // //季度
    // $('#oaQuarter').combobox({
    //     required: true,
    //     valueField: 'label',
    //     textField: 'label',
    //     data: [
    //         {label: '一季度', value: 0},
    //         {label: '二季度', value: 1},
    //         {label: '三季度', value: 2},
    //         {label: '四季度', value: 3},
    //         {label: '一月', value: 4},
    //         {label: '二月', value: 5},
    //         {label: '三月', value: 6},
    //         {label: '四月', value: 7},
    //         {label: '五月', value: 8},
    //         {label: '六月', value: 9},
    //         {label: '七月', value: 10},
    //         {label: '八月', value: 11},
    //         {label: '九月', value: 12},
    //         {label: '十月', value: 13},
    //         {label: '十一月', value: 14},
    //         {label: '十二月', value: 15}
    //     ],
    //     editable: false,
    //     prompt: '--- 请选择 ---',
    //     panelHeight: 'auto',
    //     panelWidth: 300,
    // });

    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 (optType === 0) {
                    payablePayment($(el.companyCode).combobox('getValue'),data.code,$(el.supplierCode).val());
                    if (data.code!=="CNY"&&$(el.faSupplier).combobox('getValue')!=="10810"){
                        $(el.paymentCompanyCode).combobox('setValue', "1300");
                    }else {
                        $(el.paymentCompanyCode).combobox('setValue', $(el.companyCode).combobox('getValue'));
                    }
                }
            }
            if (data.code==='CNY'){
                $(el.bankCode).combobox({ required: true });
                $(el.bankInterCode).combobox({ required: false });
            }else {
                $(el.bankCode).combobox({ required: false });
                $(el.bankInterCode).combobox({ required: true });
            }
        },
        onChange: function (value) {
            if (value==='CNY') {
                $(el.paymentPurpose).combobox('setValue', 1);
            } else if (value==='USD') {
                $(el.paymentPurpose).combobox('setValue', 2);
            }
        }
    });

    //经办人  -- 采购组
    $(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.paymentPurpose).combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_purpose',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '--- 请选择 ---',
        editable: false,
        onSelect: function (data) {
            $(el.paymentPurposeDesc).val(data.name);
        }
    });

    $(el.supBankName).textbox({
        prompt: '请选择供应商开户行',
        required: true,
        icons: [
            {
                iconCls: 'icon-search',
                handler: function () {
                    if (optType!==2){
                        choseBank();
                    }
                }
            }
        ]
    });

    if (optType === 1 || optType === 2) {
        initBankSelector($('#supplierId').val());
    } else {
        // 初始化供应商开户行账号下拉框
        $(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
        });
        $(el.paymentCompanyName).combobox({
            panelHeight: 'auto',
            prompt: '--- 请先选择供应商开户行 ---',
            disabled: true,
            //readonly: true,
            required: true
        });
        $(el.bankAddress).combobox({
            panelHeight: 'auto',
            prompt: '--- 请先选择供应商开户行 ---',
            disabled: true,
            //readonly: true,
            required: true
        });
    }

    // 初始化状态下拉框
    $(el.paymentWayCode).combobox({
        required: true,
        url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_way',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '--- 请选择 ---',
        editable: false,
        onSelect: function (data) {
            // $(el.paymentWayDesc).val(data.name);
            if (data.code !== 'C') {
                $(el.paymentWayDesc).val('');
                $(el.acceptanceMethod).combobox('setValue','');
            } else {
                $(el.paymentWayDesc).val(data.name);
            }
        }
    });
    $(el.collectionFlag).combobox({
        required: false,
        editable: false,
        valueField: 'dicId',
        textField: 'dicTxt',
        panelHeight: 'auto',
        data: [
            {dicTxt: '是', dicId: "1"},
            {dicTxt: '否', dicId: "0"}
        ],
    });
    /**
     * 初始化供应商选择
     */
    if (Number(isSupplier) === 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();
            }
        });

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

        });
    }

    var supplierName = $(el.supplierName).textbox('getValue');
    var paymentSupplierName = $(el.paymentSupplierName).textbox('getValue');
    if (!isBlank(supplierName)&&!isBlank(paymentSupplierName)){
        if (supplierName!==paymentSupplierName){
            $(el.collectionFlag).combobox('setValue',"1");
            $(el.paymentFilesTr).show();
        }else {
            $(el.collectionFlag).combobox('setValue',"0");
            $(el.paymentFilesTr).hide();
        }
    }else {
        $(el.collectionFlag).combobox('setValue',"0");
        $(el.paymentFilesTr).hide();
    }

    $(el.imgCode).textbox('textbox').css('cursor', 'pointer').css('color', '#0b94ea');
    $(el.poImgCode).textbox('textbox').css('cursor', 'pointer').css('color', '#0b94ea');
    $(el.advanceType).textbox('textbox').css('color', '#ee4d12').css('font-weight', '600');
    $(el.imgCode).textbox('textbox').bind('click', function () {
        if(!$(el.imgCode).textbox('getValue')) return false;
        showImage($(el.imgCode).textbox('getValue'));
    });
    $(el.poImgCode).textbox('textbox').bind('click', function () {
        if(!$(el.poImgCode).textbox('getValue')) return false;
        showImage($(el.poImgCode).textbox('getValue'));
    });
}
function showImage(imageCode){
    $.ajax({
        type: 'get',
        url: g.ctx + 'pc/sys/kingdeeImage/rest/getImageViewPath',
        data: {
            imageCode: imageCode
        },
        success: function (data) {
            if (data) {
                window.open(data, "_blank");
            }
        },
        error: function (error) {
            topWin.layer.alert(error.responseJSON.message, {
                icon: 2,
                content: error.responseJSON.message
            });
        }
    });
}
/**
 * 选择供应商
 */
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) {
                        $(el.supplierName).textbox('setValue', cbox[0].supplierName);
                        $(el.supplierCode).val(cbox[0].supplierCode);
                        // if (!$(el.paymentSupplierName).textbox('getValue')){
                            $(el.paymentSupplierName).textbox('setValue', cbox[0].supplierName);
                            $(el.paymentSupplierCode).val(cbox[0].supplierCode);
                            supplierSelectSetBankInfo(cbox);
                            $(el.collectionFlag).combobox('setValue',"0");
                            $(el.paymentFilesTr).hide();
                        // }
                        if ($(el.paymentSupplierName).textbox('getValue')){
                            if ($(el.paymentSupplierName).textbox('getValue')!==cbox[0].supplierName){
                                $(el.collectionFlag).combobox('setValue',"1");
                                $(el.paymentFilesTr).show();
                            }else {
                                $(el.collectionFlag).combobox('setValue',"0");
                                $(el.paymentFilesTr).hide();
                            }
                        }
                        //如果供应商代码是9999 业务003 物料商的话 业务类型002
                        if (cbox[0].supplierCode === '9999') {
                            $(el.businessType).combobox('setValue','003');
                        } else if (cbox[0].supplierGenre === '4') {
                            $(el.businessType).combobox('setValue','002');
                        } else {
                            $(el.businessType).combobox('setValue','001');
                        }
                        $(el.companyCode).combobox('setValue',cbox[0].companyCode);
                        $(el.paymentCompanyCode).combobox('setValue',cbox[0].companyCode);
                        $(el.currencyCode).combobox('setValue',cbox[0].currencyCode);
                        $(el.paymentWayCode).combobox('setValue',cbox[0].paymentMethod);
                        $(el.acceptanceMethod).combobox('setValue',cbox[0].acceptanceMethod);
                        // findFaSupplierBySupplierCode(cbox[0].supplierCode);
                        $('#supplierId').val(cbox[0].supplierId);
                        // clearBankInfo();
                        // initBankSelector(cbox[0].supplierId, function (bankList) {
                        //     if (bankList.length > 0) {
                        //         const companyBankList = bankList.filter(item => item.companyCode === cbox[0].companyCode);
                        //         if (companyBankList.length > 0) {
                        //             setBankInfo(companyBankList[0]);
                        //         } else {
                        //             setBankInfo(bankList[0]);
                        //         }
                        //     }
                        // });
                        //选择供应商后，需要根据供应商和公司查询付款计划汇总中的付款汇总金额 邓京术 2025-08-01
                        if (optType === 0) {
                            getReturnVoucherRefundAmount(cbox[0].companyCode,cbox[0].supplierCode);
                            findSupplierPaymentPlanSummary(cbox[0].supplierCode, cbox[0].companyCode);
                            payablePayment(cbox[0].companyCode,cbox[0].currencyCode,cbox[0].supplierCode);

                        }
                        //清空表格数据
                        $('#tb').datagrid('loadData', {total: 0, rows: []})
                        userOrgyDialog.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                handler: function () {
                    userOrgyDialog.dialog('close');
                }
            }
        ]
    });
}

function choseSupplierPayment() {
    var url = g.ctx + "pc/supplier/purchaseCategory/page/selector?single=1";
    var choseSupplierDialog = openDialog('choseSupplier', url, {
        title: '供应商选择',
        width: '80%',
        height: '70%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            choseSupplierDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseSupplier'].chooseRow(function (cbox) {
                        $(el.paymentSupplierName).textbox('setValue', cbox[0].supplierName);
                        $(el.paymentSupplierCode).val(cbox[0].supplierCode);
                        if ($(el.supplierName).textbox('getValue')){
                            if ($(el.supplierName).textbox('getValue')!==cbox[0].supplierName){
                                $(el.collectionFlag).combobox('setValue',"1");
                                $(el.paymentFilesTr).show();
                            }else {
                                $(el.collectionFlag).combobox('setValue',"0");
                                $(el.paymentFilesTr).hide();
                            }
                        }
                        supplierSelectSetBankInfo(cbox);
                        //清空表格数据
                        // $('#tb').datagrid('loadData', {total: 0, rows: []})
                        choseSupplierDialog.dialog('close');
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    choseSupplierDialog.dialog('close');
                }
            }
        ]
    });
}

function supplierSelectSetBankInfo(cbox) {
    clearBankInfo();
    initBankSelector(cbox[0].supplierId, function (bankList) {
        if (bankList.length > 0) {
            const companyBankList = bankList.filter(item => item.companyCode === cbox[0].companyCode);
            if (companyBankList.length > 0) {
                setBankInfo(companyBankList[0]);
            } else {
                setBankInfo(bankList[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) {
            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
 * @param currencyCode 币种
 * @param companyCode 公司代码
 */
function findSupBankDataBySupplierCode(supplierId, currencyCode, companyCode) {
    $.ajax({
        url: g.ctx + 'pc/supplier/rest/find/bank?supplierId=' + supplierId,
        type: 'POST',
        success: function (res) {
            initBankInfoSelectors(res);
        }
    });
}

function initBankSelector(supplierId, callback) {
    $.ajax({
        url: g.ctx + 'pc/supplier/rest/find/bank?supplierId=' + supplierId,
        type: 'POST',
        success: function (res) {
            const currencyCode = $(el.currencyCode).combobox('getValue');
            let bankDataList = [];
            res.forEach(item => {
                if (currencyCode === 'CNY') {
                    item.supBankCode = item.bankCode;
                } else {
                    if (item.bankCode === "" || item.bankCode == null || typeof (item.bankCode) == "undefined") {
                        item.supBankCode = item.bankInterCode;
                    } else {
                        item.supBankCode = item.bankCode;
                    }
                }
                bankDataList.push(item);
            });
            $(el.supBankAccount).combobox({
                data: bankDataList,
                valueField: 'bankAccount',
                textField: 'bankAccount',
                prompt: '--- 请选择 ---',
                panelHeight: 'auto',
                editable: false,
                disabled: true,
                required: currencyCode==='CNY'
            });

            $(el.bankCode).combobox({
                data: bankDataList,
                valueField: 'bankCode',
                textField: 'bankCode',
                prompt: '--- 请选择 ---',
                panelHeight: 'auto',
                editable: false,
                disabled: true,
                required: currencyCode==='CNY'
            });

            $(el.bankInterCode).combobox({
                data: bankDataList,
                valueField: 'bankInterCode',
                textField: 'bankInterCode',
                prompt: '--- 请选择 ---',
                panelHeight: 'auto',
                editable: false,
                disabled: true,
                required: currencyCode!=='CNY'
            });

            $(el.paymentCompanyName).combobox({
                data: bankDataList,
                valueField: 'companyName',
                textField: 'companyName',
                prompt: '--- 请选择 ---',
                panelHeight: 'auto',
                editable: false,
                disabled: true
            });

            $(el.bankAddress).combobox({
                data: bankDataList,
                valueField: 'bankAddress',
                textField: 'bankAddress',
                prompt: '--- 请选择 ---',
                panelHeight: 'auto',
                editable: false,
                disabled: true
            });
            if (typeof callback === 'function') {
                callback(bankDataList);
            }
        }
    });
}

/**
 * 选择供应商开户行
 */
function choseBank() {
    const supplierId = $('#supplierId').val();
    if (!supplierId || supplierId === '') {
        topWin.layer.alert('请先选择供应商', {icon: 0});
        return false;
    }
    const url = g.ctx + "pc/supplier/bankInfo/page/selectorOfSupplierId?supplierId=" + supplierId;
    let supplierBank = openDialog('supplierBank', url, {
        title: "选择供应商开户行",
        width: '80%',
        height: '70%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            supplierBank.dialog('destroy');
        },
        buttons: [
            {
                text: itablei8n.confirm,
                handler: function () {
                    topWin.frames['supplierBank'].chooseRow(function (cbox) {
                        setBankInfo(cbox);
                        supplierBank.dialog('close');
                    });
                }
            },
            {
                text: itablei8n.close,
                handler: function () {
                    supplierBank.dialog('close');
                }
            }
        ]
    });
}

/**
 * 设置银行信息
 * @param chosenRow 选择的银行信息
 */
function setBankInfo(chosenRow) {
    if (!chosenRow) return;
    const currencyCode = $(el.currencyCode).combobox('getValue');
    let subBankCode;
    if (currencyCode === 'CNY') {
        subBankCode = chosenRow.bankCode;
    } else {
        if (chosenRow.bankCode === "" || chosenRow.bankCode == null || typeof (chosenRow.bankCode) == "undefined") {
            subBankCode = chosenRow.bankInterCode;
        } else {
            subBankCode = chosenRow.bankCode;
        }
    }
    $(el.supBankName).textbox('setValue', chosenRow.openingBankName);
    $(el.supBankCode).val(subBankCode);
    $(el.supBankAccount).combobox('setValue', chosenRow.bankAccount);
    $(el.bankCode).combobox('setValue', chosenRow.bankCode);
    $(el.bankInterCode).combobox('setValue', chosenRow.bankInterCode);
    $(el.paymentCompanyName).combobox('setValue', chosenRow.companyName);
    $(el.bankAddress).combobox('setValue', chosenRow.bankAddress);
}

/**
 * 清空银行信息
 */
function clearBankInfo(){
    $(el.supBankName).textbox('setValue', '');
    $(el.supBankCode).val('');
    $(el.supBankAccount).combobox('setValue', '');
    $(el.bankCode).combobox('setValue', '');
    $(el.bankInterCode).combobox('setValue', '');
    $(el.paymentCompanyName).combobox('setValue', '');
    $(el.bankAddress).combobox('setValue', '');
}

function findSupplierPaymentPlanSummary(supplierCode, companyCode) {
    $.ajax({
        url: g.ctx + 'pc/finance/payment/plan/rest/findSupplierPaymentPlanSummary',
        type: 'POST',
        async: false,
        data: {companyCode: companyCode, supplierCode: supplierCode, paymentType:'S'},
        dataType: 'json',
        success: function (redata) {
            debugger;
            if (redata === 0) {
                $('#payPlanMoney').textbox('setValue', 0.0);
            } else {
                $('#payPlanMoney').textbox('setValue', formatterCustomPrice(redata,2,true,false));
            }
        },
        error: function (redata) {
            topWin.layer.alert(redata.responseJSON.message, {icon: 2});
        }
    });
}

function isDatagridReady(selector) {
    if (!selector) return false;
    var $dg = $(selector);
    if ($dg.length === 0) return false;
    return !!$dg.data('datagrid');
}

/**
 * 数据保存-暂存
 *
 * @param callback 回调函数
 */
async function dataSave(callback) {
    // 结束行编辑
    endEditor();
    summaryItemAmount();
    const currencyCode = $(el.currencyCode).combobox('getValue');
    const bankCode = $(el.bankCode).combobox('getValue');
    const bankInterCode = $(el.bankInterCode).combobox('getValue');

    if (!validateBankInfo(currencyCode, bankCode, bankInterCode)) {
        return; // 校验银行行号信息
    }

    var rows = $(el.tb).datagrid('getRows');
    if (rows.length === 0) {
        topWin.layer.alert('请添加采购订单数据', {icon: 0});
        return false;
    }
    let supplierName22 ="";
    let supplierCode22 ="";
    //2024-08-22 邓京术
    //行应付金额 = 本次申请金额 - 折扣金额
    //行应付总金额 = 各行的应付金额汇总 如果 <= 0 则报错不允许暂存
    let rowTotalActualUnpaidAmount = 0;
    let rowActualityPayMoney = 0;
    let rowTotalApplyAmount = 0;
    var advanceType = $(el.advanceType).combobox('getValue');
    for (var i = 0; i < rows.length; i++) {
        let item = rows[i];
        if (!item.expectationPaymentDate) {
            topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '期望付款日不能为空', {icon: 0});
            return false;
        }
        if (!item.paymentConditionCode) {
            topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '付款条件不能为空', {icon: 0});
            return false;
        }
        //期望付款日不能小于当前日期
        if (item.expectationPaymentDate < new Date().format('yyyy-MM-dd')) {
            topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的期望付款日不能小于当前日期', {icon: 0});
            return false;
        }
        if (Number(advanceType)===1){
            if (isBlank(item.storeAmount)){
                item.storeAmount = 0;
            }
            //如果是货到付款，入库金额不能等于0
            if (Number(item.storeAmount) === 0) {
                topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的入库金额不能等于0', {icon: 0});
                return false;
            }
            //如果是货到付款，请款金额不能超入库金额。
            if (Number(item.budOutMoney) > Number(item.storeAmount)) {
                topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的请款金额不能超入库金额', {icon: 0});
                return false;
            }
        }
        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;
            // }
            //1.行可申请金额小于或等于0，折扣金额不等于0，则报错“折扣金额必须为0”
            if (isBlank(item.discountAmount)){
                item.discountAmount = 0;
            }
            //1.行可申请金额小于或等于0，折扣金额不等于0，则报错“折扣金额必须为0”
            if (Number(item.applyAmount.toFixed(4))<=0&&Number(item.discountAmount.toFixed(4))!==0){
                topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的折扣金额必须为0', {icon: 0});
            }
            //2.行可申请金额大于0，折扣金额不能大于本次可申请金额0，则报错“折扣金额不能大于本次可申请金额”
            if (Number(item.applyAmount.toFixed(4))>0&&Number(item.discountAmount.toFixed(4))>Number(item.applyAmount.toFixed(4))){
                topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的折扣金额不能大于本次可申请金额', {icon: 0});
            }
            // //5.本次申请金额不能大于可申请金额，则报错“本次申请金额不能大于本次可申请金额”
            // if (Number(item.budOutMoney.toFixed(4))>Number(item.applyAmount)){
            //     topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的本次申请金额不能大于本次可申请金额', {icon: 0});
            // }


            //本次可申请金额小于0，判断本次金额不能大于0
            if (Number(item.applyAmount.toFixed(4))<0){
                if (Number(item.budOutMoney) >0){
                    topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的本次申请金额不能大于0', {icon: 0});
                    return false;
                }

                if (Number(item.budOutMoney) < Number(item.applyAmount.toFixed(4))) {
                    topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的本次申请金额不能大于本次可申请金额', {icon: 0});
                    return false;
                }

            }else {
                if (Number(item.budOutMoney) > Number(item.applyAmount.toFixed(4))) {
                    topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的本次申请金额不能大于本次可申请金额', {icon: 0});
                    return false;
                }
            }
            //如果本次可申请金额小于0， 则折扣金额必须为0
            if (Number(item.applyAmount.toFixed(4) <= 0)) {
                if (Number(item.discountMoney) !== 0 ) {
                    topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的折扣金额必须为0', {icon: 0});
                    return false;
                }
            } else {
                if (Number(item.discountMoney) > Number(item.applyAmount.toFixed(4))) {
                    topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的折扣金额不能大于本次可申请金额', {icon: 0});
                    return false;
                }
            }
        }

        rowTotalActualUnpaidAmount = accAdd(rowTotalActualUnpaidAmount, accSub(Number(item.budOutMoney), Number(item.discountMoney)));
        rowActualityPayMoney = accAdd(rowActualityPayMoney, Number(item.actualityPayMoney));
        rowTotalApplyAmount = accAdd(rowTotalApplyAmount, Number(item.applyAmount));


        // 本次申请金额不能小于等于0
        if (Number(item.budInnerMoney).add(Number(item.budOutMoney)) <= 0) {
            //topWin.layer.alert('采购订单号_行号: ' + item.poCode + '_' + item.poItemNo + '的申请金额不能小于等于零', {icon: 0});
            //return false;
        }

        // if (supplierName22&&rows[i].supplierName2){
        //
        //     if(i !== 0 && supplierName22 !== rows[i].supplierName2){
        //         layer.msg("所选报关公司必须一致");
        //         return false;
        //     }
        // }
        //
        if (rows[i].supplierName2){
            supplierName22 = rows[i].supplierName2;
            supplierCode22 = rows[i].supplierCode2;
        }
    }
    // 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;
    }
    //应付总金额（累计 本次请款金额-折扣金额）小于或等于0，则报错“累计应付金额必须大于0”
    if (Number(rowActualityPayMoney.toFixed(4))<=0){
        topWin.layer.alert('应付总金额必须大于0', {icon: 0});
    }
    // mainData.faSupplier = supplierCode22;
    // mainData.faSupplierName = supplierName22;
    // 数据校验

    // if (!mainData.supBankCode) {
    //     topWin.layer.alert('请选择供应商开户行信息', {icon: 0});
    //     return false;
    // }
    if (!mainData.supBankAccount) {
        topWin.layer.alert('请选择开户行账号信息', {icon: 0});
        return false;
    }
    //如果付款方式为承兑汇票， 则承兑期限必须选择 2024-08-22 邓京术 财务新需求
    if (mainData.paymentWayCode && mainData.paymentWayCode === 'C' && !mainData.acceptanceMethod) {
        topWin.layer.alert('请选择承兑期限', {icon: 0});
        return false;
    }
    if (mainData.currencyCode!=='CNY'&&!mainData.faSupplierName) {
        topWin.layer.alert('请选择报关公司', {icon: 0});
        return false;
    }
    if (Number(mainData.collectionFlag)===1&&!$(el.paymentFiles).attr('data-fileIds')) {
        topWin.layer.alert('请上传收款委托书', {icon: 0});
        return false;
    }
    if (Number(rowTotalActualUnpaidAmount) <= 0) {
        topWin.layer.alert('累计应付金额为：' + rowTotalActualUnpaidAmount +',累计应付金额必须大于0', {icon: 0});
        return false;
    }
    if($.isEmptyObject(mainData.overdueAmount)||$.isEmptyObject(mainData.dueAmount)||$.isEmptyObject(mainData.accountsPayableBalance)||$.isEmptyObject(mainData.provisionalBalance)){
        topWin.layer.alert('请获取款项信息', {icon: 0});
        return false;
    }
    if (isBlank(mainData.refundAmount)){
        topWin.layer.alert('请获取在途退款金额', {icon: 0});
        return false;
    }
    mainData.overdueAmount = Number(mainData.overdueAmount.replace(/,/g,''));
    mainData.dueAmount = Number(mainData.dueAmount.replace(/,/g,''));
    mainData.accountsPayableBalance = Number(mainData.accountsPayableBalance.replace(/,/g,''));
    mainData.provisionalBalance = Number(mainData.provisionalBalance.replace(/,/g,''));
    mainData.refundAmount = Number(mainData.refundAmount.replace(/,/g,''));
    if ((provisionalBalance+refundAmount)<rowTotalApplyAmount){
        topWin.layer.alert('此供应商应付账款余额不足以抵减在途退货订单或扣款单，请谨慎审批', {icon: 0});
        return false;
    }
    // if (!mainData.bankCode) {
    //     topWin.layer.alert('请选择银行代码', {icon: 0});
    //     return false;
    // }
    // if (!mainData.bankInterCode) {
    //     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 = optType===0?1:2
    mainData.isPushOa = 0;
    let uploadAttachmentFileDataList = Number(tbAttachmentLookFlag)===1?[]:$(el.tbAttachment).datagrid("getData").rows;
    uploadAttachmentFileDataList = await getAllBusinessData(uploadAttachmentFileDataList);
    const tbAttachmentCheckList = Number(tbAttachmentLookFlag)===1?[]:$(el.tbAttachmentCheck).datagrid("getData").rows;
    mainData.businessAttachmentDTOList = uploadAttachmentFileDataList;

    if (uploadAttachmentFileDataList.length===0){
        topWin.layer.alert('附件检查中缺少附件，无法保存', {icon: 0});
        return false

    }
    var satisfyFlagExist = false;
    tbAttachmentCheckList.forEach(item=>{
        if (item.satisfyFlag===0){
            satisfyFlagExist = true;
        }
    })

    if (satisfyFlagExist){
        topWin.layer.alert('附件检查中存在附件未满足，无法保存', {icon: 0});
        return false
    }


    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'pc/finance/paymentAdvance/apply/rest/dave/saveCheck',
        type: 'POST',
        data: JSON.stringify(mainData),
        contentType: 'application/json',
        success: function (result) {
            topWin.layer.close(loading);
            if (result){
                let currentIndex = 0;
                let logDetailList = [];
                function processValidationMessages(messages) {
                    if (currentIndex >= messages.length) {
                        // 所有校验通过后调用 dataSaveAjax
                        mainData.logDetailList = logDetailList;
                        dataSaveAjax(mainData, callback);
                        return true;
                    }

                    const currentMessage = messages[currentIndex];
                    layer.confirm(currentMessage + ',是否继续？', {
                        btn: ['确定', '取消'] // 按钮
                    }, function () {
                        layer.closeAll();
                        currentIndex++;
                        const logDetail = {
                            confirmAction: "CONFIRM",
                            warnMessage: currentMessage + ',是否继续？'
                        }
                        logDetailList.push(logDetail);
                        processValidationMessages(messages); // 继续处理下一个校验消息
                    }, function () {
                        layer.closeAll();
                        return false; // 用户取消，结束处理
                    });
                }

                // 调用函数开始处理校验消息
                processValidationMessages(result);
            }else {
                dataSaveAjax(mainData,callback);
            }
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}

function dataSaveAjax(mainData, callback) {
    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 validateBankInfo(currencyCode, bankCode, bankInterCode) {
    // CNY货币验证
    if (currencyCode === 'CNY') {
        if (!bankCode || bankCode.trim() === '') {
            topWin.layer.msg('银行信息验证失败：CNY货币必须填写银行代码');
            return false;
        }
        // 可选：如果CNY货币下填写了bankInterCode，可以清空或提示
        if (bankInterCode && bankInterCode.trim() !== '') {
            // 可以在这里清空bankInterCode的值，或者只是提示
            console.log('CNY货币下银行国际代码将被忽略');
        }
    }
    // 非CNY货币验证
    else {
        if (!bankInterCode || bankInterCode.trim() === '') {
            topWin.layer.msg('银行信息验证失败：非CNY货币必须填写银行国际代码');
            return false;
        }
        // 可选：如果非CNY货币下填写了bankCode，可以清空或提示
        if (bankCode && bankCode.trim() !== '') {
            console.log('非CNY货币下银行代码将被忽略');
        }
    }

    return true;
}
/**
 * 处理待保存数据
 *
 * @param rows 明细数据
 * @returns {boolean} 结果
 */
function handleWaitSaveData(rows) {
    var headData = {};
    var  apApplyNo = $(el.apApplyNo).val();
    if ($('#headForm').form('validate') ) {
        headData = $('#headForm').serializeJson();
        headData.supBankAccount = $(el.supBankAccount).combobox('getValue');
        headData.bankCode = $(el.bankCode).combobox('getValue');
        headData.bankInterCode = $(el.bankInterCode).combobox('getValue');
        headData.paymentCompanyName = $(el.paymentCompanyName).combobox('getValue');
        headData.bankAddress = $(el.bankAddress).combobox('getValue');
        headData.files = $(el.files).attr('data-fileIds');
        headData.paymentFiles = $(el.paymentFiles).attr('data-fileIds');
    } else {
        layer.msg("红色框为必输项，请填写！");
        return false;
    }

    var itemList = [];
    for (var i = 0; i < rows.length; i++) {
        var obj = {}, item = rows[i];
        if (optType===0){
            obj.appId = 0;
            obj.appNo = '';
        }else {
            obj.id = item.id;
            obj.appId = $(el.id).val();
            obj.appNo = apApplyNo;
        }
        obj.poCode = item.poCode;
        obj.poItemNo = item.poItemNo;
        obj.poNum = item.poNum;
        obj.materialCode = item.materialCode;
        obj.materialDesc = item.materialDesc;
        obj.materialUnit = item.materialUnit;
        obj.taxCode = item.taxCode;
        obj.taxDesc = item.taxDesc;
        obj.taxValue = item.taxValue;
        // obj.ntPrice = item.ntPrice;
        obj.itPrice = item.itPrice;
        // obj.ntAmount = item.ntAmount;
        obj.itAmount = item.itAmount;
        // obj.dtAmount = item.dtAmount;
        obj.budInnerMoney = item.budInnerMoney;
        obj.budOutMoney = item.budOutMoney;
        obj.itemRemark = item.itemRemark;
        obj.seekPgCode = item.seekPgCode;
        obj.seekPgName = item.seekPgName;
        obj.factoryCode = item.factoryCode;
        obj.paymentWayCode = item.paymentWayCode;
        obj.paymentWayDesc = item.paymentWayDesc;
        obj.paymentConditionCode = item.paymentConditionCode;
        obj.paymentConditionDesc = item.paymentConditionName;
        obj.contractNo = item.contractNo;
        obj.contractName = item.contractName;
        obj.discountMoney = item.discountMoney;
        obj.alreadyAccountAmount = item.alreadyAccountAmount;
        obj.storeAmount = item.storeAmount;
        //2024-11-01增加采购单 预付款到期日
        obj.paymentExpireDate = item.paymentExpireDate;
        obj.expectationPaymentDate = item.expectationPaymentDate;
        itemList.push(obj);
    }
    headData.itemList = itemList;
    headData.delItemIdList = '';

    return headData;
}


function payablePayment(companyCode1, currencyCode1,supplierCode1) {

    var companyCode = isBlank(companyCode1)?$(el.companyCode).combobox('getValue'):companyCode1;
    var currencyCode = isBlank(currencyCode1)?$(el.currencyCode).combobox('getValue'):currencyCode1;
    var  supplierCode = isBlank(supplierCode1)?$(el.supplierCode).val():supplierCode1;
    if(!companyCode){
        topWin.layer.alert('请先选择交易公司', {icon: 0});
        return false;
    }
    if(!supplierCode){
        topWin.layer.alert('请先选择供应商名称', {icon: 0});
        return false;
    }
    if(!currencyCode){
        topWin.layer.alert('请先选择币种', {icon: 0});
        return false;
    }

    var loading = top.layer.msg('获取SAP款项数据中，请耐心等待...', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/finance/account/statement/rest/payablePayment',
        async: true,
        data: {
            companyCode: companyCode,
            currencyCode: currencyCode,
            supplierCode: supplierCode
        },
        success: function (data) {
            $(el.overdueAmount).textbox('setValue',formatterPrice(new BigNumber(data.ZOVBTR)));
            $(el.dueAmount).textbox('setValue',formatterPrice(new BigNumber(data.ZNOBTR0)));
            $(el.accountsPayableBalance).textbox('setValue',formatterPrice(new BigNumber(data.DMBTR02)));
            $(el.provisionalBalance).textbox('setValue',formatterPrice(new BigNumber(data.DMBTR01)));
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            $(el.overdueAmount).textbox('setValue',0);
            $(el.dueAmount).textbox('setValue',0);
            $(el.accountsPayableBalance).textbox('setValue',0);
            $(el.provisionalBalance).textbox('setValue',0);
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 0, shadeClose: true, title: '温馨提示'});
        }
    });


}
function getReturnVoucherRefundAmount(companyCode1,supplierCode1) {

    var companyCode = isBlank(companyCode1)?$(el.companyCode).combobox('getValue'):companyCode1;
    var  supplierCode = isBlank(supplierCode1)?$(el.supplierCode).val():supplierCode1;
    if(!companyCode){
        topWin.layer.alert('请先选择交易公司', {icon: 0});
        return false;
    }
    if(!supplierCode){
        topWin.layer.alert('请先选择供应商名称', {icon: 0});
        return false;
    }

    var loading = top.layer.msg('获取在途退款金额数据中，请耐心等待...', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/finance/receipt/voucher/rest/getReturnVoucherRefundAmount',
        async: true,
        data: {
            factoryCode: companyCode,
            supplierCode: supplierCode
        },
        success: function (data) {
            $(el.refundAmount).textbox('setValue',formatterPrice(new BigNumber(data)));
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            $(el.refundAmount).textbox('setValue',0);
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 0, shadeClose: true, title: '温馨提示'});
        }
    });


}
function createByPercent() {
    endEditor();
    var rows = $(el.tb).datagrid('getRows');
    topWin.layer.prompt({title: "请填写百分比%", formType: 3, value: '', maxlength: 500}, function(text, index){
        if(text ===''){
            topWin.layer.msg('请填写百分比%', {icon: 2});
            return false;
        }
        //如果text不是0到100，且不为整数，则报错
        if (!/^(0|[1-9]\d?|100)$/.test(text)) {
            topWin.layer.msg('百分比%填写错误，请填写0到100的整数', {icon: 2});
            return false;
        }
        if (rows.length>0){
            // var totalBudOutMoney =  new BigNumber(0);
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                //计算row.applyAmount百分比后的值，用BigNumber.js中的方法
                var budOutMoney = new BigNumber(row.applyAmount).multipliedBy(new BigNumber(text/100)).decimalPlaces(2, BigNumber.ROUND_HALF_UP).toNumber()

                // totalBudOutMoney = budOutMoney.plus(totalBudOutMoney);
                $(el.tb).datagrid('updateRow', {index: i, row: {budOutMoney: budOutMoney}})
                updateRowData(budOutMoney, 'budOutMoney');

            }
        }
        topWin.layer.close(index);
    });
}

function iniTtbLog() {
    const dataDivHeight = $(el.dataDiv).outerHeight();
    $(el.tbLog).datagrid({
        loadMsg: '数据加载中......',
        url: optType === 0? null : g.ctx + 'pc/finance/finPaymentConfirmLog/rest/list',
        height: el.bodyHeight - dataDivHeight,
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        pagination: true,
        showFooter: true,
        queryParams: {
            paymentId: $(el.id).val()
        },
        columns: [
            [
                {
                    field: 'warnMessage',
                    title: '警告消息',
                    width: 1000
                },
                {
                    field: 'userName',
                    title: '操作人',
                    width: 80
                },
                {
                    field: 'confirmAction',
                    title: '操作动作',
                    width: 80,
                    formatter: function (value) {
                        if (value === "CONFIRM") {
                            return "确认";
                        } else if (value === "CANCEL") {
                            return "取消";
                        } else {
                            return "";
                        }
                    }
                },
                {
                    field: 'createdTime',
                    title: '操作时间',
                    width: 150
                }
            ]
        ]
    });
}
/**
 * 获取所有业务附件
 */
async function getAllBusinessData(rows) {
    if (rows.length === 0) return [];
    const url = $(el.tbAttachment).datagrid('options').url;
    if (isBlank(url)) return [];
    const detailRows = await new Promise((resolve, reject) => {
        $.ajax({
            url: url,
            type: "GET",
            success: resolve,
            error: reject
        });
    });
    return detailRows.rows;
}