var el = {
    dataPanel: '#dataPanel',
    dataDiv: '#dataDiv',
    isSupplier: '#isSupplier',
    tbAttachmentManualCheck: '#tbAttachmentManualCheck',
    editManualIndex: undefined,
    tbSignFileRowsExt: false,
    tbSaleFileRowsExt: false,
    tbInvoiceFileRowsExt: false,
    tbInvoicePaymentCertificateFileRowsExt: false,
    id: '#id',
    tbSignFile: '#tbSignFile',
    tbStatementSignFile:'#tbStatementSignFile',
    accountId: '#accountId',
    iaNo: '#invoiceApplyNo',
    orderType: '#orderType',
    accountStatementNo: '#accountStatementNo',
    imgCode: '#imgCode',
    accountStatementId: '#accountStatementId',
    accountStatementYear: '#accountStatementYear',
    accountStatementMonth: '#accountStatementMonth',
    supplierCode: '#supplierCode',
    companyCode: '#companyCode',
    factoryCode: '#factoryCode',
    currencyCode: '#currencyCode',
    deductionAmount: '#deductionAmount',
    dntAmount: '#dntAmount',
    rebateAmount: '#rebateAmount',
    rntAmount: '#rntAmount',
    invoiceNetAmount: '#invoiceNetAmount',
    invoiceTaxAmount: '#invoiceTaxAmount',
    taxAmount: '#taxAmount',
    tariffTotalAmount: '#tariffTotalAmount',
    valueAddedTaxTotalAmount: '#valueAddedTaxTotalAmount',
    freightAndMiscellaneousFeeIncludingTaxTotal: '#freightAndMiscellaneousFeeIncludingTaxTotal',
    domesticTaxTotalAmount: '#domesticTaxTotalAmount',
    invoiceTotalDiffAmount: '#invoiceTotalDiffAmount',
    paymentCertificateTotalExclTax: '#paymentCertificateTotalExclTax',
    paymentCertificateTotalInclTax: '#paymentCertificateTotalInclTax',
    paymentCertificateTaxAmount: '#paymentCertificateTaxAmount',
    files: '#files',
    allBudInnerMoney: '#allBudInnerMoney',
    strikePriceAmount: '#strikePriceAmount',
    actualUnpaidAmount: '#actualUnpaidAmount',
    invoiceNum: '#invoiceNum',
    taxCode: '#taxCode',
    inStockStartDate: '#inStockStartDate',
    inStockEndDate: '#inStockEndDate',
    paymentTermCode: '#paymentTermCode',
    invoiceNo: '#invoiceNo',
    remark: '#remark',
    approveRemark: '#approveRemark',
    dataTabs: '#dataTabs',
    tbFile: '#tbFile',
    tbDetails: '#tbDetails',
    tbInvoicePaymentCertificate: '#tbInvoicePaymentCertificate',
    tbInvoicePaymentCertificateTable: '#tbInvoicePaymentCertificateTable',
    tbAttachment: '#tbAttachment',
    tbAttachmentCheck: '#tbAttachmentCheck',
    tbDeduction: '#tbDeduction',
    tbAdvance: '#tbAdvance',
    editAdvanceIndex: undefined,
    diffAmount1: '#diffAmount1',
    tbRebate: '#tbRebate',
    addDetailDialog: null,
    addRebateDialog: null,
    addDeductionDialog: null,
    choseAccountStatement: null,
    delDetail: [],
    delRebate: [],
    delDeduction: [],
    originalSignRows: [],
    userTableColumn: [],
    originalRows: [],
    bodyHeight: document.documentElement.clientHeight,
    supplierCurrencyCode: null,
    supplierTaxRate: null,
    supplierBusinessRegisterNo: businessRegisterNo,
    companyName: '#companyNameDesc',
    supplierName: '#supplierName',
    tbInvoice: '#tbInvoice',
    invoiceTotalAmount: '#invoiceTotalAmount',
    invoiceTaxTotalAmount: '#invoiceTaxTotalAmount',
    diffAmount: '#diffAmount',
    diffAmountSap: '#diffAmountSap',
    diffTaxAmountSap: '#diffTaxAmountSap',
    tbIaApprove: '#tbIaApprove',
    poType: '#poType',
    purchaseGroup: '#purchaseGroup',
    paperlessFlag: '#paperlessFlag',
    paymentWay: '#paymentWay',
    delInvoice: [],
    typeName : 'add_fast'
};
let uploadAttachmentFileDialog;

$(function () {
    initDict('payment_method,po_type,unit,sign_order,sign_type,po_item_subject,po_item_type,businessFileType')
    initDictName('businessFileType')
    initNecessaryDatas('pc/sys/tax/rest/listAll')
    initFileForm('account-file-form')
    $(el.dataPanel).panel({
        collapsible: true,
        onCollapse: function () {
            // $(el.dataTabs).tabs('select', 0);

            $(el.tbDetails).datagrid('resize', {height: el.bodyHeight - 80});
            // $(el.tbRebate).datagrid('resize', {height: el.bodyHeight - 80});
            // $(el.tbDeduction).datagrid('resize', {height: el.bodyHeight - 80});
            $(el.tbAdvance).datagrid('resize', {height: el.bodyHeight - 80});
            $(el.tbIaApprove).datagrid('resize', {height: el.bodyHeight - 80});
            $(el.tbInvoice).datagrid('resize', {height: el.bodyHeight - 80});
            $(el.tbSignFile).datagrid('resize', {height: el.bodyHeight - 80});
            $(el.tbStatementSignFile).datagrid('resize', {height: 50});

            // if ($(el.tbAttachment).length>0){
            //     $(el.tbAttachment).datagrid('resize', {height: el.bodyHeight - 80});
            // }
            // $(el.tbAttachmentCheck).datagrid('resize', {height: el.bodyHeight - 80});
            if (manualCheckShowFlag){
                $(el.tbAttachmentManualCheck).datagrid('resize', {height: el.bodyHeight - 80});
            }
        },
        onExpand: function () {
            // $(el.dataTabs).tabs('select', 0);

            var dataDiv = $(el.dataDiv).outerHeight() + 90;
            $(el.tbDetails).datagrid('resize', {height: el.bodyHeight - dataDiv});
            // $(el.tbRebate).datagrid('resize', {height: el.bodyHeight - dataDiv});
            // $(el.tbDeduction).datagrid('resize', {height: el.bodyHeight - dataDiv});
            $(el.tbAdvance).datagrid('resize', {height: el.bodyHeight - dataDiv});
            $(el.tbIaApprove).datagrid('resize', {height: el.bodyHeight - dataDiv});
            $(el.tbSignFile).datagrid('resize', {height: el.bodyHeight - dataDiv});
            // $(el.tbAttachmentCheck).datagrid('resize', {height: el.bodyHeight - dataDiv});
            // if ($(el.tbAttachment).length>0){
            //     $(el.tbAttachment).datagrid('resize', {height: el.bodyHeight - dataDiv});
            // }
            // $(el.tbAttachmentCheck).datagrid('resize', {height: el.bodyHeight - dataDiv});
            $(el.tbStatementSignFile).datagrid('resize', {height: 50});
            if (manualCheckShowFlag){
                $(el.tbAttachmentManualCheck).datagrid('resize', {height: 400});
            }
        }
    });

    // 加载页面输入或下拉框数据
    initPageInput();
    // 获取当前用户在本页面中表格列配置
    // findUserTableColumn();

    initTbDetails();

    initTbIaApprove();
    loadSignFileGrid();

    // if ($(el.tbAttachment).length>0){
    //     loadTbAttachmentGrid();
    // }
    // initTbAttachmentCheck();
    // initTbDeduction();
    // initTbRebate();
    loadtbStatementSignFileGrid();


    if (manualCheckShowFlag){
        initTbAttachmentManualCheck();
        $(el.tbAttachmentManualCheck).datagrid('options').queryParams = {
            businessType: 2,
            businessId: $(el.accountId).val(),
            businessCode: $(el.accountStatementNo).textbox('getValue')
        };
        $(el.tbAttachmentManualCheck).datagrid('options').url = g.ctx + 'pc/finance/attachment/manual/check/rest/list';
        $(el.tbAttachmentManualCheck).datagrid('load');
    }

    if (optType!==0){
        findStatementDetail();
    }
    if (optType===3){
        findAdvanceDetail();
    }
});

/**
 * 初始化页面输入框
 */
