/**
 * 对账模块-新增付款申请页面JS
 *
 * Created by li.kui on 2020/9/15.
 */
'use strict';
var el = {
    dataPanel: '#dataPanel',
    isSupplier: '#isSupplier',
    refundAmount: '#refundAmount',
    files: '#files',
    userAccount: '#userAccount',
    tbAttachmentManualCheck: '#tbAttachmentManualCheck',
    id: '#id',
    dataDiv: '#dataDiv',
    businessCodes: [],
    companyCode: '#companyCode',
    paymentCompanyCode: '#paymentCompanyCode',
    overdueAmount: '#overdueAmount',
    dueAmount: '#dueAmount',
    accountsPayableBalance: '#accountsPayableBalance',
    provisionalBalance: '#provisionalBalance',
    companyName: '#companyName',
    factoryCode: '#factoryCode',
    factoryName: '#factoryName',
    supplierCode: '#supplierCode',
    paymentSupplierCode: '#paymentSupplierCode',
    supplierName: '#supplierName',
    paymentSupplierName: '#paymentSupplierName',
    bankInterCode: '#bankInterCode',
    paymentCompanyName: '#paymentCompanyName',
    bankAddress: '#bankAddress',
    bankCode: '#bankCode',
    currencyCode: '#currencyCode',
    supBankCode: '#supBankCode',
    advancePaymentFlag: '#advancePaymentFlag',
    collectionFlag: '#collectionFlag',
    paymentFilesTr: '#paymentFilesTr',
    imgCode: '#imgCode',
    paymentFiles: '#paymentFiles',
    acceptanceMethod: '#acceptanceMethod',
    faSupplier: '#faSupplier',
    businessType: '#businessType',
    feePayer: '#feePayer',
    urgentFlag: '#urgentFlag',
    faSupplierName: '#faSupplierName',
    supBankName: '#supBankName',
    supBankAccount: '#supBankAccount',
    paymentWayCode: '#paymentWayCode',
    paymentWayDesc: '#paymentWayDesc',
    paymentTermCode: '#paymentTermCode',
    paymentTermDesc: '#paymentTermDesc',
    applyPaymentAmount: '#applyPaymentAmount',
    planAmount: '#planAmount',
    oaHandler: '#oaHandler',
    oaHandlerCode: '#oaHandlerCode',
    payPlanMoney: '#payPlanMoney',
    paymentPurpose: '#paymentPurpose',
    paymentPurposeDesc: '#paymentPurposeDesc',
    applyRemark: '#applyRemark',
    tb: '#tb',
    tb2: '#tb2',
    tb3: '#tb3',
    tbToolbar: '#tbToolbar',
    tbLog: '#tbLog',
    mvPostDateStart: '#mvPostDateStart',
    mvPostDateEnd: '#mvPostDateEnd',
    supplierReturn: '#supplierReturn',
    existedData: [],
    tempDelTbData: [],
    editIndex: undefined,
    choseSupplierDialog: undefined,
    bodyHeight: document.documentElement.clientHeight
};
/**
 * 文档就绪
 */
$(function () {
    initDictName('businessFileType')
    $(el.dataPanel).panel({
        collapsible: true,
        onCollapse: function () {
            $(el.tb).datagrid('resize', {height: el.bodyHeight - 45});
        },
        onExpand: function () {
            var dataDivHeight = $(el.dataDiv).outerHeight();
            $(el.tb).datagrid('resize', {height: el.bodyHeight - dataDivHeight});
        }
    });
    initNecessaryDatas('pc/sys/purchaseGroup/rest/listAll,pc/sys/tax/rest/listAll')
    initDict('payment_method')
    initPageComBoBox();

    initPageDataGrid();
    initPageDataGrid2();
    loadReceiptGrid();
    initTbAttachmentManualCheck();
    iniTtbLog();
    // $('#tt').tabs({
    //     onSelect:function(title){
    //         if('已申请付款信息' === title){
    //             var rows = $(el.tb).datagrid('getRows');
    //             let accountStatementNos = [];
    //             for (let i = 0; i < rows.length; i++) {
    //                 var item = rows[i];
    //                 accountStatementNos.push(item.accountStatementNo);
    //             }
    //             findPaymentDetailByPoCode(accountStatementNos)
    //         }
    //     }
    // });
});
let processName = "";

/**
 * 初始化页面下拉框
 */
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: []})
            }
            //重新查询付款计划汇总中的，应付金额 邓京术 2025-08-01
            //选择供应商后，需要根据供应商和公司查询付款计划汇总中的付款汇总金额 邓京术 2025-08-01
            //新增的时候才需要去查询付款计划金额，其他查看和编辑不需要查询
            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.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.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.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.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: false
        });
        $(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) {
            if (data.code !== 'C') {
                $(el.paymentWayDesc).val('');
                $(el.acceptanceMethod).combobox('setValue','');
            } else {
                $(el.paymentWayDesc).val(data.name);
            }
        }
    });

    // 初始化供应商退款下拉框
    $(el.supplierReturn).combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=supplier_return',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        editable: false,
        onLoadSuccess: function(data){
            if(optType===0){
                $(this).combobox('setValue', "0");
            }
        }
    });

    $(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 (supplierName&&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.imgCode).textbox('textbox').bind('click', function () {
        if(!$(el.imgCode).textbox('getValue')) return false;
        showImage($(el.imgCode).textbox('getValue'));
    });
}

/**
 * 初始化页面表格数据
 */
function initPageDataGrid() {
    var dataDivHeight = $(el.dataDiv).outerHeight();
    $(el.tb).datagrid({
        loadMsg: '数据加载中......',
        height: el.bodyHeight - dataDivHeight,
        singleSelect: false,
        showFooter: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        url: g.ctx + 'pc/finance/payment/cod/apply/rest/query/cod/apply/invoice/id',
        queryParams: {
            id: $(el.id).val(),
            businessType: $(el.businessType).combobox('getValue'),
            dataShowType: 1
        },
        frozenColumns:[[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'accountStatementNo',
                title: '对账单号号',
                width: 100,
                sortable: true
            },
            {
                field: 'invoiceNo',
                title: '开票申请号',
                width: 100,
                sortable: true
            },
            {
                field: 'taxCode',
                title: '税率',
                width: 100,
                formatter: function (value) {
                    return getNecessaryDataName('pc/sys/tax/rest/listAll',value);
                }
            },
            {
                field: 'purchaseGroup',
                title: '采购组',
                width: 100,
                formatter: function (value) {
                    return getNecessaryDataName('pc/sys/purchaseGroup/rest/listAll',value);
                }
            }
        ]],
        columns: [
            [
                {
                    field: 'paymentExpireDate',
                    title: '付款到期日',
                    width: 120,
                    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: 'itAmount',
                    title: '含税金额',
                    width: 100,
                    sortable: true,
                    formatter:function (value) {
                        if (!value){
                            return  0;
                        }
                        return  formatterPrice(value);
                    }
                },
                {
                    field: 'strikePriceAmount',
                    title: '冲账金额',
                    width: 110,
                    sortable: true,
                    formatter:function (value) {
                        if (!value){
                            return  0;
                        }
                        return  formatterPrice(value);
                    }
                },
                {
                    field: 'actualUnpaidAmount',
                    title: '开票实际未付金额',
                    width: 110,
                    sortable: true,
                    formatter:function (value) {
                        if (!value){
                            return  0;
                        }
                        return  formatterPrice(value);
                    }
                },
                {
                    field: 'applyAmount',
                    title: '可申请金额',
                    width: 110,
                    sortable: true,
                    formatter:function (value) {
                        if (!value){
                            return  0;
                        }
                        return  formatterPrice(value);
                    }
                },
                {
                    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: 'discountMoney',
                    title: '折扣金额',
                    width: 100,
                    sortable: true,
                    formatter:function (value) {
                        if (value === null || value === undefined || value === '') {
                            return 0.00;
                        }
                        return  formatterPrice(value);
                    },
                    editor: {
                        type: 'numberbox',
                        options: {
                            precision: priceHandle.precision,
                            value: 0.00,
                            onChange: function (nv) {
                                updateRowData(nv, 'discountMoney');
                            }
                        }
                    }
                },
                {
                    field: 'actualUnpaidAmount1',
                    title: '实际应付金额',
                    width: 110,
                    sortable: true,
                    formatter:function (value,row) {
                        var discountMoney = row.discountMoney?row.discountMoney:0;
                        return formatterPrice(row.budOutMoney-discountMoney);
                    }
                },
                {
                    field: 'alreadyApplyAmount',
                    title: '已申请金额',
                    width: 100,
                    sortable: true,
                    formatter:function (value) {
                        if (!value){
                            return  0;
                        }
                        return  formatterPrice(value);
                    }
                },
                {
                    field: 'alreadyPaymentAmount',
                    title: '已付款金额',
                    width: 100,
                    sortable: true,
                    formatter:function (value) {
                        if (!value){
                            return  0;
                        }
                        return  formatterPrice(value);
                    }
                },
                {
                    field: 'supplierName2',
                    title: '报关公司',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'ipwCode',
                    title: '付款条件',
                    width: 200,
                    editor: {
                        type: 'combobox',
                        options: {
                            required: true,
                            valueField: "code",
                            textField: "codeWithDesc",
                            data: getDictList('payment_method'),
                            editable: false,
                            panelHeight: '150'
                        }
                    },
                    formatter: function (value) {
                        return getDicName('payment_method',value);
                    }
                },
                {
                    field: 'accountImageCode',
                    title: '对账影像',
                    width: 100,
                    formatter: function (value) {
                        if (value) {
                            return '<a href="javascript:void(0)" onclick="showImage(\'' + value + '\')">'+value+'</a>';
                        }
                        return '';
                    }
                },
                {
                    field: 'invoicedImageCode',
                    title: '开票影像',
                    width: 100,
                    formatter: function (value) {
                        if (value) {
                            return '<a href="javascript:void(0)" onclick="showImage(\'' + value + '\')">'+value+'</a>';
                        }
                        return '';
                    }
                },
                {
                    field: 'imageAllCode',
                    title: '对账付款影像',
                    width: 100,
                    formatter: function (value) {
                        if (value) {
                            return '<a href="javascript:void(0)" onclick="showImage(\'' + value + '\')">'+value+'</a>';
                        }
                        return '';
                    }
                },
                {
                    field: 'itemRemark',
                    title: '摘要',
                    width: 200,
                    styler: function (value, row) {
                        if (row.amountTypeDesc !== '合计') {
                            return 'background-color:#E1E1E1;';
                        }
                        return '';
                    },
                    editor: {type: 'textbox'}
                },
            ]
        ],
        toolbar: el.tbToolbar,
        onBeforeLoad: function () {
            $(el.tb).datagrid('reloadFooter',
                [
                    {
                        amountTypeDesc: '合计',
                        itAmount: 0,
                        budInnerMoney: 0,
                        budOutMoney: 0,
                        alreadyApplyAmount: 0,
                        alreadyPaymentAmount: 0
                    }
                ]
            );
        },
        onLoadSuccess: function () {
            $(el.tb).datagrid('clearSelections');
            summaryItemAmountCod();

            if (optType!==0){
                loadManualCheck();
            }

        },
        onClickRow: function (index, row) {
            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;
                }
                //根据属性判断申请金额是否可编辑
                if(row.amountType === 'Z001'){
                    let budInnerMoney = $(el.tb).datagrid('getEditor', {index: index, field: 'budInnerMoney'});
                    $(budInnerMoney.target).numberbox('disable');

                    let budOutMoney = $(el.tb).datagrid('getEditor', {index: index, field: 'budOutMoney'});
                    $(budOutMoney.target).numberbox('disable');
                }
            }
        }
    });
}

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
            });
        }
    });
}
/**
 * 根据采购订单编号获取付款信息
 * @param poCodes
 */
function findPaymentDetailByPoCode(accountStatementNos) {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/finance/payment/cod/apply/detail/rest/find/payment/detail',
        data:{
            'accountStatementNoList': accountStatementNos
        },
        dataType:'json',
        success: function (data) {
            $(el.tb2).datagrid('loadData', {total: data.rows.length, rows: data.rows});
        },
        error: function (data) {
            console.log(data);
            topWin.layer.alert('数据获取失败, 请联系管理员', {icon: 0});
        }
    });
}


/**
 * 初始化申请付款信息
 */
function initPageDataGrid2() {
    var dataDivHeight = $(el.dataDiv).outerHeight()

    $(el.tb2).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/finance/payment/cod/apply/rest/query/cod/apply/invoice/id',
        //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: {
            id: $(el.id).val(),
            businessType: $(el.businessType).combobox('getValue'),
            dataShowType: 1,
            totalFlag: 1
        },
        columns: [
            [
                {
                    field: 'accountStatementNo',
                    title: '对账单号',
                    width: 150
                },
                {
                    field: 'invoiceNo',
                    title: '开票申请号',
                    width: 180
                },
                {
                    field: 'paymentExpireDate',
                    title: '付款到期日',
                    width: 120,
                    // sortable: true,
                    exportDateFormatter:'date',
                    formatter: function (value, row) {
                        if (!value) {
                            return '';
                        }
                        return '<span style="color: red;">' + moment(value).format('YYYY-MM-DD') + '</span>';
                    }
                },
                {
                    field: 'itAmount',
                    title: '含税金额',
                    width: 100,
                    sortable: true,
                    formatter:function (value) {
                        if (!value){
                            return  0;
                        }
                        return  formatterPrice(value);
                    }
                },
                {
                    field: 'strikePriceAmount',
                    title: '冲账金额',
                    width: 110,
                    sortable: true,
                    formatter:function (value) {
                        if (!value){
                            return  0;
                        }
                        return  formatterPrice(value);
                    }
                },
                {
                    field: 'actualUnpaidAmount',
                    title: '实际应付金额',
                    width: 110,
                    sortable: true,
                    formatter:function (value) {
                        if (!value){
                            return  0;
                        }
                        return  formatterPrice(value);
                    }
                },
                // {
                //     field: 'actualPrepaid',
                //     title: '实际预付金额',
                //     width: 180
                // },
                // {
                //     field: 'deductionPrepaid',
                //     title: '已抵扣预付金额',
                //     width: 180,
                //     // formatter:function (value) {
                //     //     if (!value) {
                //     //         return 0;
                //     //     }
                //     //     return  formatNumber(value, 4, 1);
                //     // }
                // },
                // {
                //     field: 'ticketPrepaid',
                //     title: '票到付款申请金额',
                //     width: 180,
                //     // formatter:function (value) {
                //     //     if (!value) {
                //     //         return 0;
                //     //     }
                //     //     return  formatNumber(value, 4, 1);
                //     // }
                // },
                {
                    field: 'alreadyApplyAmount',
                    title: '已申请金额',
                    width: 180,
                    formatter:function (value) {
                        if (!value){
                            return  0;
                        }
                        return  formatterPrice(value);
                    }
                },
                {
                    field: 'alreadyPaymentAmount',
                    title: '累计已付款金额',
                    width: 180,
                    formatter:function (value) {
                        if (!value){
                            return  0;
                        }
                        return  formatterPrice(value);
                    }
                },
                // {
                //     field: 'remaining',
                //     title: '剩余付款金额',
                //     width: 180
                // },
                // {
                //     field: 'buyer',
                //     title: '采购员',
                //     width: 200
                // },
                // {
                //     field: 'contractNo',
                //     title: '合同号',
                //     width:120,
                //     formatter:function (value,row,index) {
                //         return "<a href='/contract/manage/examine/lookByCode?code=" + window.btoa(encodeURIComponent(value)) + "' target='_blank'>"+value+"</a>"
                //     }
                // },
            ]
        ],
        // onLoadSuccess: function () {
        //     $(el.tb).datagrid('clearSelections');
        // },
        //构造一个满足Datagrid的div
        detailFormatter: function (index) {
            return '<div id="ddv-' + index + '" style="padding: 5px;"></div>';
        },
        onExpandRow: function (index, row) {
            //el.dateViewTotal.push(index);
            catPaymentDetail(index,row);
        },
    });
}