function initPageInput() {

    // 初始化公司代码下拉框
    $(el.companyCode).combobox({
        url: g.ctx + 'pc/sys/company/rest/listAll',
        panelHeight: 300,
        panelWidth: 340,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---'
    });

    // 初始化工厂代码下拉框
    $(el.factoryCode).combobox({
        url: g.ctx + 'pc/sys/factory/rest/listAll',
        editable: false,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        panelHeight: 'auto'
    });

    // 初始化税率代码下拉框
    // $(el.taxCode).combobox({
    //     required: true,
    //     panelHeight: 300,
    //     panelWidth: 340,
    //     limitToList: 'true',
    //     valueField: 'taxCode',
    //     method: 'GET',
    //     textField: 'codeWithDesc',
    //     url: g.ctx + 'pc/sys/tax/rest/listAll',
    //     prompt: '--- 请选择 ---'
    // });
    // // 付款条件
    // $(el.paymentTermCode).combobox({
    //     required: true,
    //     limitToList: 'true',
    //     panelHeight: 'auto',
    //     panelWidth: 200,
    //     method: 'GET',
    //     valueField: 'code',
    //     textField: 'codeWithDesc',
    //     prompt: '--- 请选择 ---',
    //     url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_method',
    // });
    // 付款方式
    $(el.paymentWay).combobox({
        required: true,
        panelHeight: '200',
        valueField: 'code',
        limitToList: 'true',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        method: 'GET',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_way'
    });
    // 订单类型
    // $(el.poType).combobox({
    //     required: false,
    //     limitToList: 'true',
    //     panelHeight: 'auto',
    //     panelWidth: 200,
    //     method: 'GET',
    //     valueField: 'code',
    //     textField: 'codeWithDesc',
    //     prompt: '--- 请选择 ---',
    //     url: g.ctx + 'pc/sys/dict/getDicByType?type=po_type',
    // });

    //采购组
    $(el.purchaseGroup).combobox({
        required: true,
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'GET',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll',
        prompt: '--- 请选择 ---',
    });

    $(el.paperlessFlag).combobox({
        required: true,
        valueField: 'value',
        textField: 'label',
        data: [
            {label: '否', value: '0'},
            {label: '是', value: '1'}
        ],
        limitToList: 'true',
        panelHeight: 'auto',
        prompt: '--- 请选择 ---'
    });

    // 初始化币种下拉框
    getExchangeRate($(el.currencyCode).textbox('getValue'));

    $(el.accountStatementNo).textbox({
        prompt: '请选择对账单',
        required: true,
        icons: [
            {
                iconCls: 'icon-search',
                handler: function () {
                    choseAccountStatement();
                }
            }
        ]
    });
    $(el.accountStatementNo).textbox('textbox').css('cursor', 'pointer');
    $(el.accountStatementNo).textbox('textbox').bind('click', function () {
        choseAccountStatement();
    });

    $(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 showImage(imageCode){
    $.ajax({
        type: 'get',
        url: g.ctx + 'pc/sys/kingdeeImage/rest/getImageViewPath',
        data: {
            imageCode: imageCode
        },
        success: function (data) {
            if (data) {
                window.open(data, "_blank");
            }
        },
        error: function (error) {
            topWin.layer.alert(error.responseJSON.message, {
                icon: 2,
                content: error.responseJSON.message
            });
        }
    });
}

/**
 * 初始化对账明细表格
 */
function initTbDetails() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90, orderType = $(el.orderType).val();
    // var columns = dynamicColumns(orderType);

    var toolbar = [];

    if (!lookFlag){
        // toolbar.push(
        //     {
        //         text: '获取对账明细',
        //         iconCls: 'icon-add',
        //         handler: function () {
        //             findStatementDetail();
        //         }
        //     }
        // )
    }
    //供应商不能看到的字段
    // if (Number($(el.isSupplier).val())===1){
    //     columns = columns.filter(obj => obj.field !== 'paymentExpireDate');
    // }
    $(el.tbDetails).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        // height: el.bodyHeight - dataDiv,
        height: 400,
        singleSelect: false,
        rownumbers: true,
        showFooter: true,
        pagination: true,
        remoteSort:false,
        pageSize: 500,
        pageList: [10, 50, 100, 200, 500, 1000],
        queryParams: {
            iaId: $(el.id).val(),
            becShare: 0
        },
        columns: [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'code',
                title: '委托单号',
                width: '120',
                align: 'left'
            },
            {
                field: 'customsDeclarationCode',
                title: '报关单号',
                width: '120',
                align: 'left'
            },
            {
                field: 'codeDate',
                title: '报关日期',
                width: '150',
                align: 'left',
                formatter: function (value) {
                    if (value) {
                        return new Date(value).format('yyyy-MM-dd');
                    }
                    return value;
                }
            },
            {
                field: 'num',
                title: '数量',
                width: '120',
                align: 'left'
            },
            {
                field: 'taxAmount',
                title: '进口总价(USD)',
                width: '120',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            },
            {
                field: 'tariffPrice',
                title: '关税(CNY)',
                width: '120',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            },
            {
                field: 'valueAddedTaxPrice',
                title: '增值税(CNY)',
                width: '120',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            },
            {
                field: 'agencyFeePrice',
                title: '代理费(CNY)',
                width: '120',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            },
            {
                field: 'domesticFeePrice',
                title: '境内费用(CNY)',
                width: '120',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            },
            {
                field: 'overseasFeePrice',
                title: '境外费用(CNY)',
                width: '120',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            },
            {
                field: 'feeTaxAmountPrice',
                title: '费用税额(CNY)',
                width: '120',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            },
            {
                field: 'freightPrice',
                title: '运费(CNY)',
                width: '120',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            },
            {
                field: 'freightTaxAmountPrice',
                title: '运费用税额(CNY)',
                width: '120',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            },
            {
                field: 'otherFeePrice',
                title: '其他费用',
                width: '120',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            }
        ]],
        loadFilter: pagerFilter,
        toolbar: toolbar,
        onBeforeSortColumn:function(sort, order){
            if (order.toUpperCase() === 'DESC')
                order = -1
            else
                order = 1;
            el.originalRows.sort(function (a, b) {
                if (parseFloat(a[sort]) > 1 * b[sort])
                    return 1 * order;
                else if (a[sort] * 1 < 1 * b[sort])
                    return -1 * order;
                else
                    return 0;
            });
            return true;
        }, onLoadSuccess: function (data) {
            // 在第一个表格数据加载成功后，获取数据并准备加载第二个表格
            var firstGridData = data.rows; // 获取第一个表格的数据
            // initTbAdvance(firstGridData);
            calculateTaxAmount();

             //业务编码集合
            // var businessCodes = [];
            // var detail = data.rows;
            // for(var ii = 0; ii < detail.length; ii++){
            //     if (detail[ii].poCode){
            //         businessCodes.push(detail[ii].poCode);
            //     }
            // }
            // //businessCodes中去重
            // if (businessCodes.length > 0){
            //     businessCodes = businessCodes.filter(function(item, index, self) {
            //         return self.indexOf(item) === index;
            //     })
            //     el.businessCodes = businessCodes;
            //     if ($(el.tbAttachment).length>0){
            //         $(el.tbAttachment).datagrid('options').loadFilter = pagerSignFilter;
            //         $(el.tbAttachment).datagrid('options').url = g.ctx + 'pc/finance/invoiced/apply/attachment/rest/list?businessCodes='+businessCodes.join(',')+'&businessTypeCodes=purchase_order&reloadFlag=0&iaId='+$(el.id).val();
            //         if (optType===0){
            //             $(el.tbAttachment).datagrid('options').url = g.ctx + 'pc/finance/invoiced/apply/attachment/rest/list?businessCodes='+businessCodes.join(',')+'&businessTypeCodes=purchase_order&reloadFlag=1';
            //         }
            //         if (optType===1){
            //             $(el.tbAttachment).datagrid('options').url = g.ctx + 'pc/finance/invoiced/apply/attachment/rest/list?businessCodes='+businessCodes.join(',')+'&businessTypeCodes=purchase_order&reloadFlag=1&iaId='+$(el.id).val();
            //         }
            //         $(el.tbAttachment).datagrid('load');
            //
            //
            //
            //     }
            //
            //
            // }

        }

    });

    if (optType!==0){
        var queryParams = $(el.tbDetails).datagrid('options').queryParams;
        queryParams.asId = $(el.accountId).val();
        queryParams.becShare = 0;
        $(el.tbDetails).datagrid('options').loadFilter = pagerFilter;
        $(el.tbDetails).datagrid('options').url = g.ctx + 'pc/finance/cost/account/statement/detail/rest/find/by/statement/id';
        $(el.tbDetails).datagrid('load');
    }
}
function calculateTaxAmount(){
    var allRows = $(el.tbDetails).datagrid('getRows');
    //增值税
    var totalCustomsPaymentCertificateTaxAmount = new BigNumber(0);
    //关税
    var totalTariffPrice = new BigNumber(0);
    //国内税额合计
    var totalDomesticTaxTotalAmount = new BigNumber(0);
    //分摊费用金额
    var totalSharedExpenseAmount = new BigNumber(0);
    for (let i = 0; i < allRows.length; i++) {
        if (allRows[i].valueAddedTaxPrice){
            totalCustomsPaymentCertificateTaxAmount = new BigNumber(allRows[i].valueAddedTaxPrice).plus(totalCustomsPaymentCertificateTaxAmount);
        }
        if (allRows[i].tariffPrice){
            totalTariffPrice = new BigNumber(allRows[i].tariffPrice).plus(totalCustomsPaymentCertificateTaxAmount);
        }
        totalDomesticTaxTotalAmount =  new BigNumber(allRows[i].feeTaxAmountPrice?allRows[i].feeTaxAmountPrice:0).plus(new BigNumber(allRows[i].freightTaxAmountPrice?allRows[i].freightTaxAmountPrice:0)).plus(totalDomesticTaxTotalAmount);
        totalSharedExpenseAmount = new BigNumber(allRows[i].agencyFeePrice?allRows[i].agencyFeePrice:0)
            .plus(new BigNumber(allRows[i].domesticFeePrice?allRows[i].domesticFeePrice:0))
            .plus(new BigNumber(allRows[i].overseasFeePrice?allRows[i].overseasFeePrice:0))
            .plus(new BigNumber(allRows[i].freightPrice?allRows[i].freightPrice:0))
            .plus(new BigNumber(allRows[i].otherFeePrice?allRows[i].otherFeePrice:0))
            .plus(totalSharedExpenseAmount);
    }
    // $(el.tariffTotalAmount).textbox('setValue',totalTariffPrice);
    $(el.valueAddedTaxTotalAmount).textbox('setValue',totalCustomsPaymentCertificateTaxAmount);
    $(el.freightAndMiscellaneousFeeIncludingTaxTotal).textbox('setValue',totalSharedExpenseAmount);
    $(el.domesticTaxTotalAmount).textbox('setValue',totalDomesticTaxTotalAmount);
    // $(el.taxAmount).textbox('setValue',totalSharedExpenseAmount.plus(totalDomesticTaxTotalAmount));
}
/**
 * 初始化审批信息表格
 */
function initTbIaApprove() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;

    $(el.tbIaApprove).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        // height: el.bodyHeight - dataDiv,
        height: 400,
        url: g.ctx + 'pc/finance/cost/invoiced/apply/detail/rest/find/ia/approve/log',
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: true,
        queryParams: {
            iaId: $(el.id).val()
        },
        columns: [
            [
                {
                    field: 'approveNode',
                    title: '审批节点描述',
                    width: 120,
                    formatter: function (value) {
                        if(Number(value) === 1){
                            return '对账确认';
                        }else {
                            return '财务节点';
                        }
                    }
                },
                {
                    field: 'approveResult',
                    title: '审批结果',
                    width: 120,
                    formatter: function (value) {
                        switch (Number(value)){
                            case 0:
                                return '<span style="color: red;">拒绝</span>';
                            case 1:
                                return '<span style="color: green;">同意</span>';
                            case 2:
                                return '<span style="color: orange;">采购撤销</span>';
                            case 3:
                                return '<span style="color: orange;">财务撤销</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'approveOpinion',
                    title: '审批意见',
                    width: 300
                },
                {
                    field: 'approveUserName',
                    title: '审批用户姓名',
                    width: 130
                },
                {
                    field: 'approveTime',
                    title: '审批时间',
                    width: 140,
                    sortable: true,
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format("YYYY-MM-DD HH:mm:ss");
                        }
                        return '';
                    }
                }
            ]
        ]
    });
}

/**
 * 初始化预付款明细表格
 */
function initTbAdvance(firstGridData) {
    var toolbar = [];
    if (optType===3){
        toolbar.push(
            {
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    addAdvanceItem();
                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    delAdvanceItem();
                }
            },
            '-',
            {
                text: '导出',
                iconCls: 'icon-download',
                handler: function () {
                    advanceExport();
                }
            }
        );
    }else {
        toolbar.push(
            {
                text: '导出',
                iconCls: 'icon-download',
                handler: function () {
                    advanceExport();
                }
            }
        )
    }

    var companyCode = $(el.companyCode).val(),invoiceApplyId = $(el.id).val(),
        supplierCode = $(el.supplierCode).textbox('getValue');
    //获取对账明细里的订单号和订单行号
    console.log(firstGridData);
    var poCodeItemNoList = firstGridData.map(item => item.poCode + "_" + item.poItemNo).join(',');
    var dataDiv = $(el.dataDiv).outerHeight() + 90, orderType = $(el.orderType).val();
    const params = {};
    var url = "";
    if(optType == 2 || optType == 4){
        params.invoiceApplyId = $(el.id).val();
        url = "pc/finance/paymentAdvance/apply/rest/find/paa/findPaaDetailByInvoiceApplyId";
    }else{
        params.supplierCode = supplierCode;
        params.companyCode = companyCode;
        params.poCodeItemNoList = poCodeItemNoList;
        url ="pc/finance/paymentAdvance/apply/detail/rest/provide/create/advance/apply";
    }



    // const initOrAdd = {
    //     supplierCode:supplierCode,
    //     companyCode:companyCode,
    //     poCodeItemNoList:poCodeItemNoList
    // };

    $(el.tbAdvance).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        // height: el.bodyHeight - dataDiv,
        height: 400,
        singleSelect: false,
        rownumbers: true,
        showFooter: true,
        pagination: true,
        queryParams: params,
        url: g.ctx + url,
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                }, {
                field: 'poId',
                title: '预付款id',
                width: 200,
                hidden: true
            },
                {
                    field: 'deleteFlag',
                    title: '数据状态',
                    width: 100,
                    formatter:function (value) {
                        if (Number(value)===1){
                            return '<span style="color: red;">已删除</span>';
                        }else {
                            return '<span style="color: green;">正常</span>';
                        }
                    }
                },
                {
                    field: 'poCode',
                    title: '采购订单',
                    width: 200,
                    sortable: true
                },
                {
                    field: 'poItemNo',
                    title: '订单行号',
                    width: 200,
                    sortable: true
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'applyPrice',
                    title: '预付款金额',
                    width: 200,
                    sortable: true,
                    formatter:function (value) {
                        return  formatterPrice(value);
                    }
                },
                {
                    field: 'reversalMoney',
                    title: '已冲账金额',
                    width: 200,
                    sortable: true,
                    formatter:function (value) {
                        return  formatterPrice(value);
                    }
                },
                {
                    field: 'refundedTaxAmount',
                    title: '已退款含税金额',
                    width: 200,
                    sortable: true,
                    formatter:function (value) {
                        return  formatterPrice(value);
                    }
                },
                {
                    field: 'surplusReversalMoney',
                    title: '剩余可冲账金额',
                    width: 200,
                    sortable: true,
                    formatter:function (value) {
                        return  formatterPrice(value);
                    }
                },
                {
                    field: 'strikePrice',
                    title: '本次冲账金额',
                    width: 200,
                    sortable: true,
                    formatter:function (value) {
                        return  formatterPrice(value);
                    },
                    editor: {
                        type: 'numberbox',
                        options: {
                            precision: priceHandle.precision,
                            onChange: function (nv, ov) {
                                console.log(nv)
                                console.log(ov)
                                if(nv){
                                    updateAdvanceRowData(nv, 'strikePrice');
                                }
                            }
                        }
                    }
                },
                // {
                //     field: 'yearNum',
                //     title: '年度',
                //     width:100
                // },
                {
                    field: 'currencyCode',
                    title: '币种',
                    width:100
                },
                {
                    field: 'applyNo',
                    title: '预付款凭证号',
                    width:140
                },
                {
                    field: 'applyItemNo',
                    title: '预付款凭证行号',
                    width:120
                },
                {
                    field: 'paymentChangeNumber',
                    title: '预付款变更单号',
                    width:120
                },
                {
                    field: 'paymentChangeItemNo',
                    title: '预付款变更单行',
                    width:120
                },
                {
                    field: 'remark',
                    title: '摘要',
                    width:200
                },

            ]
        ],
        toolbar: toolbar,
        // rowStyler: function (index, row) {
        //     if (!checkAdvanceOrderNoExit(row.zlsdh)) {
        //         return 'background-color:#f8d594;';
        //     }
        // },
        onClickRow: function (index, row) {
            if (el.editAdvanceIndex !== undefined) {
                if(endAdvanceEditor()){
                    beginAdvanceEditor(index, row);
                }
            }else {
                beginAdvanceEditor(index, row);
            }
        },
        onLoadSuccess: function () {
            // $(el.tbAdvance).datagrid('selectAll');
            calculationAdvancePageAmount();
        }
    });
}
function addAdvanceItem() {
    var companyCode = $(el.companyCode).val(),invoiceApplyId = $(el.id).val(),
        supplierCode = $(el.supplierCode).textbox('getValue');
    //获取对账明细里的订单号和订单行号
    var details = $(el.tbDetails).datagrid('getRows');
    //var poCodeItemNoList = [];
    // for (let i = 0 ; i < details.length ; i ++){
    //     poCodeItemNoList.push(details[i].poCode+"_"+details[i].poItemNo);
    // }
    var poCodeItemNoList = details.map(item => item.poCode + "_" + item.poItemNo).join(',');
    var url = g.ctx + 'pc/finance/invoiced/apply/chose/advance/detail/dialog?companyCode=' + companyCode +
        '&supplierCode=' + supplierCode + '&invoiceApplyId=' + invoiceApplyId +'&poCodeItemNoList='+poCodeItemNoList;
    el.addDetailDialog = openDialog('choseAdvanceDetail', url, {
        title: '选择预付款明细',
        width: '75%',
        height: '75%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.addDetailDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseAdvanceDetail'].confirmChose(function (data) {
                        let old_advance = $(el.tbAdvance).datagrid('getRows');
                        for(var n = 0; n < data.length; n++){
                            var item = data[n], row = {};
                            //去重
                            let sameFlag = false;
                            for (let j = 0; j < old_advance.length; j++) {
                            var dataType= item.dataType;
                            if(dataType === undefined){
                                console.log(dataType);
                            }else{
                                console.log("有值:"+dataType);
                            }


                                if (item.poCode === old_advance[j].poCode&&item.poItemNo === old_advance[j].poItemNo&&item.applyNo === old_advance[j].applyNo&&item.applyItemNo === old_advance[j].applyItemNo && item.dataType !== 0) {
                                    sameFlag = true;
                                    break;
                                }else if(item.dataType === 0 && item.paymentChangeNumber === old_advance[j].paymentChangeNumber && item.paymentChangeItemNo == old_advance[j].paymentChangeItemNo){//转单类型的数据使用预付款变更单行号+预付款变更单编号判断是否唯一
                                    sameFlag = true;
                                    break;
                                }
                            }
                            if (sameFlag) {
                                continue;
                            }
                            // row.oldPoCode = item.oldPoCode;
                            row.paId = item.paId;
                            row.poCode = item.poCode;
                            row.poItemNo = item.poItemNo;
                            row.applyPrice = item.applyPrice;
                            row.strikePrice = item.surplusReversalMoney;
                            row.budOutMoney = item.budOutMoney;
                            row.reversalMoney = item.reversalMoney;
                            row.surplusReversalMoney = item.surplusReversalMoney;
                            row.yearNum = item.yearNum;
                            row.currencyCode = item.currencyCode;
                            row.applyNo = item.applyNo;
                            row.applyItemNo = item.applyItemNo;
                            row.sysInvoiceNo = item.sysInvoiceNo;
                            row.remark = item.remark;
                            row.refundedTaxAmount=item.refundedTaxAmount;
                            row.paymentChangeNumber=item.paymentChangeNumber;
                            row.paymentChangeItemNo=item.paymentChangeItemNo;
                            // row.zlsdh = item.zlsdh;
                            // row.specialFlag = item.specialFlag;
                            $(el.tbAdvance).datagrid('appendRow', row);
                        }
                        el.addDetailDialog.dialog('close');
                        calculationAdvancePageAmount();
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.addDetailDialog.dialog('close');
                }
            }
        ]
    });
}
function delAdvanceItem() {
    var rows = $(el.tbAdvance).datagrid('getSelections');
    if(rows.length === 0){
        topWin.layer.alert('请选择您要删除的数据', {icon: 0});
        return false;
    }
    for(var i = 0; i < rows.length; i++){
        var item = rows[i];
        var rowIndex = $(el.tbAdvance).datagrid('getRowIndex', item);
        $(el.tbAdvance).datagrid('deleteRow', rowIndex);
    }
    //调用删除
    calculationAdvancePageAmount();
}
/**
 * 启动行编辑
 */