function loadReceiptGrid(){
    $(el.tb3).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/finance/payment/receipt/rest/list?mainId=' + $(el.id).val()+'&businessType=201',
        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');
        },
    });
}

function initTbAttachmentManualCheck(){
    let toolbar = [];
    $(el.tbAttachmentManualCheck).datagrid({
        loadMsg: '数据加载中......',
        height: '460px',
        width: '98%',
        pagination: true,
        autoRowHeight: true,
        remoteSort:false,
        fitColumns: true,
        checkbox: true,
        rownumbers: false,
        singleSelect: true,
        columns: [[
            {
                field: 'type',
                title: "单据类型",
                sortable: true,
                width: 200,
                exportEnum:getDictList('businessFileType'),
                formatter: function (value) {
                    return getDicName('businessFileType',value);
                }
            },
            {
                field: 'manualCheck',
                title: "人工检查",
                sortable: true,
                width: 300,
                formatter: function (value) {
                    if (isBlank(value)) {
                        return '';
                    }
                    if (Number(value)===1) {
                        return '<span style="color:green;">齐全</span>';
                    }else {
                        return '<span style="color:red;">缺失</span>';
                    }
                }
            },
            {
                field: 'remark',
                title: "备注",
                sortable: true,
                width: 300,
                editor: {
                    type: 'textbox'
                }
            }
        ]],
        toolbar: toolbar,
    });
}
/**
 * 查看每个订单下的付款详细数据
 * @param index 行索引
 * @param row 行数据
 */
function catPaymentDetail(index, row) {
    $('#ddv-' + index).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/finance/payment/cod/apply/rest/query/cod/apply/invoice/accountStatementNo',
        singleSelect: false,
        height: 'auto',
        pagination: false,
        width: screenWidth - 10,
        page: 1,
        pageSize: 1000,
        queryParams: {
            accountStatementNo: row.accountStatementNo
        },
        columns: [[
            {
                field: 'status',
                title: '付款状态',
                width: 120,
                formatter: function (value, row, index) {
                    switch (value) {
                        case 1:
                            return '暂存';
                        case 2:
                            return '<span style="color: orange;">待推送审批</span>';
                        case 3:
                            return '<span style="color: blue;">OA审批中</span>';
                        case 4:
                            return '<span style="color: red;">OA审批拒绝</span>';
                        case 5:
                            return '<span style="color: green;">付款完成</span>';
                        case 6:
                            return '<span style="color: red;">OA审批作废</span>';
                        default:
                            return '';
                    }
                }
            },
            {
                field: 'cppNo',
                title: '申请单号',
                width: 150
            },
            {
                field: 'accountStatementNo',
                title: '对账单号号',
                width: 150
            },
            {
                field: 'invoiceNo',
                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: 'budOutMoney',
                title: '申请付款金额',
                width: 100,
                formatter:function (value) {
                    return  formatterPrice(value);
                }
            },
            {
                field: 'itemRemark',
                title: '摘要',
                width: 100,
            },
            {
                field: 'ipwCode',
                title: '付款条件',
                width: 120,
                formatter: function (value) {
                    return getDicName('payment_method',value);
                }
            }
            // {
            //     field: 'deductionPrepaid',
            //     title: '抵扣预付金额',
            //     width: 100
            // },
            // {
            //     field: 'buyer',
            //     title: '采购员',
            //     width: 100
            // }
        ]],
        onLoadSuccess: function (data) {
            $(el.tb2).datagrid('fixDetailRowHeight', index);
            var buyer = row.buyer;
            var rows = data.rows;
            for (let i = 0; i < rows.length; i++) {
                $('#ddv-' + index).datagrid('updateRow',{
                    index: i,
                    row: {
                        buyer: buyer,
                    }
                });
            }
            //$('#supplierTb').datagrid('fixDetailRowHeight', index);
        },
        // onClickRow: function (detailIndex, rowData) {
        //     if (supplierEditIndex === undefined) {
        //         el.tableDom = '#ddv-' + index;
        //         $(el.tableDom).datagrid('beginEdit', detailIndex);
        //         supplierEditIndex = detailIndex;
        //     } else {
        //         supplierEndEditor();
        //         el.tableDom = '#ddv-' + index;
        //         $(el.tableDom).datagrid('beginEdit', detailIndex);
        //         supplierEditIndex = detailIndex;
        //     }
        // },
        onResize: function () {
            $(el.tb2).datagrid('fixDetailRowHeight', index);
        }
        // onCheck: function (rowIndex, rowData) {
        //     $(el.tb).datagrid('unselectAll');
        // },
        // onCheckAll: function (rows) {
        //     $(el.tb).datagrid('unselectAll');
        // }
    });
}

function groupBy (arr, name) {
    const groups = {}
    arr.forEach(function(f) {
        const group = f[name]
        groups[group] = groups[group] || []
        groups[group].push(f)
    })
    return groups;
}
/**
 * 添加发票信息
 */
function addInvoiceData() {
    var companyCode = $(el.companyCode).combobox('getValue'),
        supplierCode = $(el.supplierCode).textbox('getValue'), currencyCode = $(el.currencyCode).combobox('getValue');
    if (!companyCode) {
        topWin.layer.msg('请先选择公司信息', {icon: 0});
        return false;
    }
    // if (!factoryCode) {
    //     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;
    }

    var queryParams = $(el.tb).datagrid('options').queryParams;
    queryParams.companyCode = companyCode;
    // queryParams.factoryCode = factoryCode;
    queryParams.currencyCode = currencyCode;
    queryParams.supplierCode = supplierCode;
    // queryParams.mvPostDateStart = $(el.mvPostDateStart).datebox('getValue');
    // queryParams.mvPostDateEnd = $(el.mvPostDateEnd).datebox('getValue');
    queryParams.applyId = 0;
    $(el.tb).datagrid('options').url = g.ctx + 'fin/payment/cod/apply/rest/query/cod/apply/invoice';
    $(el.tb).datagrid('load');
}
function checkContract(paymentWayCode,businessType,data) {
    var msg = '';
    if (paymentWayCode === 'C') {

        for(var j = 0; j < data.length; j++){
            var item1 = data[j];
            if (item1.contractSupplementStatus === 1||item1.contractSupplementStatus === 2){
                msg+='对账单号：'+item1.accountStatementNo+'，存在购销合同未复核或复核未通过；<br>';
                break;
            }
        }
        if (businessType==='001'&&msg){
            msg+='请上传购销合同并复核！';
            // topWin.layer.alert(msg,{icon: 2, shadeClose: true, title: '温馨提示'});
            // return false;
        }

        //对账单供应商是9999时，判断购销合同类型“加工费合同“附件是否存在，不存在则报错，需要补录；
        if (supplierCode==='9999'){
            for(var jj = 0; jj < data.length; jj++){
                var item11 = data[jj];
                if (!item11.salesProcessAgreementSignStatus) {
                    msg+='对账单号：'+item11.accountStatementNo+'，未上传加工费购销合同；<br>';
                    break;
                }
            }
            if (businessType==='001'&&msg){
                msg+='请上传加工费购销合同并复核！';
                // topWin.layer.alert(msg,{icon: 2, shadeClose: true, title: '温馨提示'});
                // return false;
            }
        }else {
            //对账单供应商不是9999时，判断购销合同类型“材料购销合同“附件是否存在，不存在则报错，需要补录；
            for(var jjj = 0; jjj < data.length; jjj++){
                var item111 = data[jjj];
                if (!item111.itemSalesAgreementSignStatus) {
                    msg+='对账单号：'+item111.accountStatementNo+'，未上传材料购销合同；<br>';
                    break;
                }
            }
            if (businessType==='001'&&msg){
                msg+='请上传材料购销合同并复核！';
                // topWin.layer.alert(msg,{icon: 2, shadeClose: true, title: '温馨提示'});
                // return false;
            }
        }
        return msg;
    }
}
/**
 * 查询发票
 */
function searchInvoiceData() {
    var companyCode = $(el.companyCode).combobox('getValue'),
        supplierCode = $(el.supplierCode).val(),
        currencyCode = $(el.currencyCode).combobox('getValue'),
        businessType = $(el.businessType).combobox('getValue'),
        paymentWayCode = $(el.paymentWayCode).combobox('getValue');
    // 获取已存在的数据
    var rows = $(el.tb).datagrid('getRows');
    for(var m = 0; m < rows.length; m++){
        var item = rows[m];
        if(el.existedData.indexOf(item.dataKey) < 0){
            el.existedData.push(item.dataKey);
        }
    }

    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 (!businessType) {
        topWin.layer.msg('请先选择业务类型', {icon: 0});
        return false;
    }
    var url = '';
    if (businessType==='002'){
        url = g.ctx + 'pc/finance/cost/account/statement/chose/statement/with/apply/dialog?companyCode=' + companyCode + '&supplierCode=' + supplierCode + '&currencyCode=' + currencyCode+ '&paymentWay=' + paymentWayCode;
    }else if (businessType==='005'){
        url = g.ctx + 'pc/finance/company/account/statement/chose/statement/with/apply/dialog?companyCode=' + companyCode + '&supplierCode=' + supplierCode + '&currencyCode=' + currencyCode+ '&paymentWay=' + paymentWayCode;
    }else {
        url = g.ctx + 'pc/finance/account/statement/chose/statement/with/apply/dialog?companyCode=' + companyCode + '&supplierCode=' + supplierCode + '&currencyCode=' + currencyCode+ '&paymentWay=' + paymentWayCode;
    }
    el.choseInvoiceDataDialog = openDialog('chosePcData', url, {
        title: '选择对账单',
        width: '80%',
        height: '90%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.choseInvoiceDataDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['chosePcData'].confirmChose(function (data) {
                        console.log(data)
                        //校验是否已经选择了该对账单
                        var rows = $(el.tb).datagrid('getRows');
                        var businessCodeList = [];
                        for(var i = 0; i < rows.length; i++){
                            var item = rows[i];
                            businessCodeList.push(item.accountStatementNo);
                        }
                        var returnMsg = "";
                        for(var j = 0; j < data.length; j++){
                            var item1 = data[j];
                            if (businessCodeList.indexOf(item1.accountStatementNo) !== -1){
                                returnMsg+='对账单号：'+item1.accountStatementNo+'，已在列表明细中';
                                break;
                            }
                        }
                        if (returnMsg){
                            topWin.layer.alert(returnMsg,{icon: 2, shadeClose: true, title: '温馨提示'});
                            return false;
                        }
                        var msg = checkContract(paymentWayCode,businessType,data)
                        if (msg){
                            topWin.layer.alert(msg,{icon: 2, shadeClose: true, title: '温馨提示'});
                            return false;
                        }

                        // if (paymentWayCode === 'C') {
                        //     var msg = '';
                        //     for(var j = 0; j < data.length; j++){
                        //         var item1 = data[j];
                        //         if (item1.contractSupplementStatus === 1||item1.contractSupplementStatus === 2){
                        //             msg+='对账单号：'+item1.accountStatementNo+'，存在购销合同未复核或复核未通过；<br>';
                        //         }
                        //     }
                        //     if (businessType==='001'&&msg){
                        //         msg+='请上传购销合同并复核！';
                        //         topWin.layer.alert(msg,{icon: 2, shadeClose: true, title: '温馨提示'});
                        //         return false;
                        //     }
                        //
                        //     //对账单供应商是9999时，判断购销合同类型“加工费合同“附件是否存在，不存在则报错，需要补录；
                        //     if (supplierCode==='9999'){
                        //         var msg1 = '';
                        //         for(var jj = 0; jj < data.length; jj++){
                        //             var item11 = data[jj];
                        //             if (!item11.salesProcessAgreementSignStatus) {
                        //                 msg1+='对账单号：'+item11.accountStatementNo+'，未上传加工费购销合同；<br>';
                        //             }
                        //         }
                        //         if (businessType==='001'&&msg1){
                        //             msg1+='请上传加工费购销合同并复核！';
                        //             topWin.layer.alert(msg1,{icon: 2, shadeClose: true, title: '温馨提示'});
                        //             return false;
                        //         }
                        //     }else {
                        //         //对账单供应商不是9999时，判断购销合同类型“材料购销合同“附件是否存在，不存在则报错，需要补录；
                        //         var msg2 = '';
                        //         for(var jjj = 0; jjj < data.length; jjj++){
                        //             var item111 = data[jjj];
                        //             if (!item111.itemSalesAgreementSignStatus) {
                        //                 msg2+='对账单号：'+item111.accountStatementNo+'，未上传材料购销合同；<br>';
                        //             }
                        //         }
                        //         if (businessType==='001'&&msg2){
                        //             msg2+='请上传材料购销合同并复核！';
                        //             topWin.layer.alert(msg2,{icon: 2, shadeClose: true, title: '温馨提示'});
                        //             return false;
                        //         }
                        //     }
                        //
                        //
                        //
                        // }
                        //对账单供应商是9999时，判断购销合同类型“加工费合同“附件是否存在，不存在则报错，需要补录；
                        // if (supplierCode==='9999'){
                        //     var msg1 = '';
                        //     for(var jj = 0; jj < data.length; jj++){
                        //         var item11 = data[jj];
                        //         if (!item11.itemSalesAgreementSignStatus) {
                        //             msg1+='对账单号：'+item11.accountStatementNo+'，未上传加工费购销合同；<br>';
                        //         }
                        //     }
                        //     if (businessType==='001'&&msg1){
                        //         msg1+='请上传加工费购销合同并复核！';
                        //         topWin.layer.alert(msg1,{icon: 2, shadeClose: true, title: '温馨提示'});
                        //         return false;
                        //     }
                        // }else {
                        //     //对账单供应商不是9999时，判断购销合同类型“材料购销合同“附件是否存在，不存在则报错，需要补录；
                        //     var msg2 = '';
                        //     for(var jjj = 0; jjj < data.length; jjj++){
                        //         var item111 = data[jjj];
                        //         if (!item111.salesProcessAgreementSignStatus) {
                        //             msg2+='对账单号：'+item111.accountStatementNo+'，未上传材料购销合同；<br>';
                        //         }
                        //     }
                        //     if (businessType==='001'&&msg2){
                        //         msg2+='请上传材料购销合同并复核！';
                        //         topWin.layer.alert(msg2,{icon: 2, shadeClose: true, title: '温馨提示'});
                        //         return false;
                        //     }
                        // }
                        for(var i = 0; i < data.length; i++){
                            var item = data[i];
                            if (item.supplierName2){
                                $(el.faSupplier).combobox('setValue',item.supplierCode2);
                                $(el.faSupplierName).val(item.supplierName2);
                            }
                            console.log(item)
                            if(el.existedData.indexOf(item.accountStatementNo) < 0){
                                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');
                                    }
                                }
                                $(el.tb).datagrid('appendRow',
                                    {
                                        dataKey: item.accountStatementNo,
                                        accountStatementNo:item.accountStatementNo,
                                        salesProcessAgreementSignStatus:item.salesProcessAgreementSignStatus,
                                        contractSupplementStatus:item.contractSupplementStatus,
                                        itemSalesAgreementSignStatus:item.itemSalesAgreementSignStatus,
                                        invoiceNo:item.invoiceNo,
                                        taxCode:item.taxCode,
                                        paymentExpireDate:item.paymentExpireDate,
                                        expectationPaymentDate:expectationPaymentDate,
                                        purchaseGroup:item.purchaseGroup,
                                        itAmount:businessType==='002'?item.actualUnpaidAmount:item.taxAmount,
                                        strikePriceAmount:item.strikePriceAmount,
                                        actualUnpaidAmount:item.actualUnpaidAmount,
                                        applyAmount:item.applyAmount,
                                        budOutMoney:item.applyAmount,
                                        supplierCode2:item.supplierCode2,
                                        supplierName2:item.supplierName2,
                                        alreadyApplyAmount:item.alreadyApplyAmount,
                                        alreadyPaymentAmount:item.alreadyPaymentAmount,
                                        itemRemark:item.remark,
                                        ipwCode:item.paymentTermCode,
                                        accountImageCode:item.accountImageCode,
                                        invoicedImageCode:item.invoicedImageCode
                                    }
                                );
                                el.existedData.push(item.accountStatementNo);
                            }
                        }
                        // 汇总申请总金额
                        summaryItemAmountCod();
                        loadManualCheck();
                        el.choseInvoiceDataDialog.dialog('close');
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.choseInvoiceDataDialog.dialog('close');
                }
            }
        ]
    });
}