function beginAdvanceEditor(rowIndex, row) {

    $(el.tbAdvance).datagrid('beginEdit', rowIndex);
    el.editAdvanceIndex = rowIndex;
}
function updateAdvanceRowData(data, editColumn) {
    var row = {}, rows = $(el.tbAdvance).datagrid('getRows');
    for(var i = 0; i < rows.length; i++){
        var rowIndex = $(el.tbAdvance).datagrid('getRowIndex', rows[i]);
        if(rowIndex === el.editAdvanceIndex){
            row = rows[i];
            break;
        }
    }
    if('strikePrice' === editColumn){

        var strikePriceAmount= new BigNumber(0)
        for (var i = 0; i < rows.length; i++) {
            var item = rows[i];
            var rowIndex = $(el.tbAdvance).datagrid('getRowIndex', item);

            var strikePrice = item.strikePrice?Number(item.strikePrice):0;
            if(el.editAdvanceIndex === rowIndex){
                var strikePriceEditor = $(el.tbAdvance).datagrid('getEditor', {index: el.editAdvanceIndex, field: 'strikePrice'}).target;
                strikePrice = strikePriceEditor.numberbox('getValue');
            }
            strikePriceAmount = strikePriceAmount.plus(strikePrice);
        }
        $(el.strikePriceAmount).textbox('setValue', formatterPrice(strikePriceAmount));
        var invoiceTaxAmount = $(el.invoiceTaxAmount).textbox('getValue');
        var invoiceTaxTotalAmount = $(el.invoiceTaxTotalAmount).textbox('getValue');
        if ( $(el.currencyCode).textbox('getValue')==='CNY'){
            $(el.actualUnpaidAmount).textbox('setValue', formatterPrice(new BigNumber(invoiceTaxTotalAmount.replace(/,/g,'')).minus(strikePriceAmount)));
        }else {
            $(el.actualUnpaidAmount).textbox('setValue', formatterPrice(new BigNumber(invoiceTaxAmount.replace(/,/g,'')).minus(strikePriceAmount)));
        }
    }
}

function advanceExport() {
    var rows = $(el.tbAdvance).datagrid('getRows');
    $(el.tbAdvance).datagrid('toExcel', {
        filename: '开票申请数据-预付款.xls',
        rows: rows,
        worksheet: '开票申请明细-预付款'
    });
}
function  calculationAdvancePageAmount(){
    var advanceDetail = $(el.tbAdvance).datagrid('getRows');
    var allBudInnerMoney = new BigNumber(0);
    for (var i = 0; i < advanceDetail.length; i++) {
        var item2 = advanceDetail[i];
        allBudInnerMoney = allBudInnerMoney.plus(item2.strikePrice);
    }
    $(el.allBudInnerMoney).val(formatterPrice(allBudInnerMoney));
    $(el.strikePriceAmount).textbox('setValue', formatterPrice(allBudInnerMoney));

    var invoiceTaxAmount = $(el.invoiceTaxAmount).textbox('getValue');
    var invoiceTaxTotalAmount = $(el.invoiceTaxTotalAmount).textbox('getValue');
    // if(optType!==2){

    if ( $(el.currencyCode).textbox('getValue')==='CNY'){
        console.log(invoiceTaxTotalAmount)
        console.log(allBudInnerMoney)
        $(el.actualUnpaidAmount).textbox('setValue', formatterPrice(new BigNumber(invoiceTaxTotalAmount.replace(/,/g,'')).minus(new BigNumber(allBudInnerMoney))));
    }else {
        $(el.actualUnpaidAmount).textbox('setValue', formatterPrice(new BigNumber(invoiceTaxAmount.replace(/,/g,'')).minus(new BigNumber(allBudInnerMoney))));
    }

    // }

}
function loadtbStatementSignFileGrid(){
    $(el.tbStatementSignFile).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/sys/esign/rest/file/list?businessId=' + $(el.accountStatementId).val() +'&businessTypeCode=purchase_sale_contract,purchase_sale_process_contract&notShowDelete=1&signOrder=1,2',
        height: '100px',
        width: '98%',
        pagination: false,
        autoRowHeight: true,
        remoteSort:false,
        fitColumns: true,
        checkbox: true,
        rownumbers: false,
        queryParams: {},
        columns: [[
            {
                field: 'fileId',
                title: '签署文件',
                width: '40%',
                formatter: function (value, row, index) {
                    return '<div class="supplier-file-form custom-file-form-style" data-options=\'{"deleteEnable":false, "previewEnable":true, "uploadEnable": false, "moreFileUploadEnable": true, "fileSize": 50, "fileTypes": ".xls,.doc,.txt,.pdf"}\' data-fileIds = "'+value+'"></div>';
                }
            }, {
                field: 'signStatus',
                title: '状态',
                width: '20%',
                formatter: function (value) {
                    switch (value) {
                        case 0:
                            return '<span style="color: grey;">草稿</span>';
                        case 1:
                            return '<span style="color: blue;">签署中</span>';
                        case 2:
                            return '<span style="color: green;">完成</span>';
                        case 3:
                            return '<span style="color: orange;">已过期</span>';
                        case 4:
                            return '<span style="color: red;">已拒签</span>';
                        case 5:
                            return '<span style="color: dimgrey;">已作废</span>';
                        case 6:
                            return '<span style="color: blue;">作废中</span>';
                        case 7:
                            return '<span style="color: red;">已删除</span>';
                        default:
                            return '';
                    }
                }
            },
            {
                field: 'signOrder',
                title: '签章顺序',
                width: '20%',
                formatter: function (value) {
                    return getDicName('sign_order',value)
                }

            },
            {
                field: 'signatureType',
                title: '签章类别',
                width: '20%',
                formatter: function (value) {
                    return getDicName('sign_type',value)
                }

            },
        ]],
        onLoadSuccess: function (data) {
            if (data.rows.length>0){
                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: 'sysCheck',
                title: "系统检查",
                sortable: true,
                width: 200,
                formatter: function (value, row, index) {
                    console.log( row)
                    if (!isBlank(row.id)&&Number(row.businessType)===0){
                        return Number(row.sysCheck)===1?'<span style="color:green;">齐全</span>':'<span style="color:red;">缺失</span>';
                    }
                    var html = '<span style="color:red;">缺失</span>';
                    //判断对账单是否有附件
                    if (row.type==='account'){
                        html = el.tbSignFileRowsExt?'<span style="color:green;">齐全</span>':'<span style="color:red;">缺失</span>';
                    }
                    //判断海关缴款书是否有附件
                    if (row.type==='customs_payment_voucher'){
                        html = el.tbInvoicePaymentCertificateFileRowsExt?'<span style="color:green;">齐全</span>':'<span style="color:red;">缺失</span>';
                    }
                    //判断发票是否有附件
                    if (row.type==='invoice'){
                        html = el.tbInvoiceFileRowsExt?'<span style="color:green;">齐全</span>':'<span style="color:red;">缺失</span>';
                    }
                    return html;
                }
            },
            {
                field: 'manualCheck',
                title: "人工检查",
                sortable: true,
                width: 200,
                formatter: function (value) {
                    if (isBlank(value)) {
                        return '';
                    }
                    if (Number(value)===1) {
                        return '<span style="color:green;">齐全</span>';
                    }else {
                        return '<span style="color:red;">缺失</span>';
                    }
                },
                editor: {
                    type: 'combobox',
                    options: {
                        data: [
                            {'name': '缺失', 'code': '0'},
                            {'name': '齐全', 'code': '1'}
                        ],
                        valueField: 'code',
                        textField: 'name',
                        editable: false,
                        required:false,
                        limitToList: 'true',
                        panelHeight: 'auto',
                    }
                }
            },
            {
                field: 'remark',
                title: "备注",
                sortable: true,
                width: 200,
                editor: {
                    type: 'textbox'
                }
            }
        ]],
        toolbar: toolbar,
        rowStyler: function (index, row) {
            if (row.id&&Number(row.businessType)===0) {
                return 'background-color:#FAC80026;';
            }
        },
        onClickRow: function (index, row) {
            if (row.id&&Number(row.businessType)===0) {
                return false;
            }
            if (el.editManualIndex !== index) {
                if (endManualEditing()) {
                    el.editManualIndex = index;
                    $(el.tbAttachmentManualCheck).datagrid('selectRow', index).datagrid('beginEdit', index);
                    el.editManualIndex = index;
                } else {
                    el.editManualIndex = index;
                    $(el.tbAttachmentManualCheck).datagrid('selectRow', el.editManualIndex);
                }
            } else {
                $(el.tbAttachmentManualCheck).datagrid('selectRow', index).datagrid('beginEdit', index);
                el.editManualIndex = index;

            }
        },
        onLoadSuccess: function (data) {
            for (let ii = 0; ii < data.rows.length; ii++) {
                var sysCheck = 0;
                //判断对账单是否有附件
                if (data.rows[ii].type==='account'){
                    sysCheck = el.tbSignFileRowsExt?1:0;
                }
                //判断购销合同是否有附件
                if (data.rows[ii].type==='customs_payment_voucher'){
                    sysCheck = el.tbInvoicePaymentCertificateFileRowsExt?1:0;
                }
                //判断发票是否有附件
                if (data.rows[ii].type==='invoice'){
                    sysCheck = el.tbInvoiceFileRowsExt?1:0;
                }
                if (Number(data.rows[ii].businessType)===1){
                    $(el.tbAttachmentManualCheck).datagrid('updateRow', {
                        index: ii,
                        row: {
                            sysCheck: sysCheck
                        }
                    });
                }
                // 采购确认节点之前（因为在这之前都没有存表），系统检查齐全时，人工检查默认齐全
                if (isBlank(data.rows[ii].id) && sysCheck===1){
                    $(el.tbAttachmentManualCheck).datagrid('updateRow', {
                        index: ii,
                        row: {
                            manualCheck: sysCheck
                        }
                    });
                }
            }
        }
    });
}

function endManualEditing() {
    if (el.editManualIndex === undefined) {
        return true
    }
    if ($(el.tbAttachmentManualCheck).datagrid('validateRow', el.editManualIndex)) {
        $(el.tbAttachmentManualCheck).datagrid('endEdit', el.editManualIndex);
        el.editManualIndex = undefined;
        return true;
    } else {
        return false;
    }
}

function loadSignFileGrid(){
    $(el.tbSignFile).datagrid({
        loadMsg: '数据加载中......',
        url: g.ctx + 'pc/sys/esign/rest/file/list?businessId=' + $(el.accountStatementId).val() +'&businessTypeCode=cost_account_statement,cost_purchase_sale_contract,cost_purchase_sale_process_contract&notShowDelete=1&signOrder=1,2',
        height: '460px',
        width: '98%',
        pagination: false,
        autoRowHeight: true,
        remoteSort:false,
        fitColumns: true,
        checkbox: true,
        rownumbers: false,
        queryParams: {},
        columns: [[
            {
                field: 'fileId',
                title: '签署文件',
                width: '40%',
                formatter: function (value, row, index) {
                    return '<div class="supplier-file-form custom-file-form-style" data-options=\'{"deleteEnable":false, "previewEnable":true, "uploadEnable": false, "moreFileUploadEnable": true, "fileSize": 50, "fileTypes": ".xls,.doc,.txt,.pdf"}\' data-fileIds = "'+value+'"></div>';
                }
            }, {
                field: 'signStatus',
                title: '状态',
                width: '20%',
                formatter: function (value) {
                    switch (value) {
                        case 0:
                            return '<span style="color: grey;">草稿</span>';
                        case 1:
                            return '<span style="color: blue;">签署中</span>';
                        case 2:
                            return '<span style="color: green;">完成</span>';
                        case 3:
                            return '<span style="color: orange;">已过期</span>';
                        case 4:
                            return '<span style="color: red;">已拒签</span>';
                        case 5:
                            return '<span style="color: dimgrey;">已作废</span>';
                        case 6:
                            return '<span style="color: blue;">作废中</span>';
                        case 7:
                            return '<span style="color: red;">已删除</span>';
                        default:
                            return '';
                    }
                }
            },
            {
                field: 'signOrder',
                title: '签章顺序',
                width: '20%',
                formatter: function (value) {
                    return getDicName('sign_order',value)
                }

            },
            {
                field: 'signatureType',
                title: '签章类别',
                width: '20%',
                formatter: function (value) {
                    return getDicName('sign_type',value)
                }

            },
        ]],
        onLoadSuccess: function (data) {
            if (data.rows.length>0){
                initFileForm('supplier-file-form');
                el.tbSignFileRowsExt = true;
            }

        },
    });
}

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

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

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

                    var obj = {
                        "purchaseOrderNo": item,
                        "purchaseOrderFile": purchase_order_exist?1:0,
                        "satisfyFlag": (!purchase_order_exist)?0:1
                    }
                    checkRows.push(obj);
                });
                $(el.tbAttachmentCheck).datagrid('loadData', {total: checkRows.length, rows: checkRows});
            }
        },
    });
}