function loadManualCheck(){
    var rows = $(el.tb).datagrid('getRows');
    var businessCodeList = [];
    for(var i = 0; i < rows.length; i++){
        var item = rows[i];
        businessCodeList.push(item.accountStatementNo);
    }

    var businessType = $(el.businessType).combobox('getValue');
    $(el.tbAttachmentManualCheck).datagrid('options').queryParams ={
        businessType: businessType==='001'?1:businessType==='002'?2:businessType==='005'?3:1,
        currencyCode: $(el.currencyCode).combobox('getValue'),
        paymentWay: $(el.paymentWayCode).combobox('getValue'),
        businessCodes: businessCodeList.join(',')
    };
    $(el.tbAttachmentManualCheck).datagrid('options').url = g.ctx + 'pc/finance/attachment/manual/check/rest/listByPayment';
    $(el.tbAttachmentManualCheck).datagrid('load');
}

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

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


/**
 * 数据暂存
 *
 * @param callback 回调函数
 */
function dataSave(callback) {
    // 结束行编辑
    endEditor();
    summaryItemAmountCod();
    const currencyCode = $(el.currencyCode).combobox('getValue');
    const bankCode = $(el.bankCode).combobox('getValue');
    const bankInterCode = $(el.bankInterCode).combobox('getValue');
    if (!validateBankInfo(currencyCode, bankCode, bankInterCode)) {
        return; // 校验银行行号信息
    }
    // rows -> 选中的行; apSumAmount -> 申请付款总金额
    var rows = $(el.tb).datagrid('getRows');
    if (rows.length === 0) {
        topWin.layer.alert('请添加明细数据', {icon: 0});
        return false;
    }


    // let Z003Rows=rows.filter(e=> e.amountType=="Z003");
    // let groupRows = groupBy(Z003Rows,"poCode");
    //
    // for (let i1 = 0; i1 < Object.keys(groupRows).length; i1++) {
    //     const poCode = Object.keys(groupRows)[i1];
    //     let Z003PoRows = groupRows[poCode];
    //     let subjectTypeCode = Z003PoRows[0].subjectTypeCode;
    //     if ("N" == subjectTypeCode) {
    //         let  itemGroupRows = groupBy(Z003Rows,"poItemNo");
    //         for (let j = 0; j < Object.keys(itemGroupRows).length; j++) {
    //             const poItemNo = Object.keys(itemGroupRows)[j];
    //             let Z003PoItemRows = itemGroupRows[poItemNo];
    //             let sum1 = 0;
    //             Z003PoItemRows.forEach(function (row) {
    //                 sum1 = accAdd(sum1, accAdd(row.budOutMoney, row.budInnerMoney));
    //             });
    //             let sum2 = 0;
    //             let Z001Rows = rows.filter(e => e.amountType == "Z001" && poCode == e.poCode && poItemNo == e.poItemNo);
    //             Z001Rows.forEach(function (row) {
    //                 sum2 = accAdd(sum2, accAdd(row.budOutMoney, row.budInnerMoney));
    //             });
    //
    //             if (parseFloat(sum2) + parseFloat(sum1) < 0) {
    //                 topWin.layer.alert('订单号：' + poCode + '，行号：' + poItemNo + '预付总金额不能大于发票总金额', {icon: 0});
    //                 return false;
    //             }
    //         }
    //     } else {
    //         let sum1 = 0;
    //         Z003PoRows.forEach(function (row) {
    //             sum1 = accAdd(sum1, accAdd(row.budOutMoney, row.budInnerMoney));
    //         });
    //
    //         let sum2 = 0;
    //         let Z001Rows = rows.filter(e => e.amountType == "Z001" && poCode == e.poCode);
    //         Z001Rows.forEach(function (row) {
    //             sum2 = accAdd(sum2, accAdd(row.budOutMoney, row.budInnerMoney));
    //         });
    //         if (parseFloat(sum2) + parseFloat(sum1) < 0) {
    //             topWin.layer.alert('订单' + poCode + '预付总金额不能大于发票总金额', {icon: 0});
    //             return false;
    //         }
    //     }
    //
    // }
    let supplierName22 ="";
    let supplierCode22 ="";
    //2024-08-22 邓京术
    //行应付金额 = 本次申请金额 - 折扣金额
    //行应付总金额 = 各行的应付金额汇总 如果 <= 0 则报错不允许暂存
    let rowTotalActualUnpaidAmount = 0;
    let rowTotalApplyAmount = 0;

    for (let i = 0; i < rows.length; i++) {
        var item = rows[i], rowIndex = $(el.tb).datagrid('getRowIndex', item), amountType = item.amountType;
        if (!item.expectationPaymentDate) {
            topWin.layer.alert('对账单号: ' + item.accountStatementNo + '的期望付款日不能为空', {icon: 0});
            return false;
        }
        //期望付款日不能小于当前日期
        if (item.expectationPaymentDate < new Date().format('yyyy-MM-dd')) {
            topWin.layer.alert('对账单号: ' + item.accountStatementNo + '的期望付款日不能小于当前日期', {icon: 0});
            return false;
        }
        if ($(el.supplierReturn).val() === "1") {
            if (Number(item.actualUnpaidAmount) >= 0) {
                topWin.layer.alert('对账单号: ' + item.accountStatementNo + '的实际应付金额必须小于0', {icon: 0});
                return false;
            }
            if (Number(item.budOutMoney) < 0 && Number(item.discountMoney) === 0) {
                topWin.layer.alert('对账单号: ' + item.accountStatementNo + '折扣金额不可以等于0', {icon: 0});
                return false;
            }
        }
        //本次可申请金额小于0，判断本次金额不能大于0
        if (Number(item.applyAmount.toFixed(4))<0){
            if (Number(item.budOutMoney) >0){
                topWin.layer.alert('对账单号: ' + item.accountStatementNo + '的本次申请金额不能大于0', {icon: 0});
                return false;
            }

            if (Number(item.budOutMoney) < Number(item.applyAmount.toFixed(4))) {
                topWin.layer.alert('对账单号: ' + item.accountStatementNo + '的本次申请金额不能大于本次可申请金额', {icon: 0});
                return false;
            }

        }else {
            if (Number(item.budOutMoney) > Number(item.applyAmount.toFixed(4))) {
                topWin.layer.alert('对账单号: ' + item.accountStatementNo + '的本次申请金额不能大于本次可申请金额', {icon: 0});
                return false;
            }
        }
        //如果本次可申请金额小于0， 则折扣金额必须为0
        if (Number(item.applyAmount.toFixed(4) <= 0)) {
            const discountValue = Number(item.discountMoney) || 0;
            if (discountValue !== 0 ) {
                topWin.layer.alert('对账单号: ' + item.accountStatementNo + '的折扣金额必须为0', {icon: 0});
                return false;
            }
        } else {
            if (Number(item.discountMoney) > Number(item.applyAmount.toFixed(4))) {
                topWin.layer.alert('对账单号: ' + item.accountStatementNo + '的折扣金额不能大于本次可申请金额', {icon: 0});
                return false;
            }
        }
        const discountValue = Number(item.discountMoney) || 0;
        rowTotalActualUnpaidAmount = accAdd(rowTotalActualUnpaidAmount, accSub(Number(item.budOutMoney), discountValue));
        rowTotalApplyAmount = accAdd(rowTotalApplyAmount,Number(item.applyAmount));
        // 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) {
    //     topWin.layer.alert('货到付款单预算金额不能小于零', {icon: 0});
    //     return false;
    // }

    var mainData = handleWaitSaveData(rows);
    if(!mainData){
        return false;
    }

    var msg = checkContract(mainData.paymentWayCode,mainData.businessType,rows)
    if (msg){
        topWin.layer.alert(msg,{icon: 2, shadeClose: true, title: '温馨提示'});
        return false;
    }
    // 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;
    }
    //如果付款方式为不是承兑汇票， 则承兑期限不允许选择 2024-08-22 邓京术 财务新需求
    if (mainData.paymentWayCode && mainData.paymentWayCode !== 'C' && mainData.acceptanceMethod) {
        topWin.layer.alert('承兑期限不可选择', {icon: 0});
        $(el.paymentWayDesc).val('');
        $(el.acceptanceMethod).combobox('setValue','');
        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) {
        const userAccount = $(el.userAccount).val();
        console.log(userAccount);
        if(userAccount !=="ZWZN1086"){
            console.log("11");
            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)  && Number(isOa) === 0  && Number(oaCode) !== 2001){
    //     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 ;
    //     }
    // }
    // var transferMoney = 0;
    // //工程技改预算
    // if(oaType&&'工程技改预算' ===oaType){
    //     transferMoney = $('#projectChange-oaTransferMoney').numberbox('getValue');
    // }else if(oaType&&'设备购置预算' ===oaType){
    //     transferMoney = $('#equipmentPurchase-oaTransferMoney').numberbox('getValue');
    // }else if(oaType&&'设备维修预算' ===oaType){
    //     transferMoney = $('#equipmentMaintain-oaTransferMoney').numberbox('getValue');
    // }else if(oaType&&'咨询服务预算' ===oaType){
    //     transferMoney = $('#serviceToBorrow-oaTransferMoney').numberbox('getValue');
    // }else if(oaType&&'日常借款' ===oaType){
    //     transferMoney = $('#borrow-oaTransferMoney').numberbox('getValue');
    // }
    // var oaBorrowMoney = $('#oaBorrowMoney').numberbox('getValue');
    // debugger
    // if(oaType&&'物料采购预算' !==oaType){
    //     if(oaBorrowMoney&&transferMoney){
    //         if(Number(oaBorrowMoney)!==Number(transferMoney)){
    //             layer.alert("转账金额与付款金额必须相同");
    //             return;
    //         }
    //     }else {
    //         layer.alert("转账金额和付款金额必须填值");
    //         return;
    //     }
    // }
    //saveType 1新增 2编辑
    mainData.saveType = optType===0?1:2
    mainData.isPushOa = 0;
    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'pc/finance/payment/cod/apply/rest/dave/saveOrUpdateCheck',
        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/payment/cod/apply/rest/dave/saveOrUpdate',
        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;
}
function findInvalidFields(formId) {
    var invalidFields = [];
    // 查找表单内所有带有验证规则的 input, select, textarea
    $(formId).find('input[required], input.validatebox-text, select[required], textarea[required], .validatebox-invalid').each(function(){
        // 使用 validatebox 的 isValid 方法检查单个字段 (如果它是 easyui-validatebox)
        if ($.fn.validatebox && $(this).data('validatebox')) {
            if (!$(this).validatebox('isValid')) {
                invalidFields.push(this);
                console.log('Invalid field (using validatebox):', this);
            }
        } else {
            // 对于普通的 HTML5 required 或其他简单验证
            // 注意：这种方法不如 validatebox('isValid') 准确，但对于基本 required 检查有效
            if (this.checkValidity && !this.checkValidity()) {
                invalidFields.push(this);
                console.log('Invalid field (using checkValidity):', this);
            } else if ($(this).hasClass('validatebox-invalid')) { // EasyUI 有时会标记此类
                invalidFields.push(this);
                console.log('Invalid field (marked by EasyUI class):', this);
            }
        }
    });
    return invalidFields;
}

/**
 * 处理待保存数据
 *
 * @param rows 明细数据
 * @param apSumAmount 付款总金额
 * @returns {boolean} 结果
 */
function handleWaitSaveData(rows) {
    var headData = {};
    // console.log($('#headForm').form('validate'))
    // console.log($('#'+processName.split("-")[0]).form('validate'))
    // console.log("Form validation failed.");
    // var invalidList = findInvalidFields('#headForm');
    // console.log("List of invalid fields:", invalidList);
    if ($('#headForm').form('validate') && $('#'+processName.split("-")[0]).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.amountType = item.amountType;
        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.ppwCode = item.ppwCode;
        obj.ppwDesc = item.ppwDesc;
        obj.ppcCode = item.ppcCode;
        obj.ppcDesc = item.ppcDesc;
        obj.mvCode = item.mvCode;
        obj.mvItemNo = item.mvItemNo;
        obj.mvPostDate = item.mvPostDate;
        obj.mvNum = item.mvNum;
        obj.invoiceYear = item.invoiceYear;
        obj.invoiceNo = item.invoiceNo;
        obj.invoiceItemNo = item.invoiceItemNo;
        obj.invoicePostDate = item.invoicePostDate;
        obj.invoiceText = item.invoiceText;
        obj.ipwCode = item.ipwCode;
        obj.ipwDesc = item.ipwDesc;
        obj.ipcCode = item.ipcCode;
        obj.ipcDesc = item.ipcDesc;
        obj.jcPoCode = item.jcPoCode;
        obj.jcPoItemNo = item.jcPoItemNo;
        obj.jcFactoryCode = item.jcFactoryCode;
        obj.posNegFlag = item.posNegFlag;
        obj.sourceId = item.detailId;
        obj.contractNo = item.contractNo;
        obj.contractName = item.contractName;
        obj.subjectTypeCode = item.subjectTypeCode;
        obj.accountStatementNo = item.accountStatementNo;
        obj.strikePriceAmount = item.strikePriceAmount;
        obj.actualUnpaidAmount = item.actualUnpaidAmount;
        obj.discountMoney = item.discountMoney;
        obj.expectationPaymentDate = item.expectationPaymentDate;
        if (Number(item.applyAmount) === (Number(item.budInnerMoney).add(Number(item.budOutMoney)))) {
            obj.isUsed = 1;
        } else {
            obj.isUsed = 0;
        }
        itemList.push(obj);
    }
    headData.itemList = itemList;
    headData.delItemIdList = el.tempDelTbData.length === 0 ? '' : el.tempDelTbData;

    return headData;
}



/**
 * 选择供应商
 */
function choseSupplier() {
    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.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);

                        }

                        // debugger
                        // if (cbox[0].currencyCode==='CNY'){
                        //     $(el.bankCode).combobox({ required: true });
                        //     $(el.bankInterCode).combobox({ required: false });
                        // }else {
                        //     $(el.bankCode).combobox({ required: false });
                        //     $(el.bankInterCode).combobox({ required: true });
                        // }

                        //清空表格数据
                        $('#tb').datagrid('loadData', {total: 0, rows: []})
                        choseSupplierDialog.dialog('close');
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    choseSupplierDialog.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]);
            }
        }
    });
    if (cbox[0].currencyCode==='CNY'){
        $(el.bankCode).combobox({ required: true });
        $(el.bankInterCode).combobox({ required: false });
    }else {
        $(el.bankCode).combobox({ required: false });
        $(el.bankInterCode).combobox({ required: true });
    }

}