function detailRelationFileExport() {

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

function initTbAttachmentCheck(){
    let toolbar = [];
    $(el.tbAttachmentCheck).datagrid({
        loadMsg: '数据加载中......',
        height: '460px',
        width: '98%',
        pagination: true,
        autoRowHeight: true,
        remoteSort:false,
        fitColumns: true,
        checkbox: true,
        rownumbers: false,
        singleSelect: true,
        columns: [[
            {
                field: 'purchaseOrderNo', title: "采购订单号", width: 200
            },
            {
                field: 'purchaseOrderFile', title: "采购订单附件", width: 200,
                formatter: function (value) {
                    if (value===1) {
                        return '<span style="color:green;">存在</span>';
                    }
                    return '<span style="color:red;">不存在</span>';
                }
            },
            {
                field: 'satisfyFlag', title: "是否满足", width: 200,
                formatter: function (value) {
                    if (value===1) {
                        return '<span style="color:green;">满足</span>';
                    }
                    return '<span style="color:red;">不满足</span>';
                }
            }
        ]],
        toolbar: toolbar,
    });
}
function loadSignFileGrid1(){
    let toolbar = [];
    if (optType !== 2) {
        toolbar = [
            {
                text: BJGL.BJGL__SC, iconCls: 'icon-add', hidden: true, handler: uploadAttachmentFile
            }, "-", {
                text: BJGL.BJGL__SHANC, iconCls: 'icon-remove', handler: deleteAttachmentFile
            }, "-", {
                text: "设置备注", iconCls: 'icon-remove', handler: remarkAttachmentFile
            }
        ];
        // 暂存后可编辑状态，允许操作影像
        if (optType === 1 || optType === 3 || optType === 4) {
            const imageButtons = [
                "-", {
                    text: "推送影像", iconCls: 'icon-add', handler: pushAllImageButtonEvent
                }, "-", {
                    text: "删除影像（整单）", iconCls: 'icon-remove', handler: deleteAllImageButtonEvent
                }, "-", {
                    text: "查看影像附件", iconCls: 'icon-find', handler: viewImageButtonEvent
                }
            ]
            toolbar = [...toolbar, ...imageButtons];
        }
    } else {
        toolbar = [
            {
                text: "查看影像附件", iconCls: 'icon-find', handler: viewImageButtonEvent
            }
        ];
    }
    let businessId;
    if (optType === 0 || optType === 5) {
        businessId = $(el.accountStatementId).val();
    } else {
        businessId = $(el.id).val();
    }
    const url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentList?businessId=' + businessId;
    $(el.tbSignFile).datagrid({
        loadMsg: '数据加载中......',
        url: url,
        height: '460px',
        width: '98%',
        pagination: true,
        autoRowHeight: true,
        remoteSort:false,
        fitColumns: true,
        checkbox: true,
        rownumbers: false,
        singleSelect: true,
        queryParams: {},
        columns: [[
            {
                field: 'ck', checkbox: true
            }, {
                field: 'type', title: "附件类型", width: '10%', formatter: function (value) {
                    return getNameByCode(businessFileTypeNecessaryData, value);
                }
            }, {
                field: 'imageCode', title: "影像编码", width: '10%'
            }, {
                field: 'businessCode', title: "单据编号", width: '10%'
            }, {
                field: 'fileId',
                title: '附件名称',
                width: '20%',
                formatter: function (value, row, index) {
                    return '<div class="supplier-file-form custom-file-form-style" data-options=\'{"deleteEnable":false, "previewEnable":true, "uploadEnable": false, "moreFileUploadEnable": true, "fileSize": 50, "fileTypes": ".xls,.doc,.txt,.pdf"}\' data-fileIds = "'+value+'"></div>';
                }
            }, {
                field: 'signStatus',
                title: '签章状态',
                width: '5%',
                formatter: function (value) {
                    switch (value) {
                        case 0:
                            return '<span style="color: grey;">草稿</span>';
                        case 1:
                            return '<span style="color: blue;">签署中</span>';
                        case 2:
                            return '<span style="color: green;">完成</span>';
                        case 3:
                            return '<span style="color: orange;">已过期</span>';
                        case 4:
                            return '<span style="color: red;">已拒签</span>';
                        case 5:
                            return '<span style="color: dimgrey;">已作废</span>';
                        case 6:
                            return '<span style="color: blue;">作废中</span>';
                        case 7:
                            return '<span style="color: red;">已删除</span>';
                        default:
                            return '';
                    }
                }
            },
            {
                field: 'signOrder',
                title: '签章顺序',
                width: '5%',
                formatter: function (value) {
                    return getDicName('sign_order',value)
                }

            },
            {
                field: 'signatureType',
                title: '签章类别',
                width: '5%',
                formatter: function (value) {
                    return getDicName('sign_type',value)
                }

            }, {
                field: 'remark', title: "备注", width: '10%'
            }, {
                field: 'deleteFlag', title: "删除标记", formatter: function (value) {
                    if (value === 1) {
                        return "<span style='color: red;'>已删除</span>"
                    }
                    return "未删除"
                }
            }, {
                field: 'createTime', title: "上传时间"
            }, {
                field: 'updateUser', title: "最近修改人"
            }, {
                field: 'updateTime', title: "最近修改时间"
            }
        ]],
        toolbar: toolbar,
        onLoadSuccess: function (data) {
            if (data.rows.length>0){
                initFileForm('supplier-file-form');
            }

        },
    });
}

/**
 * 获取对账单明细数据
 */
function findStatementDetail() {
    // var  factoryCode = $(el.factoryCode).combobox('getValue'),
    var accountStatementId = $(el.accountStatementId).val();

    var queryParams = $(el.tbDetails).datagrid('options').queryParams;
    // queryParams.factoryCode = factoryCode;
    queryParams.asId = accountStatementId;
    // $(el.tbDetails).datagrid('options').url = g.ctx + 'pc/finance/account/statement/detail/rest/provide/create/invoiced/apply/asId';
    $(el.tbDetails).datagrid('options').url = g.ctx + 'pc/finance/cost/account/statement/detail/rest/find/by/statement/id';
    $(el.tbDetails).datagrid('load');

    //获取扣款明细数据
    // findDeductionDetail(supplierCode,companyCode);

}

function findAdvanceDetail() {
    if ($(el.tbAdvance).length>0){
        if (!$(el.tbAdvance).data('datagrid')) {
            console.log('datagrid is not initialized.');
            return;
        }
        var poCodeItemNoList ="";
        $(el.tbAdvance).datagrid('options').url = g.ctx + 'pc/finance/paymentAdvance/apply/detail/rest/provide/create/advance/apply?supplierCode='+ $(el.supplierCode).textbox('getValue')+'&companyCode='+$(el.companyCode).combobox( 'getValue')+'&poCodeItemNoList='+poCodeItemNoList;
        $(el.tbAdvance).datagrid('load');
    }

}

function findSignFileDetail() {
    $(el.tbSignFile).datagrid('options').url = g.ctx + 'pc/sys/esign/rest/file/list?businessId='+ $(el.accountStatementId).val()+'&businessTypeCode=cost_account_statement&notShowDelete=1&signOrder=1,2';
    $(el.tbSignFile).datagrid('load');
    initFileForm('supplier-file-form');

}

function findtbStatementSignFileDetail() {
    $(el.tbStatementSignFile).datagrid('options').url = g.ctx + 'pc/sys/esign/rest/file/list?businessId='+ $(el.accountStatementId).val()+'&businessTypeCode=cost_purchase_sale_contract,cost_purchase_sale_process_contract&notShowDelete=1&signOrder=1,2';
    $(el.tbStatementSignFile).datagrid('load');
    initFileForm('supplier-file-form');
}


/**
 * 选择对账单
 */
function choseAccountStatement() {
    var url = g.ctx + "pc/finance/cost/account/statement/chose/statement/dialog?single=1";
    el.choseAccountStatement = openDialog('choseAccountStatement', url, {
        title: '对账单选择',
        width: '80%',
        height: '70%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.choseAccountStatement.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseAccountStatement'].confirmChose(function (data) {
                        console.log(data)
                        //取选中后的对账单的年与月 2025-06-25 邓京术
                        $(el.accountStatementYear).val(data.accountStatementYear);
                        $(el.accountStatementMonth).val(data.accountStatementMonth);
                        //新增逻辑
                        if(optType == 0 ||  optType == 5) {
                            //新增时获取对账单号到资料开票表里去进行校验
                            var accountStatementNo = data.accountStatementNo;
                            $.ajax({
                                url: g.ctx + 'pc/finance/cost/invoiced/apply/rest/statementInvoicing/check',
                                type: 'POST',
                                async: false,
                                data: {accountStatementNo:accountStatementNo},
                                dataType: 'json',
                                success: function (data) {
                                    console.log(data)
                                    const isTrue = data === true || data === "true";
                                    if(isTrue){
                                        topWin.layer.alert("该对账单："+accountStatementNo+"，存在已开票信息，请检查！", {icon: 2});
                                        return false;
                                    }
                                },
                                error: function (data) {
                                    topWin.layer.alert(data.responseJSON.message, {icon: 2});
                                }
                            });
                        }
                        //新增逻辑，编辑都需要校验，该供应商对账月份是否有未确认的订单及未签署的订单，否则报错 邓京术 2025-06-05
                        // var paperlessFlag1 = $(el.paperlessFlag).combobox('getValue');
                        // if((optType == 0 ||  optType == 1 ||  optType == 5) &&　paperlessFlag1　&&　Number(paperlessFlag1)===1) {
                        //     //新增时获取对账单号到资料开票表里去进行校验
                        //     var accountStatementNo = data.accountStatementNo;
                        //     var accountStatementId = data.id;
                        //     var year = data.accountStatementYear;
                        //     var month = data.accountStatementMonth;
                        //     var supCode = data.supplierCode;
                        //     $.ajax({
                        //         url: g.ctx + 'pc/finance/invoiced/apply/rest/statementInvoicing/checkHasNGSignOk',
                        //         type: 'POST',
                        //         async: false,
                        //         data: {accountStatementId:accountStatementId,year:year,month:month, supplierCode:supCode},
                        //         dataType: 'json',
                        //         success: function (flag) {
                        //             var oriSupCode = $(el.supplierCode).val();
                        //             $(el.supplierCode).val(data.supplierCode);
                        //             $(el.accountStatementId).val(data.id);
                        //             $(el.accountStatementNo).textbox('setValue',data.accountStatementNo);
                        //             $(el.supplierName).textbox('setValue',data.supplierName);
                        //             $(el.companyCode).combobox( 'setValue', data.companyCode);
                        //             $(el.factoryCode).combobox( 'setValue', data.factoryCode);
                        //             $(el.currencyCode).textbox('setValue',data.currencyCode);
                        //             $(el.purchaseGroup).combobox('setValue',data.purchaseGroup);
                        //             $(el.paymentWay).combobox('setValue',data.paymentWay);
                        //             $(el.invoiceTaxAmount).textbox('setValue',new BigNumber(data.taxAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
                        //             $(el.invoiceNetAmount).textbox('setValue',new BigNumber(data.notTaxAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
                        //             $(el.diffAmount).textbox('setValue',new BigNumber(data.taxAmount).minus(new BigNumber(data.notTaxAmount)).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
                        //             $(el.poType).combobox('setValue',data.poType);
                        //             $(el.taxCode).combobox('setValue', data.taxCode);
                        //             el.supplierTaxRate = data.taxCode
                        //             el.supplierCurrencyCode = data.currencyCode
                        //             $('.account-file-form').attr('data-fileIds',data.files)
                        //             initFileForm('account-file-form')
                        //             // $(el.inStockStartDate).datebox('setValue', moment(data.inStockStartDate).format('YYYY-MM-DD'));
                        //             // $(el.inStockEndDate).datebox('setValue', moment(data.inStockEndDate).format('YYYY-MM-DD'));
                        //             el.choseAccountStatement.dialog('close');
                        //
                        //             findStatementDetail();
                        //             findAdvanceDetail();
                        //             findSignFileDetail();
                        //             findtbStatementSignFileDetail();
                        //         },
                        //         error: function (redata) {
                        //             topWin.layer.alert(redata.responseJSON.message, {icon: 2});
                        //             return;
                        //         }
                        //     });
                        // } else {
                        $(el.supplierCode).textbox('setValue',data.supplierCode);
                        $(el.accountStatementId).val(data.id);
                        $(el.accountStatementNo).textbox('setValue',data.accountStatementNo);
                        $(el.supplierName).textbox('setValue',data.supplierName);
                        $(el.companyCode).combobox( 'setValue', data.companyCode);
                        $(el.factoryCode).combobox( 'setValue', data.factoryCode);
                        $(el.currencyCode).textbox('setValue',data.currencyCode);
                        $(el.purchaseGroup).combobox('setValue',data.purchaseGroup);
                        $(el.paymentWay).combobox('setValue',data.paymentWay);
                        $(el.taxAmount).textbox('setValue',new BigNumber(data.taxAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
                        $(el.tariffTotalAmount).textbox('setValue',new BigNumber(data.tariffTotalAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
                        $(el.valueAddedTaxTotalAmount).textbox('setValue',new BigNumber(data.valueAddedTaxTotalAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
                        $(el.freightAndMiscellaneousFeeIncludingTaxTotal).textbox('setValue',new BigNumber(data.freightAndMiscellaneousFeeIncludingTaxTotal).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
                        $(el.domesticTaxTotalAmount).textbox('setValue',new BigNumber(data.domesticTaxTotalAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
                        // $(el.invoiceNetAmount).textbox('setValue',new BigNumber(data.notTaxAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
                        // $(el.diffAmount).textbox('setValue',new BigNumber(data.taxAmount).minus(new BigNumber(data.notTaxAmount)).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
                        // $(el.taxCode).combobox('setValue', data.taxCode);
                        el.supplierTaxRate = data.taxCode
                        el.supplierCurrencyCode = data.currencyCode
                        $('.account-file-form').attr('data-fileIds',data.files)
                        initFileForm('account-file-form')
                        // $(el.inStockStartDate).datebox('setValue', moment(data.inStockStartDate).format('YYYY-MM-DD'));
                        // $(el.inStockEndDate).datebox('setValue', moment(data.inStockEndDate).format('YYYY-MM-DD'));
                        el.choseAccountStatement.dialog('close');

                        findStatementDetail();
                        // findAdvanceDetail();
                        findSignFileDetail();
                        // findtbStatementSignFileDetail();

                        // 获取供应商、公司税号
                        initTaxNo(data.supplierCode, data.companyCode);
                        // }

                        // if(oriSupCode !== data.supplierCode){
                        //     $(el.tbDetails).datagrid('loadData', {total: 0, rows: []});
                        // }
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.choseAccountStatement.dialog('close');
                }
            }
        ]
    });
}


/**
 * 数据保存
 *
 * @param callback 回调函数
 */
function dataSave(callback) {
    if (Number(foreignCurrencyAddFlag)===0){
        endInvoiceEditor();
    endInvoicePaymentCertificateEditor();
    }
    // addOrDelInvoice();
    var orderType = $(el.orderType).val(), supplierCode = $(el.supplierCode).textbox('getValue'),
        supplierName = $(el.supplierName).textbox('getValue'), currencyCode = $(el.currencyCode).val(),
        companyCode = $(el.companyCode).combobox('getValue'), companyName = $(el.companyName).val(),
        // factoryName = $(el.factoryName).val(),
        // factoryCode = $(el.factoryCode).combobox('getValue'),
        purchaseGroup = $(el.purchaseGroup).combobox('getValue'),
        paperlessFlag = $(el.paperlessFlag).combobox('getValue'),
        paymentWay = $(el.paymentWay).combobox('getValue'),
        // invoiceNetAmount = $(el.invoiceNetAmount).textbox('getValue'),
        // paymentCertificateTotalInclTax = $(el.paymentCertificateTotalInclTax).textbox('getValue'),
        // paymentCertificateTotalExclTax = $(el.paymentCertificateTotalExclTax).textbox('getValue'),
        paymentCertificateTaxAmount = $(el.paymentCertificateTaxAmount).textbox('getValue'),
        invoiceTotalDiffAmount = $(el.invoiceTotalDiffAmount).textbox('getValue'),
        // invoiceTaxAmount = $(el.invoiceTaxAmount).textbox('getValue'),
        // diffAmount1 = $(el.diffAmount1).textbox('getValue'),
        diffAmountSap = $(el.diffAmountSap).textbox('getValue'),
        diffTaxAmountSap = $(el.diffTaxAmountSap).textbox('getValue'),
        taxAmount = $(el.taxAmount).textbox('getValue'),
        domesticTaxTotalAmount = $(el.domesticTaxTotalAmount).textbox('getValue'),
        files = $(el.files).attr('data-fileIds'),
    // allBudInnerMoney = $(el.allBudInnerMoney).textbox('getValue'),
    invoiceTaxTotalAmount = $(el.invoiceTaxTotalAmount).textbox('getValue'),
        invoiceTotalAmount = $(el.invoiceTotalAmount).textbox('getValue'),
        deductionAmount = "", rebateAmount = "",
        // taxCode = $('#taxCode').combobox('getValue'),
        invoiceNum = $(el.invoiceNum).numberbox('getValue'), invoiceNo = $(el.invoiceNo).textbox('getValue'),
        remark = $(el.remark).textbox('getValue'), dntAmount = $(el.dntAmount).val(), rntAmount = $(el.rntAmount).val();

    if (!currencyCode) {
        topWin.layer.alert('请选择币种', {icon: 0});
        return false;
    }
    if (!companyCode) {
        topWin.layer.alert('请选择采购公司', {icon: 0});
        return false;
    }
    // if (!taxCode) {
    //     topWin.layer.alert('请选择税率', {icon: 0});
    //     return false;
    // }
    if (!paymentWay) {
        topWin.layer.alert('请选择付款方式', {icon: 0});
        return false;
    }


    if (!purchaseGroup) {
        topWin.layer.alert('请选择采购组', {icon: 0});
        return false;
    }
    if (!paperlessFlag) {
        topWin.layer.alert('请选择是否无纸化', {icon: 0});
        return false;
    }
    var tbStatementSignFileSum = $(el.tbSignFile).datagrid('getRows');
    //创建开票申请，付款方式为承兑的时候，必须上传附件
    if ((paymentWay==='C'&&Number(paperlessFlag)===1&&!files) && tbStatementSignFileSum.length === 0) {
        topWin.layer.alert('付款方式为承兑，请上传购销合同/其他附件', {icon: 0});
        return false;
    }

    // if(!invoiceNum){
    //     topWin.layer.alert('请填写发票张数', {icon: 0});
    //     return false;
    // }
    // if(!invoiceNo){
    //     topWin.layer.alert('请填写发票号', {icon: 0});
    //     return false;
    // }
    // // 发票号填写的字符串长度不能超过30位字符
    // if(invoiceNo.length > 30){
    //     topWin.layer.alert('发票号填写的字符串长度不能超过30位字符', {icon: 0});
    //     return false;
    // }
    //人民币资料交接特殊判断
    if(optType == 0 || Number(foreignCurrencyAddFlag)===0){
        var diffAmountSapValue = Math.abs(diffAmountSap);//金额差
        var diffTaxAmountSapValue = Math.abs(diffTaxAmountSap);//税额差
        if ((diffAmountSapValue > 0.5) || (diffTaxAmountSapValue > 0.5) ) {
            topWin.layer.alert('金额差/税额差不能超过±0.5', {icon: 0});
            return false;
        }
    }
    // 对账单明细
    var detail = $(el.tbDetails).datagrid('getRows'), statementItem = [], leshuiItem = []
        ,taxData = [],paymentTermCode =  [],is101Flag = false;


    var invoicedPaymentCertificate = $(el.tbInvoicePaymentCertificate).datagrid('getRows');
    if (Number(foreignCurrencyAddFlag)===0) {
        if (currencyCode!=='CNY') {
            topWin.layer.alert('币种不是人民币，无法保存', {icon: 0});
            return false;
        }
        var invoicedReceipt = $(el.tbInvoice).datagrid('getRows');
    }else {
        if (currencyCode==='CNY') {
            topWin.layer.alert('币种不是外币，无法保存', {icon: 0});
            return false;
        }
    }
    if (detail.length === 0) {
        topWin.layer.alert('请先获取明细', {icon: 0});
        return false;
    }
    // SAP发票明细行不得超过999行
    // if(detail.length > 900){
    //     topWin.layer.alert('由于系统原因, 开票申请明细不得超过900行', {icon: 0});
    //     return false;
    // }
    if (Number(foreignCurrencyAddFlag)===0&&invoicedReceipt.length === 0) {
        topWin.layer.alert('请添加关联发票信息', {icon: 0});
        return false;
    }
    if (invoicedPaymentCertificate.length === 0) {
        topWin.layer.alert('请添加海关缴款书信息', {icon: 0});
        return false;
    }
    if (Number(foreignCurrencyAddFlag)===0) {
        for (let i = 0 ; i < invoicedReceipt.length ; i ++){
            if(!invoicedReceipt[i].deductionCodeType){
                layer.msg("关联发票信息：第"+ ++i+"行可抵扣编号不能为空");
                return false;
            }
            if(!invoicedReceipt[i].invoiceDate){
                layer.msg("关联发票信息：第"+ ++i+"行发票日期不能为空");
                return false;
            }
            var flag1 = false;
            var flag2 = false;
            var flag3 = false;
            var flag4 = true;
            if(invoicedReceipt[i].invoiceNumber){
                flag1 = true;
            }
            if(invoicedReceipt[i].invoiceCode){
                flag2 = true;
            }
            if(invoicedReceipt[i].electronInvoiceNumber){
                flag3 = true;
            }

            if (!flag1 || !flag2) {
                flag4 = false
            }

            if (!flag3 && !flag1 && !flag2) {
                layer.msg("关联发票信息：第" + ++i + "行发票代码(发票号码)和数电发票号码请填写其中一项");
                return false;
            }

            if (flag3) {
                if(flag1 || flag2) {
                    layer.msg("关联发票信息：第" + ++i + "行发票代码(发票号码)和数电发票号码只能填写其中一项");
                    return false;
                }
            } else if (!flag3) {
                if(!flag1 || !flag2) {
                    layer.msg("关联发票信息：第"+ ++i+"行发票代码和发票号码必须全部填写");
                    return false;
                }
            }

            if(flag3 && !invoicedReceipt[i].fileId){
                layer.msg("关联发票信息：第"+ ++i+"行发票附件不能为空");
                return false;
            }





            // if(!invoicedReceipt[i].invoiceNumber&&!invoicedReceipt[i].electronInvoiceNumber){
            //     layer.msg("关联发票信息：第"+ ++i+"行发票号码和数电发票号码请填写其中一项");
            //     return false;
            // }
            // if(invoicedReceipt[i].invoiceNumber&&invoicedReceipt[i].electronInvoiceNumber){
            //     layer.msg("关联发票信息：第"+ ++i+"行发票号码和数电发票号码只允许填写其中一项");
            //     return false;
            // }
            //
            // if(!invoicedReceipt[i].invoiceCode&&!invoicedReceipt[i].electronInvoiceNumber){
            //     layer.msg("关联发票信息：第"+ ++i+"行发票代码不能为空");
            //     return false;
            // }


            // if(!invoicedReceipt[i].invoiceNumber&&!invoicedReceipt[i].electronInvoiceNumber){
            //     layer.msg("关联发票信息：第"+ ++i+"行发票号码不能为空");
            //     return false;
            // }
            // if(!invoicedReceipt[i].invoiceCode){
            //     layer.msg("关联发票信息：第"+ ++i+"行发票代码不能为空");
            //     return false;
            // }
            // if(!invoicedReceipt[i].invoiceNumber){
            //     layer.msg("关联发票信息：第"+ ++i+"行发票号码不能为空");
            //     return false;
            // }
            // if(!invoicedReceipt[i].electronInvoiceNumber){
            //     layer.msg("关联发票信息：第"+ ++i+"行数电发票号码不能为空");
            //     return false;
            // }
            // if(!invoicedReceipt[i].dutyParagraph){
            //     layer.msg("关联发票信息：第"+ ++i+"行税号不能为空");
            //     return false;
            // }
            if(!invoicedReceipt[i].taxRate){
                layer.msg("关联发票信息：第"+ ++i+"行税率不能为空");
                return false;
            }
            if(!invoicedReceipt[i].currencyCode){
                layer.msg("关联发票信息：第"+ ++i+"行币种不能为空");
                return false;
            }
            if(!invoicedReceipt[i].taxAmount&&invoicedReceipt[i].taxAmount!==0){
                layer.msg("关联发票信息：第"+ ++i+"行含税金额不能为空");
                return false;
            }
            if(!invoicedReceipt[i].noTaxAmount&&invoicedReceipt[i].noTaxAmount!==0){
                layer.msg("关联发票信息：第"+ ++i+"行未税金额不能为空");
                return false;
            }

            if(!invoicedReceipt[i].diffTaxMoney&&invoicedReceipt[i].diffTaxMoney!==0){
                layer.msg("关联发票信息：第"+ ++i+"行税额不能为空");
                return false;
            }

            var taxAmountTemp = Number(invoicedReceipt[i].taxAmount);
            var totalTax = Number(invoicedReceipt[i].noTaxAmount).add(Number(invoicedReceipt[i].diffTaxMoney));
            //暂存时校验关联发票填的金额是否正确，需满足公司：含税金额 = 未税金额 + 税额，否则，报错“发票含税金额不等于未税金额+税额” 邓京术 2024-08-26
            if(taxAmountTemp!== totalTax) {
                layer.msg("关联发票信息：第"+ ++i+"行发票含税金额为："+taxAmountTemp+", 不等于(未税金额+税额):"+ totalTax);
                return false;
            }

            //如果数电发票号码有值，发票附件必传
            // if(invoicedReceipt[i].electronInvoiceNumber&&!invoicedReceipt[i].fileId){
            //     layer.msg("关联发票信息：第"+ ++i+"行发票附件不能为空");
            //     return false;
            // }
            //2024-08-22注释
            // if(!invoicedReceipt[i].fileId){
            //     layer.msg("关联发票信息：第"+ ++i+"行发票附件不能为空");
            //     return false;
            // }
        }
        }
    for (let i = 0 ; i < invoicedPaymentCertificate.length ; i ++){
        if(!invoicedPaymentCertificate[i].deductionCodeType){
            layer.msg("海关缴款书信息：第"+ ++i+"行可抵扣编号不能为空");
            return false;
        }
        if(!invoicedPaymentCertificate[i].invoiceDate){
            layer.msg("海关缴款书信息：第"+ ++i+"行缴款书日期不能为空");
            return false;
        }
        var flag1 = false;
        var flag2 = false;
        var flag3 = false;
        var flag4 = true;
        if(invoicedPaymentCertificate[i].invoiceNumber){
            flag1 = true;
        }
        if(invoicedPaymentCertificate[i].invoiceCode){
            flag2 = true;
        }
        // if(invoicedPaymentCertificate[i].electronInvoiceNumber){
        //     flag3 = true;
        // }

        if (!flag1 || !flag2) {
            flag4 = false
        }

        // if (!flag3 && !flag1 && !flag2) {
        //     layer.msg("海关缴款书信息：第" + ++i + "行缴款书代码(缴款书号码)和数电发票号码请填写其中一项");
        //     return false;
        // }
        //
        // if (flag3) {
        //     if(flag1 || flag2) {
        //         layer.msg("海关缴款书信息：第" + ++i + "行缴款书代码(缴款书号码)和数电发票号码只能填写其中一项");
        //         return false;
        //     }
        // } else if (!flag3) {
        //     if(!flag1 || !flag2) {
        //         layer.msg("海关缴款书信息：第"+ ++i+"行缴款书代码和缴款书号码必须全部填写");
        //         return false;
        //     }
        // }

        if(flag3 && !invoicedPaymentCertificate[i].fileId){
            layer.msg("海关缴款书信息：第"+ ++i+"行发票附件不能为空");
            return false;
        }
        if(!invoicedPaymentCertificate[i].invoiceNumber){
            layer.msg("海关缴款书信息：第"+ ++i+"行缴款书号码不能为空");
            return false;
        }
        // if(!invoicedPaymentCertificate[i].taxRate){
        //     layer.msg("海关缴款书信息：第"+ ++i+"行税率不能为空");
        //     return false;
        // }
        if(!invoicedPaymentCertificate[i].currencyCode){
            layer.msg("海关缴款书信息：第"+ ++i+"行币种不能为空");
            return false;
        }
        // if(!invoicedPaymentCertificate[i].taxAmount&&invoicedPaymentCertificate[i].taxAmount!==0){
        //     layer.msg("海关缴款书信息：第"+ ++i+"行含税金额不能为空");
        //     return false;
        // }
        // if(!invoicedPaymentCertificate[i].noTaxAmount&&invoicedPaymentCertificate[i].noTaxAmount!==0){
        //     layer.msg("海关缴款书信息：第"+ ++i+"行未税金额不能为空");
        //     return false;
        // }

        if(!invoicedPaymentCertificate[i].diffTaxMoney&&invoicedPaymentCertificate[i].diffTaxMoney!==0){
            layer.msg("海关缴款书信息：第"+ ++i+"行税额不能为空");
            return false;
        }

        // var taxAmountTemp = Number(invoicedReceipt[i].taxAmount);
        // var totalTax = Number(invoicedReceipt[i].noTaxAmount).add(Number(invoicedReceipt[i].diffTaxMoney));
        // //暂存时校验关联发票填的金额是否正确，需满足公司：含税金额 = 未税金额 + 税额，否则，报错“发票含税金额不等于未税金额+税额” 邓京术 2024-08-26
        // if(taxAmountTemp!== totalTax) {
        //     layer.msg("海关缴款书信息：第"+ ++i+"行发票含税金额为："+taxAmountTemp+", 不等于(未税金额+税额):"+ totalTax);
        //     return false;
        // }
    }
    // }

    let flag = true, msg = [];
    // for (let i = 0 ; i < detail.length ; i ++){
    //     if (!detail[i].poId){
    //         msg.push('SAP订单号：' +detail[i].poCode + '，订单行号：'+detail[i].poItemNo+'未找到该采购订单;');
    //         flag = false;
    //         continue;
    //     }
    //     if (!detail[i].finConf || Number(detail[i].finConf)===0){
    //         msg.push('SAP订单号：' +detail[i].poCode + '，订单行号：'+detail[i].poItemNo+'财务未确认;');
    //         flag = false;
    //     }
    // }
    if(!flag){
        layer.confirm(msg.join('<br/>'), {icon: 2, title: '温馨提示'});
        return false;
    }

    // 对账数量合计
    var statementNum = 0, shareFlag = 0;
    // ,purchaseGroup = "";
    for(var i = 0; i < detail.length; i++){
        var row = detail[i], obj = {};
        obj.id = 0;
        obj.itemNo = '';
        obj.iaId = 0;
        obj.iaNo = '';
        obj.asId = row.asId;
        obj.asNo = row.asNo;
        obj.asdId = row.asdId;
        obj.asdItemNo = row.asdItemNo;
        obj.statementNum = row.statementNum;
        // obj.taxCode = row.asTaxCode;
        obj.taxValue = row.asTaxValue;
        obj.notTaxPrice = row.asNotTaxPrice;
        obj.taxPrice = row.asTaxPrice;
        obj.notTaxAmount = row.asNotTaxAmount;
        obj.taxAmount = row.asTaxAmount;
        obj.diffTaxAmount = row.asDiffTaxAmount;
        obj.iaDiffPrice = 0;
        obj.iaDiffAmount = 0;
        obj.receiveId = row.receiveId;
        obj.shareFlag = row.shareFlag;
        obj.shareNum = row.shareNum;
        statementItem.push(obj);
        // taxData.push(row.taxCode);
        paymentTermCode.push(row.paymentTermCode);

        statementNum = Number(statementNum) + Number(row.statementNum);
        shareFlag = Number(shareFlag) + Number(row.shareFlag);
        //是否包含101 102 122 123
        if(["101","102","122","123"].indexOf(row.sapMoveType) >= 0 && !is101Flag){
            is101Flag = true;
        }
        // if(i !== 0 && row.pgCode !== purchaseGroup){
        //     layer.msg("采购组不一致");
        //     return ;
        // }
        // purchaseGroup = row.pgCode;
    }

    // if(Number(invoiceTaxAmount) <= 0 && is101Flag){
        //财务说去掉此限制 2024-08-22 邓京术
        //topWin.layer.alert('开票含税总金额必须大于零', {icon: 0});
        //return false;
    // }
    // 检查对账单明细中对账税率是否都相同
    // if(!checkIsAllEqual(taxData)){
    //     topWin.layer.alert('明细中税率不相同', {icon: 0});
    //     return false;
    // }
    // // 检查对账单明细中付款条件是否都相同
    // if(!checkIsAllEqual(paymentTermCode)){
    //     topWin.layer.alert('明细中付款条件不相同', {icon: 0});
    //     return false;
    // }

    // if(Number(shareFlag) === 0){
    //     topWin.layer.alert('选择的对账明细行再后续处理分摊返利或者扣款时会出现错误, 请重新选择', {icon: 0});
    //     return false;
    // }

    // 对账扣款数据
    // var deduction = $(el.tbDeduction).datagrid('getRows'), sdIds = [];
    // for(var j = 0; j < deduction.length; j++){
    //     sdIds.push(deduction[j].sdId);
    // }

    // 对账返利数据
    // var rebate = $(el.tbRebate).datagrid('getRows'), srIds = [];
    // for(var k = 0; k < rebate.length; k++){
    //     srIds.push(rebate[k].srId);
    // }

    // 对账返利数据
    // var advance = $(el.tbAdvance).datagrid('getRows'), paIds = [];
    // for(var k = 0; k < advance.length; k++){
    //     paIds.push(advance[k].id);
    // }

    var headData = {};
    headData.id = $(el.id).val();
    headData.invoiceApplyNo = $(el.iaNo).val();
    headData.accountStatementId = $(el.accountStatementId).val();
    headData.accountStatementNo = $(el.accountStatementNo).textbox('getValue');
    // headData.orderType = orderType;
    headData.companyCode = companyCode;
    headData.companyName = companyName;
    // headData.taxCode = taxCode;
    headData.purchaseGroup = purchaseGroup;
    headData.paperlessFlag = paperlessFlag;
    headData.paymentWay = paymentWay;
    headData.files = files;
    // headData.factoryCode = factoryCode;
    // headData.factoryName = factoryName;
    headData.currencyCode = currencyCode;
    headData.supplierCode = supplierCode;
    headData.supplierName = supplierName;
    // headData.invoiceNetAmount = Number(invoiceNetAmount.replace(/,/g,''));
    // headData.invoiceTaxAmount = Number(invoiceTaxAmount.replace(/,/g,''));
    // headData.allBudInnerMoney = Number(allBudInnerMoney.replace(/,/g,''));
    headData.invoiceTaxTotalAmount = Number(invoiceTaxTotalAmount.replace(/,/g,''));
    // headData.paymentCertificateTotalInclTax = Number(paymentCertificateTotalInclTax.replace(/,/g,''));
    // headData.paymentCertificateTotalExclTax = Number(paymentCertificateTotalExclTax.replace(/,/g,''));
    headData.paymentCertificateTaxAmount = Number(paymentCertificateTaxAmount.replace(/,/g,''));
    headData.invoiceTotalAmount = Number(invoiceTotalAmount.replace(/,/g,''));
    headData.invoiceTotalDiffAmount = Number(invoiceTotalDiffAmount.replace(/,/g,''));
    headData.diffAmountSap = Number(diffAmountSap.replace(/,/g,''));
    headData.diffTaxAmountSap = Number(diffTaxAmountSap.replace(/,/g,''));
    // headData.invoiceDiffAmount = Number(headData.invoiceTaxAmount) - Number(headData.invoiceNetAmount);
    headData.invoiceTaxAmount =  Number(taxAmount.replace(/,/g,''));
    // headData.diffAmount =  Number(domesticTaxTotalAmount.replace(/,/g,''));
    headData.invoiceDiffAmount =  Number(domesticTaxTotalAmount.replace(/,/g,''));
    headData.invoiceNetAmount = Number(headData.invoiceTaxAmount) - Number(headData.invoiceDiffAmount);
    headData.actualUnpaidAmount = Number(headData.invoiceTaxTotalAmount) + Number(headData.paymentCertificateTaxAmount);
    headData.dntAmount = dntAmount;
    headData.deductionAmount = deductionAmount;
    headData.rntAmount = rntAmount;
    headData.rebateAmount = rebateAmount;
    headData.invoiceNum = invoiceNum;
    headData.invoiceNo = invoiceNo;
    headData.remark = remark;
    headData.statementNum = statementNum;
    headData.purchaseGroup = purchaseGroup;
    // if (!foreignCurrencyAddFlag){
    headData.foreignCurrencyAddFlag = foreignCurrencyAddFlag;
    // }
    if (optType === 0 || orderType === 5) {
        headData.billId = billId;
        headData.billNo = billNo;
    }

    var dataParams = {};
    dataParams.headData = headData;
    dataParams.detailDate = statementItem;
    if (Number(foreignCurrencyAddFlag)===0) {
        dataParams.invoicedReceiptData = invoicedReceipt;
    }
    // if (Number(foreignCurrencyAddFlag)===0) {
        dataParams.invoicedPaymentCertificateData = invoicedPaymentCertificate;
    // }
    // dataParams.deductionDetailData = getDeductionDetail();
    // endFileEditor();
    // var fileJson = $(el.tbFile).datagrid('getRows')
    // dataParams.fileJson = JSON.stringify(fileJson);
    // dataParams.addSdIds = sdIds;
    // dataParams.addSrIds = srIds;
    // dataParams.addPaIds = paIds;
    var url = '';
    var satisfyFlagExist = false;
    if(headData.id > 0){
        url = g.ctx + 'pc/finance/cost/invoiced/apply/rest/saveHead';
    }else{
        url = g.ctx + 'pc/finance/cost/invoiced/apply/rest/save';
    }
    // const uploadAttachmentFileDataList = Number(tbAttachmentLookFlag)===1?[]:$(el.tbAttachment).datagrid("getData").rows;
    // dataParams.businessAttachmentDTOList = uploadAttachmentFileDataList;
    // uploadAttachmentFileDataList.forEach(item=>{
    //     if (item.satisfyFlag===0){
    //         satisfyFlagExist = true;
    //     }
    // })

    dataSaveAjax(url,dataParams,callback)

}
function dataSaveAjax(url,dataParams,callback) {
    //新增逻辑，编辑都需要校验如果无纸化选择了是，该供应商对账月份是否有未确认的订单及未签署的订单，否则报错 邓京术 2025-06-05
    var paperlessFlag1 = $(el.paperlessFlag).combobox('getValue');
    if(paperlessFlag1　&&　Number(paperlessFlag1)===1) {
        $.ajax({
            url: g.ctx + 'pc/finance/invoiced/apply/rest/statementInvoicing/checkHasNGSignOk',
            type: 'POST',
            async: false,
            data: {accountStatementId:$(el.accountStatementId).val(),year:$(el.accountStatementYear).val(),month:$(el.accountStatementMonth).val(), supplierCode:$(el.supplierCode).textbox('getValue')},
            dataType: 'json',
            success: function (flag) {
                var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
                $.ajax({
                    url: url,
                    type: 'POST',
                    data: JSON.stringify(dataParams),
                    contentType: 'application/json',
                    success: function (data) {
                        topWin.layer.close(loading);
                        callback(data);
                    },
                    error: function (data) {
                        topWin.layer.close(loading);
                        topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
                    }
                });
            },
            error: function (redata) {
                topWin.layer.alert(redata.responseJSON.message, {icon: 2});
                return;
            }
        });
    } else {
        var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: url,
            type: 'POST',
            data: JSON.stringify(dataParams),
            contentType: 'application/json',
            success: function (data) {
                topWin.layer.close(loading);
                callback(data);
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    }
}
function endAdvanceEditor() {
    // 结束行编辑
    $(el.tbAdvance).datagrid('endEdit', el.editAdvanceIndex);
    $(el.tbAdvance).datagrid('unselectRow', el.editAdvanceIndex);
    el.editAdvanceIndex = undefined;
    return true;
}
/**
 * 采购确认
 * @param approveStatus
 * @param callback
 * @returns {boolean}
 */
function purchaseConfirm(approveStatus,callback) {
    endAdvanceEditor();
    var id = $(el.id).val(),remark = $(el.remark).val(), approveRemark = $(el.approveRemark).val(),
        // invoiceNetAmount = $(el.invoiceNetAmount).textbox('getValue'),
        // invoiceTaxAmount = $(el.invoiceTaxAmount).textbox('getValue'),
        // strikePriceAmount = $(el.strikePriceAmount).textbox('getValue'),
        actualUnpaidAmount = $(el.actualUnpaidAmount).textbox('getValue');
        // currencyCode = $(el.currencyCode).val()
    // if (!remark) {
    //     topWin.layer.alert('请填写备注', {icon: 0});
    //     return false;
    // }
    if(!approveRemark){
        topWin.layer.alert('请输入审批意见', {icon: 0});
        return false;
    }
    if (Number(foreignCurrencyAddFlag)===0) {
        var invoicedReceipt = $(el.tbInvoice).datagrid('getRows');
        if (invoicedReceipt.length === 0) {
            topWin.layer.alert('请添加关联发票信息', {icon: 0});
            return false;
        }
    }

    var headData = {};
    headData.id = id;
    headData.remark = remark;
    // headData.invoiceNetAmount = Number(invoiceNetAmount.replace(/,/g,''));
    // headData.invoiceTaxAmount = Number(invoiceTaxAmount.replace(/,/g,''));
    // headData.strikePriceAmount = Number(strikePriceAmount.replace(/,/g,''));
    headData.actualUnpaidAmount = Number(actualUnpaidAmount.replace(/,/g,''));
    // for (let i = 0 ; i < invoicedReceipt.length ; i ++){
    //     // if(!invoicedReceipt[i].deductionCodeType){
    //     //     layer.msg("关联发票信息：第"+ ++i+"行可抵扣编号不能为空");
    //     //     return false;
    //     // }
    //     if(!invoicedReceipt[i].invoiceDate){
    //         layer.msg("关联发票信息：第"+ ++i+"行发票日期不能为空");
    //         return false;
    //     }
    //     // if(!invoicedReceipt[i].invoiceCode){
    //     //     layer.msg("关联发票信息：第"+ ++i+"行发票代码不能为空");
    //     //     return false;
    //     // }
    //     if(!invoicedReceipt[i].invoiceNumber){
    //         layer.msg("关联发票信息：第"+ ++i+"行发票号码不能为空");
    //         return false;
    //     }
    //     if(!invoicedReceipt[i].dutyParagraph){
    //         layer.msg("关联发票信息：第"+ ++i+"行税号不能为空");
    //         return false;
    //     }
    //     if(!invoicedReceipt[i].taxRate){
    //         layer.msg("关联发票信息：第"+ ++i+"行税率不能为空");
    //         return false;
    //     }
    //     if(!invoicedReceipt[i].currencyCode){
    //         layer.msg("关联发票信息：第"+ ++i+"行币种不能为空");
    //         return false;
    //     }
    //     if(!invoicedReceipt[i].taxAmount){
    //         layer.msg("关联发票信息：第"+ ++i+"行含税金额不能为空");
    //         return false;
    //     }
    //     if(!invoicedReceipt[i].noTaxAmount&&invoicedReceipt[i].noTaxAmount!==0){
    //         layer.msg("关联发票信息：第"+ ++i+"行未税金额不能为空");
    //         return false;
    //     }
    //     // if(!invoicedReceipt[i].fileId){
    //     //     layer.msg("关联发票信息：第"+ ++i+"行发票附件不能为空");
    //     //     return false;
    //     // }
    // }
    // var advances = $(el.tbAdvance).datagrid('getRows'), paIds = [];
    // for(var ii = 0; ii < advances.length; ii++){
    //     if(advances[ii].strikePrice > advances[ii].surplusReversalMoney){
    //         topWin.layer.alert('预付款信息：第'+(ii+1)+"行本次冲账金额不能大于剩余可冲账金额，不能提交!", {icon: 0});
    //         return false;
    //     }
    // }
    var dataParams = {};
    headData.accountStatementId = $(el.accountStatementId).val();
    headData.factoryCode = $(el.factoryCode).val();
    dataParams.headData = headData;
    // dataParams.invoicedReceiptData = invoicedReceipt;
    dataParams.approveRemark = approveRemark;
    dataParams.roleType = 1;
    dataParams.approveStatus = approveStatus;
    // dataParams.addAdvances = advances;
    //2025-09-22 qzc
        //币种
        // if(currencyCode === "CNY"){
        //     //①币种是CNY时（人民币资料交接）--冲账总金额不能 大于 发票含税总金额（供应商提供的发票金额）
        //     var invoiceTaxTotalAmount = $(el.invoiceTaxTotalAmount).textbox('getValue');
        //     if(headData.strikePriceAmount > Number(invoiceTaxTotalAmount.replace(/,/g,''))){//发票含税总金额
        //         topWin.layer.alert("币种是CNY时（人民币资料交接）冲账总金额不能大于发票含税总金额", {icon: 0});
        //         return false;
        //     }
        // }
        // if(currencyCode === "USD"){
        //     //②币种非CNY时（外币资料交接）----冲账总金额不能 大于 开票含税总金额（对账单中的含税金额）
        //     //冲账总金额
        //     if(headData.strikePriceAmount  > headData.invoiceTaxAmount){//开票含税总金额
        //         topWin.layer.alert("币种是USD时（外币资料交接）冲账总金额不能大于开票含税总金额", {icon: 0});
        //         return false;
        //     }
        // }
    // var satisfyFlagExist = false;
    // const uploadAttachmentFileDataList = (Number(tbAttachmentLookFlag)===1)?[]:$(el.tbAttachment).datagrid("getData").rows;
    //     if (uploadAttachmentFileDataList.length>0){
    //         uploadAttachmentFileDataList.forEach(item=>{
    //             if (item.satisfyFlag===0){
    //                 satisfyFlagExist = true;
    //             }
    //         })
    //     }
    // if (satisfyFlagExist){
    //     topWin.layer.alert('附件检查中存在附件未满足,请补充对应附件', {icon: 0});
    //     return false;
    // }
    endManualEditing();
    var manualCheckList = $(el.tbAttachmentManualCheck).datagrid('getRows');
    //判断manualCheckList中人工检查是否选择
    if (manualCheckList.length>0&&approveStatus===1){
        for (var i = 0; i < manualCheckList.length; i++) {
            console.log(manualCheckList[i].manualCheck)
            if (isBlank(manualCheckList[i].manualCheck)) {
                $(el.dataTabs).tabs('select', 7);
                topWin.layer.alert('请确认并选择人工检查项', {icon: 0});
                return false;
            }
        }
    }
    dataParams.manualCheckList = manualCheckList;
    console.log(JSON.stringify(dataParams))
    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'pc/finance/cost/invoiced/apply/rest/approve/confirm',
        type: 'POST',
        data: JSON.stringify(dataParams),
        contentType: 'application/json',
        success: function (data) {
            topWin.layer.close(loading);
            callback(data);
            topWin.layer.msg('操作成功', {icon: 1});
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}


/**
 * 采购确认
 * @param approveStatus
 * @param callback
 * @returns {boolean}
 */
function saleContractConfirm(approveStatus,callback) {
    // endAdvanceEditor();
    var id = $(el.id).val(),remark = $(el.remark).val(), approveRemark = $(el.approveRemark).val();
    currencyCode = $(el.currencyCode).val()
    if(!approveRemark){
        topWin.layer.alert('请输入审批意见', {icon: 0});
        return false;
    }


    var headData = {};
    headData.id = id;
    headData.remark = remark;


    var dataParams = {};
    dataParams.headData = headData;
    dataParams.approveRemark = approveRemark;
    dataParams.roleType = 1;
    dataParams.approveStatus = approveStatus;


    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'pc/finance/cost/invoiced/apply/rest/saleContract/confirm',
        type: 'POST',
        data: JSON.stringify(dataParams),
        contentType: 'application/json',
        success: function (data) {
            topWin.layer.close(loading);
            callback(data);
            topWin.layer.msg('操作成功', {icon: 1});
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}


/**
 * 财务确认
 * @param approveStatus
 * @param callback
 * @returns {boolean}
 */
function financeConfirm(approveStatus,callback) {
    // endAdvanceEditor();

    var id = $(el.id).val(),remark = $(el.remark).val(), approveRemark = $(el.approveRemark).val();
        // invoiceNetAmount = $(el.invoiceNetAmount).textbox('getValue');
        // invoiceTaxAmount = $(el.invoiceTaxAmount).textbox('getValue');
    // if (!remark) {
    //     topWin.layer.alert('请填写备注', {icon: 0});
    //     return false;
    // }
    if(!approveRemark){
        topWin.layer.alert('请输入审批意见', {icon: 0});
        return false;
    }
    if (Number(foreignCurrencyAddFlag)===0) {
        var invoicedReceipt = $(el.tbInvoice).datagrid('getRows');
        if (invoicedReceipt.length === 0) {
            topWin.layer.alert('请添加关联发票信息', {icon: 0});
            return false;
        }
    }
    var headData = {};
    headData.id = id;
    headData.remark = remark;
    // headData.invoiceNetAmount = Number(invoiceNetAmount.replace(/,/g,''));
    // headData.invoiceTaxAmount = Number(invoiceTaxAmount.replace(/,/g,''));
    // for (let i = 0 ; i < invoicedReceipt.length ; i ++){
    //     // if(!invoicedReceipt[i].deductionCodeType){
    //     //     layer.msg("关联发票信息：第"+ ++i+"行可抵扣编号不能为空");
    //     //     return false;
    //     // }
    //     if(!invoicedReceipt[i].invoiceDate){
    //         layer.msg("关联发票信息：第"+ ++i+"行发票日期不能为空");
    //         return false;
    //     }
    //     // if(!invoicedReceipt[i].invoiceCode){
    //     //     layer.msg("关联发票信息：第"+ ++i+"行发票代码不能为空");
    //     //     return false;
    //     // }
    //     if(!invoicedReceipt[i].invoiceNumber){
    //         layer.msg("关联发票信息：第"+ ++i+"行发票号码不能为空");
    //         return false;
    //     }
    //     if(!invoicedReceipt[i].dutyParagraph){
    //         layer.msg("关联发票信息：第"+ ++i+"行税号不能为空");
    //         return false;
    //     }
    //     if(!invoicedReceipt[i].taxRate){
    //         layer.msg("关联发票信息：第"+ ++i+"行税率不能为空");
    //         return false;
    //     }
    //     if(!invoicedReceipt[i].currencyCode){
    //         layer.msg("关联发票信息：第"+ ++i+"行币种不能为空");
    //         return false;
    //     }
    //     if(!invoicedReceipt[i].taxAmount){
    //         layer.msg("关联发票信息：第"+ ++i+"行含税金额不能为空");
    //         return false;
    //     }
    //     if(!invoicedReceipt[i].noTaxAmount&&invoicedReceipt[i].noTaxAmount!==0){
    //         layer.msg("关联发票信息：第"+ ++i+"行未税金额不能为空");
    //         return false;
    //     }
    //     // if(!invoicedReceipt[i].fileId){
    //     //     layer.msg("关联发票信息：第"+ ++i+"行发票附件不能为空");
    //     //     return false;
    //     // }
    // }
    endManualEditing();
    var manualCheckList = $(el.tbAttachmentManualCheck).datagrid('getRows');
    //判断manualCheckList中人工检查是否选择
    if (manualCheckList.length>0&&approveStatus===1){
        for (var i = 0; i < manualCheckList.length; i++) {
            console.log(manualCheckList[i].manualCheck)
            if (isBlank(manualCheckList[i].manualCheck)) {
                topWin.layer.alert('请确认并选择人工检查项', {icon: 0});
                return false;
            }
        }
    }
    var dataParams = {};
    dataParams.manualCheckList = manualCheckList;
    dataParams.headData = headData;
    // dataParams.invoicedReceiptData = invoicedReceipt;
    dataParams.approveRemark = approveRemark;
    dataParams.roleType = 2;
    dataParams.approveStatus = approveStatus;

    console.log(JSON.stringify(dataParams))
    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: g.ctx + 'pc/finance/cost/invoiced/apply/rest/approve/confirm',
        type: 'POST',
        data: JSON.stringify(dataParams),
        contentType: 'application/json',
        success: function (data) {
            topWin.layer.close(loading);
            callback(data);
            topWin.layer.msg('操作成功', {icon: 1});
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}

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

/**
 * 上传
 */
function uploadAttachmentFile() {
    const url = g.ctx + "pc/sys/businessAttachment/fileUploadWithType";
    uploadAttachmentFileDialog = openDialog("uploadAttachmentFileDialog", url, {
        title: '附件上传',
        width: '400px',
        height: '250px',
        cache: false,
        modal: true,
        border: false,
        draggable: true,
        shadow: false,
        onClose: function () {
            uploadAttachmentFileDialog.dialog('destroy');
        },
        onOpen: function() {
            // dialog打开后，等待iframe加载完成
            const iframe = $(this).find('iframe')[0];
            iframe.onload = function() {
                // 将父页面的函数引用传递给iframe
                iframe.contentWindow.parentCallback = receiveFileUploadData;
            };
        },
        buttons: [{
            text: '继续', iconCls: 'icon-save', handler: function () {
                const iframe = uploadAttachmentFileDialog.find('iframe')[0];
                if (iframe.contentWindow.openFileUploader) {
                    iframe.contentWindow.openFileUploader();
                } else {
                    console.error('openFileUploader method not found');
                }
            }
        }, {
            text: '关闭', iconCls: 'icon-cancel', handler: function () {
                uploadAttachmentFileDialog.dialog('close');
            }
        }]
    });
}

/**
 * 上传完文件的回调
 * @param data 上传文件服务器后的文件数据
 */
function receiveFileUploadData(data) {
    if(optType === 0 || optType === 5) {
        // 新增逻辑
        data.forEach(item => {
            $(el.tbSignFile).datagrid('appendRow',{
                type: item.type,
                fileId: item.fileId,
                createTime: item.dateline,
                fileName: item.fileName
            });
        });
        const allData = $(el.tbSignFile).datagrid("getData").rows;
        $(el.tbSignFile).datagrid('loadData', allData);
    } else if (optType === 1 || optType === 3 || optType === 4) {
        // 编辑逻辑
        data.forEach(item => {
            item["businessId"] = $(el.id).val();
            item["businessCode"] = $(el.iaNo).val();
            item["businessTypeCode"] = "invoice_apply";
        })
        $.ajax({
            url: g.ctx + 'pc/sys/businessAttachment/rest/save',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function (res) {
                const imageCode = getImageCode();
                if (imageCode) {
                    pushImage(res, imageCode);
                }
                topWin.layer.msg('保存成功', {icon: 1});
                $(el.tbSignFile).datagrid('reload');
            },
            error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    }

    uploadAttachmentFileDialog.dialog('close');
}

/**
 * 删除
 */
function deleteAttachmentFile() {
    let rows = $(el.tbSignFile).datagrid("getChecked");
    rows = rows.filter(item => {
        return item.deleteFlag === 0;
    });
    if (rows.length > 0) {
        if(optType === 0 || optType === 5) {
            for (let i = 0; i < rows.length; i++) {
                const rowIndex = $(el.tbSignFile).datagrid('getRowIndex', rows[i]);
                $(el.tbSignFile).datagrid('deleteRow', rowIndex);
            }
        } else {
            const id = rows[0].id;
            topWin.layer.prompt({
                formType: 2, value: '', title: '请输入删除备注',
            }, function (value, index) {
                $.ajax({
                    type: 'post',
                    url: g.ctx + 'pc/sys/businessAttachment/rest/delete',
                    data: {
                        id: id,
                        remark: value
                    },
                    async: false,
                    success: function () {
                        const imageCode = getImageCode();
                        if (imageCode) {
                            deleteImage(rows, imageCode);
                        }
                        $(el.tbSignFile).datagrid('reload');
                        topWin.layer.close(index);
                    },
                    error: function (error) {
                        topWin.layer.close(index);
                        topWin.layer.alert(error.responseJSON.message, {
                            icon: 2,
                            content: error.responseJSON.message
                        });
                    }
                });
            });
        }
    } else {
        layer.msg('请选择一条未删除的数据');
    }
}

/**
 * 备注
 */
function remarkAttachmentFile() {
    let rows = $(el.tbSignFile).datagrid("getChecked");
    if (rows.length > 0) {
        let selectedRow = rows[0];
        topWin.layer.prompt({
            formType: 2, value: '', title: '请输入备注',
        }, function (value, index) {
            if(optType === 0 || optType === 5) {
                const allData = $(el.tbSignFile).datagrid("getData").rows;
                allData.forEach(row => {
                   if (row.fileId === selectedRow.fileId) {
                       row.remark = value;
                   }
                });
                $(el.tbSignFile).datagrid('loadData', allData);
                topWin.layer.close(index);
            } else {
                $.ajax({
                    type: 'post',
                    url: g.ctx + 'pc/sys/businessAttachment/rest/remark',
                    data: {
                        id: selectedRow.id,
                        remark: value
                    },
                    async: false,
                    success: function () {
                        $(el.tbSignFile).datagrid('reload');
                        topWin.layer.close(index);
                    }, error: function (data) {
                        topWin.layer.close(index);
                        topWin.layer.alert(data.responseJSON.message, {icon: 2});
                    }
                });
            }
        });
    } else {
        layer.msg('请选择一条数据');
    }
}

function pushAllImageButtonEvent() {
    const businessAttachmentList = [
        // 处理发票数据
        ...$(el.tbInvoice).datagrid("getData").rows.map(invoice => ({
            fileId: invoice.fileId,
            type: "invoice"
        })),

        // 处理附件数据（未删除的）
        ...$(el.tbSignFile).datagrid("getData").rows.filter(item =>
            item.deleteFlag !== 1
        )
    ];
    pushImage(businessAttachmentList);
}

/**
 * 推送影像
 * @param businessAttachmentList 业务文件附件信息
 * @param imageCode 影像编码
 */
function pushImage(businessAttachmentList, imageCode) {
    if (businessAttachmentList.length > 0) {
        let data = {
            businessAttachmentList: businessAttachmentList
        };
        if (imageCode) {
            data.imageCode = imageCode;
        }
        $.ajax({
            type: 'post',
            url: g.ctx + 'pc/sys/kingdeeImage/rest/pushImage',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function () {
                $(el.tbSignFile).datagrid('reload');
            },
            error: function (error) {
                topWin.layer.alert(error.responseJSON.message, {
                    icon: 2,
                    content: error.responseJSON.message
                });
            }
        });
    }
}

/**
 * 删除影像
 */
function deleteAllImageButtonEvent() {
    const imageCode = getImageCode();
    if (imageCode === null) return;
    topWin.layer.confirm('是否删除整单影像？', function (index) {
        let attachmentFiles = $(el.tbSignFile).datagrid("getData").rows;
        attachmentFiles = attachmentFiles.filter(item => {
            // 排除已删除
            return item.deleteFlag !== 1;
        });
        const data = {
            businessAttachmentList: attachmentFiles,
            imageCode: imageCode
        };
        $.ajax({
            type: 'post',
            url: g.ctx + 'pc/sys/kingdeeImage/rest/deleteAllImage',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function () {
                $(el.tbSignFile).datagrid('reload');
                topWin.layer.close(index);
            },
            error: function (error) {
                topWin.layer.close(index);
                topWin.layer.alert(error.responseJSON.message, {
                    icon: 2,
                    content: error.responseJSON.message
                });
            }
        });
    });
}

/**
 * 删除影像
 * @param businessAttachmentList 业务文件附件信息
 * @param imageCode 影像编码
 */
function deleteImage(businessAttachmentList, imageCode) {
    if (businessAttachmentList.length > 0) {
        const data = {
            businessAttachmentList: businessAttachmentList,
            imageCode: imageCode
        };
        $.ajax({
            type: 'post',
            url: g.ctx + 'pc/sys/kingdeeImage/rest/deleteImage',
            contentType: 'application/json',
            data: JSON.stringify(data),
            success: function () {
                $(el.tbSignFile).datagrid('reload');
            },
            error: function (error) {
                topWin.layer.alert(error.responseJSON.message, {
                    icon: 2,
                    content: error.responseJSON.message
                });

            }
        });
    }
}

/**
 * 查看影像附件
 */
function viewImageButtonEvent() {
    const imageCode = getImageCode();
    if (!imageCode) {
        topWin.layer.alert("请先推送影像", {icon: 2, title: "温馨提示"});
    } else {
        $.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
                });
            }
        });
    }
}

/**
 * 根据code获取对应的name
 * @param {Array} list - 文件类型列表
 * @param {string} code - 要查找的code
 * @returns {string|null} 对应的name，找不到返回null
 */
function getNameByCode(list, code) {
    const item = list.find(item => item.code === code);
    return item ? item.name : null;
}

async function initTaxNo(supplierCode, companyCode) {
    await $.ajax({
        type: 'get',
        url: g.ctx + 'pc/finance/invoiced/apply/rest/getSupplierInfo',
        data: {
            supplierCode: supplierCode
        },
        async: false,
        success: function (data) {
            billTaxNo = data.businessRegisterNo;
        }, error: function () {}
    });
    await $.ajax({
        type: 'get',
        url: g.ctx + 'pc/finance/invoiced/apply/rest/getSupplierInfo',
        data: {
            supplierCode: "80" + companyCode
        },
        async: false,
        success: function (data) {
            companyTaxNo = data.businessRegisterNo;
            companyName = data.supplierName;
        }, error: function () {}
    });
}

/**
 * 新增开票申请单时，上传了附件未点暂存的情况，删除文件附件
 * PS:父画面调用
 */
function deleteUnsavedAttachment() {
    const uploadAttachmentFileDataList = $(el.tbSignFile).datagrid("getData").rows;
    let deleteIds = [];
    uploadAttachmentFileDataList.forEach(row => {
        if (typeof(row.id) === "undefined" || row.id == null || row.id === "") {
            deleteIds.push(row.fileId);
        }
    });
    if (deleteIds.length === 0) return;
    $.ajax({
        type: 'get',
        url: g.ctx + 'pc/sys/file/rest/delete/file',
        data: {
            fileIds: deleteIds.join(",")
        },
        success: function () {},
        error: function () {}
    });
}

function getImageCode() {
    const allData = $(el.tbSignFile).datagrid("getData").rows;
    for (let index in allData) {
        const row = allData[index];
        if (row.imageCode) {
            return row.imageCode;
        }
    }
    return null;
}

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