function findSupplierPaymentPlanSummary(supplierCode, companyCode) {
    $.ajax({
        url: g.ctx + 'pc/finance/payment/plan/rest/findSupplierPaymentPlanSummary',
        type: 'POST',
        async: false,
        data: {companyCode: companyCode, supplierCode: supplierCode, paymentType : 'D'},
        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 choseOaDepName() {
    var url = g.ctx + 'fin/payment/advance/apply/get/department';
    el.choseOaDepNameDialog = openDialog('choseOaDepName', url, {
        title: '部门选择',
        width: '700px',
        height: '560px',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.choseOaDepNameDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseOaDepName'].save(function (data) {
                        $('#oaDepName').textbox('setValue',data.name);
                        el.choseOaDepNameDialog.dialog('close');

                        //清空表格数据
                        $('#tb').datagrid('loadData',{ total: 0, rows: [] })
                        el.existedData =[]
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.choseOaDepNameDialog.dialog('close');
                }
            }
        ]
    });
}
//选择预算数据
function choseBudget() {
    var url = g.ctx + 'fin/payment/advance/apply/get/budget';
    el.choseBudgetDialog = openDialog('choseBudget', url, {
        title: '预算数据选择',
        width: '1050px',
        height: '560px',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.choseBudgetDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseBudget'].save(function (data) {
                        if(data.gsx === '长春金赛药业有限责任公司'){
                            $('#companyCode').combobox('setValue', 1000);
                        }else if(data.gsx === '吉林省金派格药业有限责任公司'){
                            $('#companyCode').combobox('setValue', 1100);
                        }else if(data.gsx === '吉林省金康安医药有限责任公司'){
                            $('#companyCode').combobox('setValue', 1200);
                        }else if(data.gsx === '上海赛增医疗科技有限公司'){
                            $('#companyCode').combobox('setValue', 1300);
                        }
                        $('#oaType').combobox('setValue',data.lbx);
                        //日常借款取年度预算 其他取预算科目描述
                        if(data.lbx === '日常借款'){
                            $('#oaYearBudget').val(data.bz);
                        }
                        $('#oaSubName').textbox('setValue',data.yskm);
                        $('#oaCode').textbox('setValue',data.dm);
                        $('#oaDepName').textbox('setValue',data.departmentname);
                        $('#oaQuarter').combobox('setValue', data.jdx);
                        $('#oaQuaeterBud').numberbox('setValue', data.byzjzcysy);
                        $('#oaXm').combobox('setValue', data.xm);
                        $('#oaYwkm').combobox('setValue', data.ywkm);
                        $('#llkzj').val(data.llkzj);
                        el.choseBudgetDialog.dialog('close');
                        //清空表格数据
                        $('#tb').datagrid('loadData', {total: 0, rows: []})
                        el.existedData =[]
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.choseBudgetDialog.dialog('close');
                }
            }
        ]
    });
}
//选择申请人
function choseApplyUser() {
    var url = g.ctx + 'fin/payment/advance/apply/get/user';
    el.choseApplyUserDialog = openDialog('choseApplyUserDialog', url, {
        title: '请选择人员',
        width: '700px',
        height: '560px',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.choseApplyUserDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseApplyUserDialog'].saveUserData(function (data) {
                        $('#oaApplyUserName').textbox('setValue',data.username);
                        $('#oaApplyUserCode').val(data.workNo);
                        el.choseApplyUserDialog.dialog('close');
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.choseApplyUserDialog.dialog('close');
                }
            }
        ]
    });
}
/**
 * 选择供应商弹框主动关闭弹框(重要)
 *
 * @param data 选中的结果
 */
function choseSupDialogConfirm(data) {
    $(el.supplierCode).textbox('setValue', data.supplierCode);
    $(el.supplierName).val(data.supplierName);
    el.choseSupplierDialog.dialog('close');
    // findCurrencyDataBySupplierCode(data.supplierCode);
}


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

    $(el.factoryCode).combobox({
        url: factoryDataUrl,
        valueField: 'factoryCode',
        textField: 'factoryCodeName',
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        panelWidth: 260,
        editable: false,
        disabled: false,
        required: true,
        onLoadSuccess: function (data) {
            if (data.length === 1) {
                $(el.factoryCode).combobox('setValue', data[0].factoryCode);
                $(el.factoryName).val(data[0].factoryName);
            }
        },
        onSelect: function (data) {
            $(el.factoryName).val(data.factoryName);
        }
    });
}


/**
 * 根据供应商编码获取币种下拉框数据
 *
 * @param supplierCode 供应商编码
 */
function findCurrencyDataBySupplierCode(supplierCode) {
    $(el.currencyCode).combobox({
        url: g.ctx + 'fin/common/rest/find/supplier/currency?supplierCode=' + supplierCode,
        valueField: 'currencyCode',
        textField: 'currencyCode',
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        panelWidth: 200,
        editable: false,
        disabled: false,
        required: true,
        onLoadSuccess: function (data) {
            if (data.length === 1) {
                $(el.currencyCode).combobox('setValue', data[0].currencyCode);
            }
        }
    });
}
function findFaSupplierBySupplierCode(supplierCode) {
    $.ajax({
        url: g.ctx + 'pc/supplier/supRelationBid/rest/getBySupplierCode?supplierCode=' + supplierCode,
        type: 'POST',
        success: function (res) {
            if (res) {
                $(el.faSupplier).val(res.faSupplier);
                $(el.faSupplierName).textbox('setValue',res.faSupplierName);
            }
        }
    });
}

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', '');
}

//获取oa数据
function syncOAData() {
    let oaSubName = $('#oaSubName').textbox('getValue');
    let oaCode = $('#oaCode').textbox('getValue');
    let oaDepName = $('#oaDepName').textbox('getValue');
    let oaQuarter = $('#oaQuarter').combobox('getValue');
    let oaType = $('#oaType').combobox('getValue');
    let companyName = $('#companyName').val();
    let oaXm = $('#oaXm').combobox('getValue');
    let oaYwkm = $('#oaYwkm').combobox('getValue');
    let llkzj = $('#llkzj').val();
    if(!oaSubName || !oaCode || !oaDepName || !oaQuarter || !oaType || !companyName){
        layer.alert("请先填写【预算科目】【代码】【部门】【季度】【类别】【公司】信息");
        return;
    }
    let obj = {
        gsx:companyName,
        departmentname:oaDepName,
        lbx:oaType,
        dm:oaCode,
        jdx:oaQuarter,
        xm: oaXm,
        ywkm: oaYwkm,
        llkzj: llkzj
    };

    var loading = topWin.layer.msg('同步OA数据中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'fin/payment/advance/apply/rest/oa/sync',
        type: 'POST',
        data: {param:JSON.stringify(obj)},
        success: function (data) {
            topWin.layer.close(loading);
            $('#oaSubKey').val(data[0].llkzj);
            $('#oaDepKey').val(data[0].bmid);
            $('#oaYear').val(data[0].nf);
            $('#'+processName+'oaDemandDep').val(data[0].xqbm);
            $('#oaAleradyPayMoney').numberbox('setValue',data[0].yfky);
            $('#oaPlantArea').combobox('setValue',data[0].cqdd);
            $('#'+processName+'oaContract').textbox('setValue',data[0].hthmc);
            $('#'+processName+'oaSpecs').textbox('setValue',data[0].gg);
            $('#'+processName+'oaUnit').textbox('setValue',data[0].dw);
            $('#'+processName+'oaNum').numberbox('setValue',data[0].sl);
            $('#oaQuaeterBud').numberbox('setValue',data[0].byzjzcysy);
            $('#oaBudInnerMoney').numberbox('setValue',data[0].ysn);
            $('#oaBudOutMoney').numberbox('setValue',data[0].ysw);
            //余额根据 总额-预算内已支出
            $('#oaBalance').numberbox('setValue', accSub($('#oaQuaeterBud').numberbox('getValue'), $('#oaBudInnerMoney').numberbox('getValue')));
            $('#'+processName+'oaContractMoney').numberbox('setValue',data[0].htzje);
            $('#'+processName+'oaDeviceName').textbox('setValue',data[0].wxyy);
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON, {icon: 2});
        }
    });
}

//获取oa数据
function onChangeSyncOA() {
    let oaXm = $('#oaXm').combobox('getValue');
    let oaYwkm = $('#oaYwkm').combobox('getValue');
    if(oaXm&&oaYwkm){
        let oaSubName = $('#oaSubName').textbox('getValue');
        let oaCode = $('#oaCode').textbox('getValue');
        let oaDepName = $('#oaDepName').textbox('getValue');
        let oaQuarter = $('#oaQuarter').combobox('getValue');
        let oaType = $('#oaType').combobox('getValue');
        let companyName = $('#companyName').val();
        let llkzj = $('#llkzj').val();
        if(!oaSubName || !oaCode || !oaDepName || !oaQuarter || !oaType || !companyName){
            layer.alert("请先填写【预算科目】【代码】【部门】【季度】【类别】【公司】信息");
            return;
        }
        let obj = {
            gsx:companyName,
            departmentname:oaDepName,
            lbx:oaType,
            dm:oaCode,
            jdx:oaQuarter,
            xm: oaXm,
            ywkm: oaYwkm,
            llkzj: llkzj
        };

        var loading = topWin.layer.msg('同步OA数据中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'fin/payment/advance/apply/rest/oa/sync',
            type: 'POST',
            data: {param:JSON.stringify(obj)},
            success: function (data) {
                topWin.layer.close(loading);
                $('#oaSubKey').val(data[0].llkzj);
                $('#oaDepKey').val(data[0].bmid);
                $('#oaYear').val(data[0].nf);
                $('#'+processName+'oaDemandDep').val(data[0].xqbm);
                $('#oaAleradyPayMoney').numberbox('setValue',data[0].yfky);
                $('#oaPlantArea').combobox('setValue',data[0].cqdd);
                $('#'+processName+'oaContract').textbox('setValue',data[0].hthmc);
                $('#'+processName+'oaSpecs').textbox('setValue',data[0].gg);
                $('#'+processName+'oaUnit').textbox('setValue',data[0].dw);
                $('#'+processName+'oaNum').numberbox('setValue',data[0].sl);
                $('#oaQuaeterBud').numberbox('setValue',data[0].byzjzcysy);
                $('#oaBudInnerMoney').numberbox('setValue',data[0].ysn);
                $('#oaBudOutMoney').numberbox('setValue',data[0].ysw);
                //余额根据 总额-预算内已支出
                $('#oaBalance').numberbox('setValue', accSub($('#oaQuaeterBud').numberbox('getValue'), $('#oaBudInnerMoney').numberbox('getValue')));
                $('#'+processName+'oaContractMoney').numberbox('setValue',data[0].htzje);
                $('#'+processName+'oaDeviceName').textbox('setValue',data[0].wxyy);
            },
            error: function (data) {
                topWin.layer.close(loading);
                $('#oaQuaeterBud').numberbox('setValue',0);
                $('#oaBudInnerMoney').numberbox('setValue',0);
                $('#oaBudOutMoney').numberbox('setValue',0);
                //余额根据 总额-预算内已支出
                $('#oaBalance').numberbox('setValue',0);
            }
        });
    }
}
/**
 * 子级页面获取数据(重要)
 */
function childrenPageFindData() {
    return el.existedData;
}

/**
 * 表格添加行
 */
function dataGirdAddRow(row) {
    row.id = 0;
    $(el.tb).datagrid('appendRow', row);
}


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;
    }
    // if (supplierCode==='9999'){
    //     supplierCode = '801400';
    // }
    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 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
                }
            ]
        ]
    });
}

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);
    });
}