/**
 * 对账模块-对账单新增页面JS
 *
 * Created by li.kui on 2020/8/1.
 */
'use strict';
var el = {
    dataPanel: '#dataPanel',
    tbLog: '#tbLog',
    tbAttachment: '#tbAttachment',
    tbAttachmentCheck: '#tbAttachmentCheck',
    tbAttachmentManualCheck: '#tbAttachmentManualCheck',
    accountImgCode: '#accountImgCode',
    businessCodes: [],
    attachmentTypeCreateConfigManualList: [],
    editManualIndex: undefined,
    dataDiv: '#dataDiv',
    id: '#id',
    files: '#files',
    orderType: '#orderType',
    isSupplier: '#isSupplier',
    supplierCode: '#supplierCode',
    supplierGroup: '#supplierGroup',
    supplierName: '#supplierName',
    companyCode: '#companyCode',
    companyName: '#companyName',
    factoryCode: '#factoryCode',
    factoryName: '#factoryName',
    deductionAmount: '#deductionAmount',
    rebateAmount: '#rebateAmount',
    inStockStartDate: '#inStockStartDate',
    inStockEndDate: '#inStockEndDate',
    accountStatementNo: '#accountStatementNo',
    bpPayableBalance: '#bpPayableBalance',
    bpEstimateBalance: '#bpEstimateBalance',
    etPayableBalance: '#etPayableBalance',
    etEstimateBalance: '#etEstimateBalance',
    beginPeriodTotal: '#beginPeriodTotal',
    tbApproveLog: '#tbApproveLog',
    endPeriodTotal: '#endPeriodTotal',
    currPaymentAmount: '#currPaymentAmount',
    notTaxAmount: '#notTaxAmount',
    differenceAmount: '#differenceAmount',
    supplierCode2: '#supplierCode2',
    supplierName2: '#supplierName2',
    approveOpinion: '#approveOpinion',
    taxAmount: '#taxAmount',
    delDetail : [],
    currencyCode: '#currencyCode',
    remark: '#remark',
    dataTabs: '#dataTabs',
    tbDetails: '#tbDetails',
    filterFlag: false,
    tbDeduction: '#tbDeduction',
    tbRebate: '#tbRebate',
    localCurrency : '#localCurrency',
    originalCurrency: '#originalCurrency',
    ledgerAccount: '#ledgerAccount',
    ledgerAccountName: '#ledgerAccountName',
    advanceLocalCurrency: '#advanceLocalCurrency',
    advanceOriginalCurrency: '#advanceOriginalCurrency',
    invoiceFileInput: '#invoiceFileInput',
    fileId: '#fileId',
    voucherType: '#voucherType',
    taxCode: '#taxCode',
    accountStatementYear: '#accountStatementYear',
    accountStatementMonth: '#accountStatementMonth',
    paymentTermDesc: '#paymentTermDesc',
    paymentTermCode: '#paymentTermCode',
    paymentWay: '#paymentWay',
    purchaseGroup: '#purchaseGroup',
    poType: '#poType',
    choseSupplierDialog: null,
    choseRebateDataDialog: null,
    userTableColumn: [],
    originalRows: [],
    originalSignRows: [],
    removeList: [],
    uniqueDetailByBusinessCode: {}, // 送货单数据map，通过编码查询（el.uniqueDetailByBusinessCode[xxx]）
    uniqueDetail: [],   // 所有送货单数据（单号不重复）
    bodyHeight: document.documentElement.clientHeight
};
let uploadAttachmentFileDialog;
var businessFalg = "0";

/**
 * 文档就绪
 */
$(function () {
    initDict('payment_method,po_type,po_item_type,po_item_subject,unit,sign_order,sign_type')
    initDictName('businessFileType')
    initNecessaryDatas('pc/sys/tax/rest/listAll')
    $('#dataTabs').tabs({
        onSelect: function(title) {
            if (title === '附件清单'&&tbAttachmentLookFlag===1) {
                layer.msg("无权限访问");
                $(el.dataTabs).tabs('select', 0);
                return false;
            }
        }
    });
    $(el.dataPanel).panel({
        collapsible: true,
        onCollapse: function () {
            $(el.dataTabs).tabs('select', 0);

            $(el.tbDetails).datagrid('resize', {height: el.bodyHeight - 80});
            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});
            }
            if (optType!==0){
                $(el.tbApproveLog).datagrid('resize', {height: el.bodyHeight - 80});
            }
            // $(el.tbRebate).datagrid('resize', {height: el.bodyHeight - 80});
            // $(el.tbDeduction).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.tbDetails).datagrid('resize', {height: 400});
            if ($(el.tbAttachment).length>0){
                $(el.tbAttachment).datagrid('resize', {height: 400});
            }
            $(el.tbAttachmentCheck).datagrid('resize', {height: 400});
            if (manualCheckShowFlag){
                $(el.tbAttachmentManualCheck).datagrid('resize', {height: 400});
            }
            if (optType!==0){
                $(el.tbApproveLog).datagrid('resize', {height: el.bodyHeight - dataDiv});
            }
            // $(el.tbRebate).datagrid('resize', {height: el.bodyHeight - dataDiv});
            // $(el.tbDeduction).datagrid('resize', {height: el.bodyHeight - dataDiv});
        }
    });

    // 获取当前用户在本页面中表格列配置
    // findUserTableColumn();

    // 加载页面输入或下拉框数据
    initPageInput();

    initTbDetails();
    if ($(el.tbAttachment).length>0){
        loadSignFileGrid();
    }
    if (manualCheckShowFlag){
        initTbAttachmentManualCheck();
    }
    initTbAttachmentCheck();
    if (optType!==0){
        initTbApproveLog();
        iniTtbLog();
    }
    // initTbDeduction();
    // initTbRebate();
});

/**
 * 初始化入库明细表格
 */
function initTbDetails() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90, orderType = $(el.orderType).val();
    // var columns = dynamicColumns(orderType);
    var toolBar = [];
    if (optType===0){
        toolBar.push(
            {
                text: '获取凭证信息',
                iconCls: 'icon-add',
                handler: function () {
                    var companyCode = $(el.companyCode).combobox('getValue'), factoryCode = $(el.factoryCode).combobox('getValue'), taxCode = $(el.taxCode).combobox('getValue'),
                        inStockStartDate = $(el.inStockStartDate).datebox('getValue'), inStockEndDate = $(el.inStockEndDate).datebox('getValue'),
                        currencyCode = $(el.currencyCode).combobox('getValue'), supplierCode = $(el.supplierCode).textbox('getValue'),
                        poType = getTextByJs($(el.poType).combobox('getValues')),
                        voucherType = $(el.voucherType).combobox('getValue'),
                        purchaseGroup = $('#purchaseGroup').combobox('getValue');
                    businessFalg  = "0";
                    getVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,purchaseGroup,poType,taxCode,voucherType,businessFalg);
                }
            },
            // '-',
            // {
            //     text: '全选',
            //     iconCls: 'icon-ok',
            //     handler: function () {
            //         detailSelectAll();
            //     }
            // },
            // '-',
            // {
            //     text: '取消全选',
            //     iconCls: 'icon-remove',
            //     handler: function () {
            //         cancelSelectAll();
            //     }
            // },
            // '-',
            // {
            //     text: '导出',
            //     iconCls: 'icon-download',
            //     handler: function () {
            //         detailExport();
            //     }
            // },
            '-',
            {
                text: '填充应付未清金额',
                iconCls: 'icon-ok',
                handler: function () {
                    payableOutstanding();
                }
            },
            '-',
            {
                text: '修改其他折扣',
                iconCls: 'icon-import',
                handler: function () {
                    updateOther();
                }
            },
            // "-",
            // {
            //     text: '批量价格调整',
            //     id: 'btn_pljgtz',
            //     iconCls: 'icon-import',
            //     handler: function () {
            //         importTaxPriceExcel();
            //     }
            // },
            "-",
            {
                text: '设置不参与',
                id: 'btn_pljgtz',
                iconCls: 'icon-delete',
                handler: function () {
                    remove();
                }
            },
            "-",
            {
                text: '导出',
                iconCls: 'icon-download',
                handler: function () {
                    detailExport();
                }
            },
            "-",
            {
                text: '过滤',
                id: 'btn_filter',
                iconCls: 'icon-filter',
                handler: function () {
                    btnFilter();

                }
            },
            {
                text: '取消折扣信息',
                iconCls: 'icon-cancel',
                handler: function () {
                    //$(el.tb).datagrid('reload');
                    //el.addOrEditDialog.dialog('close');
                    rebackDiscount();

                }
            }, "-",
            {
                text: '获取新凭证信息',
                iconCls: 'icon-add',
                handler: function () {
                    var companyCode = $(el.companyCode).combobox('getValue'), factoryCode = $(el.factoryCode).combobox('getValue'), taxCode = $(el.taxCode).combobox('getValue'),
                        inStockStartDate = $(el.inStockStartDate).datebox('getValue'), inStockEndDate = $(el.inStockEndDate).datebox('getValue'),
                        currencyCode = $(el.currencyCode).combobox('getValue'), supplierCode = $(el.supplierCode).textbox('getValue'),
                        poType = getTextByJs($(el.poType).combobox('getValues')),
                        voucherType = $(el.voucherType).combobox('getValue'),
                        purchaseGroup = $('#purchaseGroup').combobox('getValue');
                    businessFalg  = "1";
                    getVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,purchaseGroup,poType,taxCode,voucherType,businessFalg);
                }
            },"-",
            {
                text: '获取旧凭证信息',
                iconCls: 'icon-add',
                handler: function () {
                    var companyCode = $(el.companyCode).combobox('getValue'), factoryCode = $(el.factoryCode).combobox('getValue'), taxCode = $(el.taxCode).combobox('getValue'),
                        inStockStartDate = $(el.inStockStartDate).datebox('getValue'), inStockEndDate = $(el.inStockEndDate).datebox('getValue'),
                        currencyCode = $(el.currencyCode).combobox('getValue'), supplierCode = $(el.supplierCode).textbox('getValue'),
                        poType = getTextByJs($(el.poType).combobox('getValues')),
                        voucherType = $(el.voucherType).combobox('getValue'),
                        purchaseGroup = $('#purchaseGroup').combobox('getValue');
                    businessFalg  = "2";
                    getVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,purchaseGroup,poType,taxCode,voucherType,businessFalg);
                }
            }
        )
    }else if (optType===1){
        toolBar.push(
            // {
            //     text: '添加',
            //     iconCls: 'icon-add',
            //     handler: function () {
            //         addVoucherData();
            //     }
            // },
            // '-',
            // {
            //     text: '删除',
            //     iconCls: 'icon-remove',
            //     handler: function () {
            //         delStatementItem();
            //     }
            // },
            // '-',
            // {
            //     text: '导出',
            //     iconCls: 'icon-download',
            //     handler: function () {
            //         detailExport();
            //     }
            // },
            // '-',
            // {
            //     text: '获取凭证信息',
            //     iconCls: 'icon-add',
            //     handler: function () {
            //         var companyCode = $(el.companyCode).combobox('getValue'), factoryCode = $(el.factoryCode).combobox('getValue'), taxCode = $(el.taxCode).combobox('getValue'),
            //             inStockStartDate = $(el.inStockStartDate).datebox('getValue'), inStockEndDate = $(el.inStockEndDate).datebox('getValue'),
            //             currencyCode = $(el.currencyCode).combobox('getValue'), supplierCode = $(el.supplierCode).textbox('getValue'),
            //             poType = getTextByJs($(el.poType).combobox('getValues')),
            //             voucherType = $(el.voucherType).combobox('getValues'),
            //             purchaseGroup = $('#purchaseGroup').combobox('getValue');
            //         getVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,purchaseGroup,poType,taxCode,voucherType);
            //     }
            // },
            // '-',
            {
                text: '填充应付未清金额',
                iconCls: 'icon-ok',
                handler: function () {
                    payableOutstanding();
                }
            },
            '-',
            {
                text: '修改其他折扣',
                iconCls: 'icon-import',
                handler: function () {
                    updateOther();
                }
            },
            "-",
            {
                text: '批量价格调整',
                id: 'btn_pljgtz',
                iconCls: 'icon-import',
                handler: function () {
                    importTaxPriceExcel();
                }
            },
            "-",
            {
                text: '设置不参与',
                id: 'btn_pljgtz',
                iconCls: 'icon-delete',
                handler: function () {
                    remove();
                }
            },
            "-",
            {
                text: '导出',
                iconCls: 'icon-download',
                handler: function () {
                    detailExport();
                }
            },
            "-",
            {
                text: '过滤',
                id: 'btn_filter',
                iconCls: 'icon-filter',
                handler: function () {
                    btnFilter();

                }
            },
        )
    }else if (optType===2){
        toolBar.push(
            {
                text: '导出',
                iconCls: 'icon-download',
                handler: function () {
                    detailExport();
                }
            },
            "-",
            {
                text: '过滤',
                id: 'btn_filter',
                iconCls: 'icon-filter',
                handler: function () {
                    if (el.filterFlag){
                        el.filterFlag = false;
                        $(el.tbDetails).datagrid('disableFilter');
                    }else {
                        el.filterFlag = true;
                        $(el.tbDetails).datagrid('enableFilter');
                    }

                }
            },
        )
    }
    var columns = [
        // {
        //     field: 'deleteFlag',
        //     title: '删除标记',
        //     width: 80,
        //     formatter: function (value) {
        //         if (value ===1) {
        //             return '<span style="color: red;">已删除</span>';
        //         }else {
        //             return "未删除";
        //         }
        //     }
        // },
        // {
        //     field: 'zlsdh',
        //     title: 'SC订单号',
        //     width: 90,
        //     sortable: true
        // },
        {
            field: 'itemNo',
            title: '对账单行号',
            width: 80,
            sortable: true,
        },
        {
            field: 'poCode',
            title: 'SAP订单号',
            width: 90,
            sortable: true,
        },
        {
            field: 'poItemNo',
            title: '订单行号',
            width: 70,
            sortable: true,
        },
        {
            field: 'headUpText',
            title: '送货单号',
            width: 100,
            sortable: true,
        },
        {
            field: 'receiveCode',
            title: '入库凭证号',
            width: 90,
            sortable: true,
        },
        {
            field: 'receiveRowNo',
            title: '入库凭证行号',
            width: 100,
            sortable: true,
        },
        {
            field: 'receiveDate',
            title: '收/退日期',
            width: 110,
            sortable: true,
        },
        {
            field: 'purPostDate',
            title: '质检入库日期',
            width: 100,
            sortable: true,
            formatter: function (value) {
                if (!value) {
                    return '';
                }
                return moment(value).format('YYYY-MM-DD');
            }
        },
        {
            field: 'extendFiled1',
            title: '免检标识',
            width: 100,
            sortable: true,
        },
        {
            field: 'invoicedCode',
            title: 'MIRO凭证号',
            width: 100,
            sortable: true,
        },
        {
            field: 'paymentExpireDate',
            title: '付款到期日',
            width: 120,
            sortable: true,
            exportDateFormatter:'date',
            formatter: function (value, row) {
                if (!value) {
                    return '';
                }
                return '<span style="color: red;">' + moment(value).format('YYYY-MM-DD') + '</span>';
            }
        },
        {
            field: 'materialCode',
            title: '物料编码',
            width: 90,
            sortable: true,
        },
        {
            field: 'materialName',
            title: '物料名称',
            width: 180,
            sortable: true,
        },
        // {
        //     field: 'specs',
        //     title: '规格',
        //     width: 120
        // },

        {
            field: 'receiveNum',
            title: '入库数量',
            width: 70,
            sortable: true,
            formatter: function (value) {
                if (value < 0) {
                    return '<span style="color: red;">' + value + '</span>';
                }else {
                    return value;
                }
            }
        },
        {
            field: 'materialUnit',
            title: '单位',
            width: 70,
            sortable: true,
            formatter: function (value) {
                return getDicName('unit',value)
            }
        },


        {
            field: 'paymentTermCode',
            title: '付款条件',
            width: 200,
            sortable: true,
            formatter: function (value) {
                return getDicName('payment_method',value)
            }
        },
        {
            field: 'inOutFlag',
            title: '出入库标识',
            width: 85,
            sortable: true,
        },
        {
            field: 'supplierName2',
            title: '报关公司',
            width: 100,
            sortable: true
        },
        {
            field: 'asQuantity',
            title: '本次对账数量',
            width: 100,
            sortable: true,
            formatter: function (value) {
                if (value < 0) {
                    return '<span style="color: red;">' + value + '</span>';
                }else {
                    return value;
                }
            }
        },
        // {
        //     field: 'notTaxPrice',
        //     title: '对账未税单价',
        //     width: 70,
        //     formatter: function (value) {
        //         return formatterPrice(value);
        //     }
        // },
        // {
        //     field: 'taxPrice',
        //     title: '对账含税单价',
        //     width: 90,
        //     formatter: function (value) {
        //         return formatterPrice(value);
        //     }
        // },
        {
            field: 'orderNotTaxPrice',
            title: '未税单价',
            width: 90,
            sortable: true,
            formatter: function (value) {
                return formatterCustomPrice(value,5,true,false)
            }
        },
        {
            field: 'orderTaxPrice',
            title: '含税单价',
            sortable: true,
            width: 90,
            formatter: function (value) {
                return formatterCustomPrice(value,5,true,false);
            }
        },
        // {
        //     field: 'orderOriginalTaxPrice',
        //     title: '订单原含税单价',
        //     width: 90,
        //     formatter: function (value) {
        //         return formatterPrice(value);
        //     }
        // },
        {
            field: 'deductionRatio',
            title: '其他折扣',
            sortable: true,
            width: 90,
            formatter: function (value) {
                return formatterPrice(value);
            }
        },
        {
            field: 'taxAmount',
            title: '对账含税金额',
            width: 100,
            sortable: true,
            formatter: function (value) {
                if (value < 0) {
                    return '<span style="color: red;">' + formatterCustomPrice(value,2,true,false) + '</span>';
                }else {
                    return formatterCustomPrice(value,2,true,false);
                }
            }
        },
        // {
        //     field: 'originalTaxAmount',
        //     title: '对账原含税金额',
        //     width: 100,
        //     sortable: true,
        //     formatter: function (value,row) {
        //         if (row.taxAmount < 0) {
        //             return '<span style="color: red;">-' + formatterCustomPrice(value,2,true,false) + '</span>';
        //         }else {
        //             return formatterCustomPrice(value,2,true,false);
        //         }
        //     }
        // },
        {
            field: 'notTaxAmount',
            title: '对账未税金额',
            width: 100,
            sortable: true,
            formatter: function (value) {
                if (value < 0) {
                    return '<span style="color: red;">' + formatterCustomPrice(value,2,true,false) + '</span>';
                }else {
                    return formatterCustomPrice(value,2,true,false);
                }
            }
        },
        {
            field: 'diffTaxAmount',
            title: '对账税额',
            width: 90,
            sortable: true,
            formatter: function (value) {
                return formatterCustomPrice(value,2,true,false);
            }
        },
        {
            field: 'poType',
            title: '订单类型名称',
            width: 100,
            sortable: true,
            formatter: function (value) {
                return getDicName('po_type',value)
            }
        },{
            field: 'subjectTypeCode',
            title: '项目类别',
            width: 100,
            formatter: function (value) {
                return getDicName("po_item_type", value);
            }
        },{
            field: 'rowTypeCode',
            title: '项目类型',
            width: 100,
            formatter: function (value) {
                return getDicName("po_item_subject", value);
            }
        },
        {
            field: 'orderTaxCode',
            title: '订单税率',
            width: 160,
            sortable: true,
            formatter: function (value) {
                return getNecessaryDataName('pc/sys/tax/rest/listAll',value)
            }
        },
        {
            field: 'taxCode',
            title: '税率',
            width: 160,
            sortable: true,
            formatter: function (value) {
                return getNecessaryDataName('pc/sys/tax/rest/listAll',value)
            }
        },
    ];

    //供应商不能看到的字段
    if (Number($(el.isSupplier).val())===1){
        columns = columns.filter(obj => obj.field !== 'paymentExpireDate');
    }
    $(el.tbDetails).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        url: g.ctx + 'pc/finance/account/statement/detail/rest/find/by/statement/id/factoryCode',
        // height: el.bodyHeight - dataDiv,
        height: 400,
        singleSelect: false,
        rownumbers: true,
        filterBtnIconCls:'icon-filter',
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: true,
        pageSize: 500,
        pageList: [10, 50, 100, 200, 500, 1000,2000,3000],
        showFooter: true,
        queryParams: {
            asId: $(el.id).val(),
            factoryCode: $(el.factoryCode).combobox('getValue')
        },
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                }
            ]
        ],
        columns: [
            columns
        ],
        toolbar: toolBar,
        loadFilter: pagerFilter,
        onLoadSuccess: function (data) {
            if (data.footer){
                $(el.taxAmount).textbox('setValue', new BigNumber(data.footer[0].taxAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN).toFormat(2));
                $(el.notTaxAmount).textbox('setValue',new BigNumber(data.footer[0].notTaxAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN).toFormat(2));
                $(el.differenceAmount).textbox('setValue',new BigNumber(data.footer[0].diffTaxAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN).toFormat(2));
                if ($(el.currencyCode).val() == "CNY") {
                    $(el.supplierCode2).combobox('setValue','');
                    $(el.supplierName2).val('');
                    $(el.supplierCode2).combobox('disable');
                } else {
                    $(el.supplierCode2).combobox('enable');
                    if (data.footer[0].supplierCode2){
                        $(el.supplierCode2).combobox('setValue',data.footer[0].supplierCode2);
                        $(el.supplierName2).val(data.footer[0].supplierName2);
                    }
                }
            }

            //业务编码集合
            var businessCodes = [];
            var detail = data.rows;
            var purchaseCodeAndDeliveryCode = [];
            for(var ii = 0; ii < detail.length; ii++){
                if (detail[ii].headUpText){
                    businessCodes.push(detail[ii].headUpText);
                }
                if (detail[ii].headUpText){
                    purchaseCodeAndDeliveryCode.push(detail[ii].poCode+'_'+detail[ii].headUpText);
                }
                // if (detail[ii].poCode){
                //     businessCodes.push(detail[ii].poCode);
                // }
            }
            // ================== 根据 businessCodes 构建明细映射 ==================
            let uniqueDetailByBusinessCode = {};   // code -> 明细对象（代表）
            let uniqueDetail = [];
            for (let i = 0; i < detail.length; i++) {
                const item = detail[i];
                const code = item && item.headUpText;
                if (!code) continue;

                if (!uniqueDetailByBusinessCode[code]) {
                    uniqueDetailByBusinessCode[code] = item;
                    uniqueDetail.push(item);
                }
            }
            el.uniqueDetailByBusinessCode = uniqueDetailByBusinessCode;
            el.uniqueDetail = uniqueDetail;
            //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;
                    var attachmentTypeCreateConfigList = $(el.currencyCode).combobox('getValue') === "CNY"?eval(attachmentTypeCreateConfigs):eval(overseasAttachmentTypeCreateConfigs);
                    if ($(el.supplierCode).textbox('getValue')==='9999'){
                        attachmentTypeCreateConfigList = eval(correlationAttachmentTypeCreateConfigs);
                    }
                    if ($(el.supplierGroup).val()==='Z001'){
                        attachmentTypeCreateConfigList = [];
                    }
                    //取attachmentTypeCreateConfigList中的code,逗号隔开
                    var attachmentTypeCreateConfigCodes = attachmentTypeCreateConfigList.map(function(item){
                        return item.code;
                    })
                    let url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes?businessIds='+$(el.id).val()+'&businessTypeCodes=account_statement';
                    if (optType===0||optType===1){
                        url = g.ctx + 'pc/sys/businessAttachment/rest/businessAttachmentListNoPageByCodes?businessCodes='+businessCodes.join(',')+'&businessTypeCodes=delivery_order,delivery_to_purchase_order'+'&types='+attachmentTypeCreateConfigCodes.join(',')+'&purchaseCodeAndDeliveryCodes='+purchaseCodeAndDeliveryCode.join('*');
                    }
                    $(el.tbAttachment).datagrid('options').url = url;
                    $(el.tbAttachment).datagrid('load');
                }
            }
        },
        onBeforeSortColumn:function(sort, order){
            console.log(sort)
            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;
        },
    });
}

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

                attachmentTypeCreateConfigList.forEach(function (attachmentTypeCreateConfig) {
                    el.attachmentTypeCreateConfigManualList.push({
                        type : attachmentTypeCreateConfig.code,
                        sysCheck:1
                    })
                });
                el.businessCodes.forEach(function (item) {
                    var obj = {};
                    obj.deliveryOrderNo = item;
                    const returnConfirmStatus = el.uniqueDetailByBusinessCode[item].returnConfirmStatus;
                    attachmentTypeCreateConfigList.forEach(function (attachmentTypeCreateConfig) {
                        var exist = allRows.find(function (item2) {
                            return item2.businessCode === item && item2.type === attachmentTypeCreateConfig.code
                                &&attachmentTypeCreateConfig.code!=='agent_supplier_invoice'
                                &&attachmentTypeCreateConfig.code!=='agent_supplier_packing_list'
                                &&attachmentTypeCreateConfig.code!=='invoice_and_packing_list'

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

                        }
                        if (attachmentTypeCreateConfig.code==='agent_supplier_packing_list'){
                            var exist22 = allRows.find(function (item2) {
                                return item2.type === 'agent_supplier_packing_list';
                            });
                            if (!exist22){
                                var exist2 = allRows.find(function (item2) {
                                    return item2.businessCode === item && item2.type === 'invoice_and_packing_list';
                                });
                                exist = exist2;
                                obj[attachmentTypeCreateConfig.code] = exist2?1:0;
                            }else {
                                exist = 1;
                                obj[attachmentTypeCreateConfig.code] = 1;
                            }
                        }

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

                        }
                        if (attachmentTypeCreateConfig.code==='packing_list'){
                            var exist22 = allRows.find(function (item2) {
                                return item2.type === 'supplier_packing_list';
                            });
                            if (!exist22){
                                var exist2 = allRows.find(function (item2) {
                                    return item2.businessCode === item && item2.type === 'material_invoice_and_packing_list';
                                });
                                exist = exist2;
                                obj[attachmentTypeCreateConfig.code] = exist2?1:0;
                            }else {
                                exist = 1;
                                obj[attachmentTypeCreateConfig.code] = 1;
                            }
                        }
                        // 退货单，且无退货状态，则无需校验
                        if (attachmentTypeCreateConfig.code === 'return_order' && !returnConfirmStatus) {
                            exist = 1;
                            obj[attachmentTypeCreateConfig.code] = 2;
                        }

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

                    });
                    checkRows.push(obj);
                });
                //加强逻辑检查
                checkRows.forEach(function (item) {
                    attachmentTypeCreateConfigList.forEach(function (attachmentTypeCreateConfig) {
                        if (item[attachmentTypeCreateConfig.code]===0){
                            item.satisfyFlag=0;
                        }
                    });
                });
                //单据类型检查
                el.attachmentTypeCreateConfigManualList.forEach(function (item) {
                    checkRows.forEach(function (item1) {
                        if (item1[item.type]===0){
                            item.sysCheck = 0;
                        }
                    });
                });

                $(el.tbAttachmentCheck).datagrid('loadData', {total: checkRows.length, rows: checkRows});
                if (manualCheckShowFlag){
                    $(el.tbAttachmentManualCheck).datagrid('options').queryParams = {
                        businessType: 0,
                        currencyCode: $(el.currencyCode).combobox('getValue'),
                        paymentWay: $(el.paymentWay).combobox('getValue'),
                        supplierCode: $(el.supplierCode).textbox('getValue'),
                        supplierGroup: $(el.supplierGroup).val(),
                        businessId: $(el.id).val(),
                        businessCode: $(el.accountStatementNo).textbox('getValue')
                    };
                    $(el.tbAttachmentManualCheck).datagrid('options').url = g.ctx + 'pc/finance/attachment/manual/check/rest/list';
                    $(el.tbAttachmentManualCheck).datagrid('load');
                    // initTbAttachmentManualCheck();
                }
            }
        },
    });
}
function initTbAttachmentCheck(){
    console.log($(el.currencyCode).combobox('getValue'))
    if (!$(el.currencyCode).combobox('getValue')){
        return false;
    }
    let toolbar = [];
    var attachmentTypeCreateConfigList = $(el.currencyCode).combobox('getValue') === "CNY"?eval(attachmentTypeCreateConfigs):eval(overseasAttachmentTypeCreateConfigs);
    if ($(el.supplierCode).textbox('getValue')==='9999'){
        attachmentTypeCreateConfigList = eval(correlationAttachmentTypeCreateConfigs);
    }
    if ($(el.supplierGroup).val()==='Z001'){
        attachmentTypeCreateConfigList = [];
    }
    let columns = [
        {
            field: 'deliveryOrderNo', title: "送货单号", sortable: true,width: attachmentTypeCreateConfigList.length>1?50:100
        }
    ];
    attachmentTypeCreateConfigList.forEach(function (attachmentTypeCreateConfig) {
        columns.push(
            {
                field: attachmentTypeCreateConfig.code, title: attachmentTypeCreateConfig.name, width: attachmentTypeCreateConfigList.length>1?50:100,sortable: true,
                formatter: function (value) {
                    if (value===1) {
                        return '<span style="color:green;">存在</span>';
                    }else if (value===0) {
                        return '<span style="color:red;">不存在</span>';
                    }else{
                        return '<span style="color:green;">无需校验</span>';
                    }
                }
            }
        );
    });
    columns.push(
        {
            field: 'satisfyFlag', title: "是否满足", width: attachmentTypeCreateConfigList.length>1?50:100,sortable: true,
            formatter: function (value) {
                if (value===1) {
                    return '<span style="color:green;">满足</span>';
                }
                return '<span style="color:red;">不满足</span>';
            }
        }
    )
    $(el.tbAttachmentCheck).datagrid({
        loadMsg: '数据加载中......',
        height: '460px',
        width: '98%',
        pagination: true,
        autoRowHeight: true,
        remoteSort:false,
        fitColumns: true,
        checkbox: true,
        rownumbers: false,
        singleSelect: true,
        columns: [columns],
        toolbar: toolbar,
    });
}
function initTbAttachmentManualCheck(){
    let toolbar = [];
    $(el.tbAttachmentManualCheck).datagrid({
        loadMsg: '数据加载中......',
        // url: g.ctx + 'pc/finance/attachment/manual/check/rest/list',
        // queryParams: {
        //     businessType: 0,
        //     currencyCode: $(el.currencyCode).combobox('getValue'),
        //     paymentWay: $(el.paymentWay).combobox('getValue'),
        //     businessId: $(el.id).val(),
        //     businessCode: $(el.accountStatementNo).textbox('getValue')
        // },
        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) {
                    var html = '<span style="color:red;">缺失</span>';
                    for(var i = 0; i < el.attachmentTypeCreateConfigManualList.length; i++){
                        if (el.attachmentTypeCreateConfigManualList[i].type === row.type) {
                            if (el.attachmentTypeCreateConfigManualList[i].sysCheck===1){
                                html =  '<span style="color:green;">齐全</span>';
                                break;
                            }
                        }
                    }
                    return html;
                }
            },
            {
                field: 'manualCheck',
                title: "人工检查",
                sortable: true,
                width: 200,
                formatter: function (value, row, index) {
                    if (isBlank(row.id)){
                        var sysCheck = 0;
                        for(var i = 0; i < el.attachmentTypeCreateConfigManualList.length; i++){
                            if (el.attachmentTypeCreateConfigManualList[i].type === row.type) {
                                if (el.attachmentTypeCreateConfigManualList[i].sysCheck===1){
                                    sysCheck =  1;
                                    break;
                                }
                            }
                        }
                        if (sysCheck===1){
                            return '<span style="color:green;">齐全</span>';
                        }
                    }

                    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,
        onClickRow: function (index, row) {
            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;
                for(var i = 0; i < el.attachmentTypeCreateConfigManualList.length; i++){
                    if (el.attachmentTypeCreateConfigManualList[i].type === data.rows[ii].type) {
                        if (el.attachmentTypeCreateConfigManualList[i].sysCheck===1){
                            sysCheck =1;
                            break;
                        }
                    }
                }
                if (isBlank(data.rows[ii].id)&&sysCheck===1){
                    $(el.tbAttachmentManualCheck).datagrid('updateRow', {
                        index: ii,
                        row: {
                            manualCheck: sysCheck
                        }
                    });
                }
                $(el.tbAttachmentManualCheck).datagrid('updateRow', {
                    index: ii,
                    row: {
                        sysCheck: sysCheck
                    }
                });
            }
            reloadReturnOrderRow(data.rows);
        }
    });
}

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 remarkAttachmentFile() {
    let rows = $(el.tbAttachment).datagrid("getChecked");
    if (rows.length > 0) {
        let selectedRow = rows[0];
        topWin.layer.prompt({
            formType: 2, value: '', title: '请输入备注',
        }, async function (value, index) {
            if(optType === 0 || optType === 5) {
                let allData = $(el.tbAttachment).datagrid("getData").rows;
                allData = await getAllBusinessData(allData);
                allData.forEach(row => {
                    if (row.fileId === selectedRow.fileId) {
                        row.remark = value;
                    }
                });
                $(el.tbAttachment).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.tbAttachment).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 initTbApproveLog() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;

    $(el.tbApproveLog).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'pc/finance/account/statement/detail/rest/find/as/approve/log',
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: true,
        queryParams: {
            asId: $(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 iniTtbLog() {
    const dataDivHeight = $(el.dataDiv).outerHeight();
    $(el.tbLog).datagrid({
        loadMsg: '数据加载中......',
        url: optType === 0? null : g.ctx + 'pc/finance/finPaymentConfirmLog/rest/list',
        height: el.bodyHeight - dataDivHeight,
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        pagination: true,
        showFooter: true,
        queryParams: {
            paymentId: $(el.id).val()
        },
        columns: [
            [
                {
                    field: 'warnMessage',
                    title: '警告消息',
                    width: 1000
                },
                {
                    field: 'userName',
                    title: '操作人',
                    width: 80
                },
                {
                    field: 'confirmAction',
                    title: '操作动作',
                    width: 80,
                    formatter: function (value) {
                        if (value === "CONFIRM") {
                            return "确认";
                        } else if (value === "CANCEL") {
                            return "取消";
                        } else {
                            return "";
                        }
                    }
                },
                {
                    field: 'createdTime',
                    title: '操作时间',
                    width: 150
                }
            ]
        ]
    });
}
/**
 * 获取凭证数据
 */
function getVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,purchaseGroup,poType,taxCode,voucherType,businessFalg) {
    if(!supplierCode){
        topWin.layer.alert('请选择供应商信息', {icon: 0});
        return false;
    }

    if(!currencyCode){
        topWin.layer.alert('请选择币种', {icon: 0});
        return false;
    }

    if(!companyCode){
        topWin.layer.alert('请选择采购公司', {icon: 0});
        return false;
    }

    if(!factoryCode){
        topWin.layer.alert('请选择工厂', {icon: 0});
        return false;
    }

    if(!inStockStartDate){
        topWin.layer.alert('请选择入库开始时间', {icon: 0});
        return false;
    }

    if(!inStockEndDate){
        topWin.layer.alert('请选择入库结束时间', {icon: 0});
        return false;
    }
    if(!voucherType){
        topWin.layer.alert('请选择凭证类型', {icon: 0});
        return false;
    }
    // if (!purchaseGroup) {
    //     topWin.layer.alert('请选择采购组', {icon: 0});
    //     return false;
    // }
    if(!taxCode){
        topWin.layer.alert('请选择税率', {icon: 0});
        return false;
    }

    if(moment(inStockStartDate) > moment(inStockEndDate)){
        topWin.layer.alert('入库开始时间不能大于结束时间', {icon: 0});
        return false;
    }
    // 3.获取入库凭证数据
    findVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,'',poType,taxCode,voucherType,businessFalg);
    // findDeductionData(companyCode, supplierCode, inStockStartDate, inStockEndDate);
}

/**
 * 获取入库明细数据
 *
 * @param companyCode 公司编码
 * @param factoryCode 工厂编码
 * @param supplierCode 供应商编码
 * @param currencyCode 货币代码
 * @param inStockStartDate 入库开始时间
 * @param inStockEndDate 入库结束时间
 */
function findVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,purchaseGroup,poType,taxCode,voucherType,businessFalg) {
    var queryParams = $(el.tbDetails).datagrid('options').queryParams;
    queryParams.supplierCode = supplierCode;
    if (Number(voucherType)===1){
        queryParams.companyCode = companyCode;
    }else {
        queryParams.companyCode = '';
    }
    queryParams.factoryCode = factoryCode;
    queryParams.currencyCode = currencyCode;
    queryParams.postTimeStart = inStockStartDate;
    queryParams.postTimeEnd = inStockEndDate;
    // queryParams.purchaseGroup = purchaseGroup;
    queryParams.poTypes = poType;
    queryParams.receiveType = $(el.orderType).val();
    queryParams.taxCode = taxCode;
    if (Number(voucherType)===1||Number(voucherType)===2){
        queryParams.voucherTypes = voucherType+',3';
    }else {
        queryParams.voucherType = voucherType;
    }

    // queryParams.paymentTermCode = $(el.paymentTermCode).val();
    queryParams.accountStatementFlag = 1;
    queryParams.businessFalg = businessFalg;
    $(el.tbDetails).datagrid('options').loadFilter = pagerFilter;
    $(el.tbDetails).datagrid('options').url = g.ctx + 'pc/finance/receipt/voucher/rest/provide/create/statement';
    $(el.tbDetails).datagrid('load');

    //获取凭证的第一条记录的报关公司
    var detail = el.originalRows, statementItem = [];

    var supplierCode2 = $(el.supplierCode2).combobox('getValue');
    debugger
    for(var i = 0; i < detail.length; i++){
        //报关公司校验，如果是外币，且报关公司为空，取第一条报关公司赋值。
        if (currencyCode == 'USD' && !supplierCode2 && detail[i].supplierName2) {
            $(el.supplierCode2).combobox('setValue',detail[i].supplierCode2);
            $(el.supplierName2).val(detail[i].supplierName2);
            break;
        }
    }


    payableOutstanding();
    // $(el.tbDetails).datagrid({ loadFilter: pagerFilter }).datagrid({
    //     url: g.ctx + 'pc/finance/receipt/voucher/rest/provide/create/statement',
    // });

}

/**
 * 入库明细全选
 */
function detailSelectAll() {
    $(el.tbDetails).datagrid('selectAll');
    var dataRows = $(el.tbDetails).datagrid('getRows');
    calculationAmount(dataRows);
}


/**
 * 入库明细取消全选
 */
function cancelSelectAll() {
    $(el.tbDetails).datagrid('unselectAll');
    var rows = $(el.tbDetails).datagrid('getSelections');
    calculationAmount(rows);
}

/**
 * 入库明细导出
 */
function detailExport() {

    var rows = $(el.tbDetails).datagrid('getRows');
// // 遍历每一行数据，对金额字段进行四舍五入处理
//     $.each(rows, function(index, row) {
//         var
//             notTaxAmount = new BigNumber(0),
//             diffTaxAmount = new BigNumber(0),
//             taxAmount = new BigNumber(0);
//         if (row.notTaxAmount !== undefined && row.notTaxAmount !== null) {//对账未税金额 notTaxAmount 一致
//             row.notTaxAmount = notTaxAmount.plus(row.notTaxAmount).toFormat(2);
//         }
//         if (row.diffTaxAmount !== undefined && row.diffTaxAmount !== null) {//对账税额 diffTaxAmount 一致
//             row.diffTaxAmount = diffTaxAmount.plus(row.diffTaxAmount).toFormat(2);
//         }
//         if (row.taxAmount !== undefined && row.taxAmount !== null) {// 对账含税金额 taxAmount 一致
//             row.taxAmount = taxAmount.plus(row.taxAmount).toFormat(2);
//         }
//     });
//    // 对账含税金额  taxAmount  对账税额 diffTaxAmount
//
//     var footers = $(el.tbDetails).datagrid('getFooterRows');
//     var taxAmountSum = new BigNumber(0),
//         diffTaxAmountSum = new BigNumber(0);
//     var taxAmount = footers[0]['taxAmount'];
//     var diffTaxAmount = footers[0]['diffTaxAmount'];
//     footers[0]['taxAmount'] = taxAmountSum.plus(taxAmount).toFormat(2);
//     footers[0]['diffTaxAmount']= diffTaxAmountSum.plus(diffTaxAmount).toFormat(2);

    $(el.tbDetails).datagrid('toExcel', {
        filename: '入库明细数据.xls',
        rows: rows,
        worksheet: '入库明细'
    });
}

function detailRelationFileExport() {

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


/**
 * 获取凭证数据
 */
function addVoucherData() {
    var companyCode = $(el.companyCode).val(), factoryCode = $(el.factoryCode).val(), currencyCode = $(el.currencyCode).val(),
        supplierCode = $(el.supplierCode).val(), inStockStartDate = $(el.inStockStartDate).datebox('getValue'),
        purchaseGroup = $('#purchaseGroup').val(), taxCode = $(el.taxCode).combobox('getValue'),voucherType = $(el.voucherType).combobox('getValue'),
        poType = getTextByJs($(el.poType).combobox('getValues')),
        inStockEndDate = $(el.inStockEndDate).datebox('getValue'), asNo = $(el.accountStatementNo).textbox('getValue'), orderType = $(el.orderType).val();
    if(!poType){
        topWin.layer.alert('请选择订单类型', {icon: 0});
        return false;
    }
    var rows = $(el.tbDetails).datagrid('getRows'), alreadyExistId = [];
    for(var i = 0; i < rows.length; i++){
        alreadyExistId.push(rows[i].receiveId);
    }

    var url = g.ctx + 'pc/finance/account/statement/chose/voucher/dialog?orderType=' + orderType +
        '&companyCode=' + companyCode + '&factoryCode=' + factoryCode + '&supplierCode=' + supplierCode + '&poType=' + poType + '&taxCode=' + taxCode + '&voucherType=' + voucherType +
        '&currencyCode=' + currencyCode + '&inStockStartDate=' + inStockStartDate +'&purchaseGroup='+purchaseGroup+
        '&inStockEndDate=' + inStockEndDate + '&alreadyExistId=' + alreadyExistId.join(',') +
        '&asId=' + $(el.id).val();

    el.addDetailDialog = openDialog('choseVoucherData', url, {
        title: '选择入库明细',
        width: '80%',
        height: '75%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.addDetailDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseVoucherData'].confirmChose(function (data) {
                        for(var n = 0; n < data.length; n++){
                            var item = data[n], row = {}, vf = item.voucherFlag;
                            row.id = 0;
                            row.asId = $(el.id).val();
                            row.asNo = asNo;
                            row.asQuantity = item.asQuantity;
                            row.diffTaxAmount = item.diffTaxAmount;
                            row.materialCode = item.materialCode;
                            row.materialName = item.materialName;
                            row.materialUnit = item.materialUnit;
                            row.notTaxAmount = item.notTaxAmount;
                            row.taxAmount = item.taxAmount;
                            row.notTaxPrice = item.notTaxPrice;
                            row.taxPrice = item.taxPrice;
                            row.poCode = item.poCode;
                            row.poItemNo = item.poItemNo;
                            row.priceUnit = item.priceUnit;
                            row.taxValue = item.taxValue;
                            row.taxCode = item.taxCode;
                            row.taxDesc = item.taxDesc;
                            row.taxCodeDesc = item.taxCodeDesc;
                            row.receiveCode = item.receiveCode;
                            row.receiveRowNo = item.receiveRowNo;
                            row.receiveDate = item.receiveDate;
                            row.receiveId = item.receiveId;
                            row.receiveNum = item.receiveNum;
                            row.voucherFlag = vf;
                            row.sapMoveType = item.sapMoveType;
                            row.inOutFlag = item.inOutFlag;
                            row.paymentWayCode = item.paymentWayCode;
                            row.paymentWayDesc = item.paymentWayDesc;
                            row.paymentWayCodeDesc = item.paymentWayCodeDesc;
                            row.paymentTermCode = item.paymentTermCode;
                            row.paymentTermName = item.paymentTermName;
                            row.paymentTermCodeName = item.paymentTermCodeName;
                            row.seekPgCode = item.seekPgCode;
                            row.seekPgName = item.seekPgName;
                            row.seekPgCodeName = item.seekPgCodeName;
                            row.invoicedAmount = item.invoicedAmount;
                            row.surplusAmount = item.surplusAmount;
                            row.materialSupplierCode = item.materialSupplierCode;
                            row.materialSupplierName = item.materialSupplierName;
                            row.freightType = item.freightType;
                            row.editFlag = item.editFlag;
                            row.minStatementQuantity = item.minStatementQuantity;
                            row.jcPoCode = item.jcPoCode;
                            row.jcPoItemNo = item.jcPoItemNo;
                            row.jcFactoryCode = item.jcFactoryCode;
                            row.poTypeName = item.poTypeName;

                            $(el.tbDetails).datagrid('appendRow', row);
                        }
                        calculationAmount($(el.tbDetails).datagrid('getRows'));
                        el.addDetailDialog.dialog('close');
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.addDetailDialog.dialog('close');
                }
            }
        ]
    });
}

/**
 * 删除入库凭证数据
 */
function delStatementItem() {
    var rows = $(el.tbDetails).datagrid('getSelections');
    if(rows.length === 0){
        topWin.layer.alert('请选择您要删除的入库明细', {icon: 0});
        return false;
    }

    var surplusReceiveId = [];
    var allRows = $(el.tbDetails).datagrid('getRows');
    for(var n = 0; n < allRows.length; n++){
        surplusReceiveId.push(allRows[n].receiveId);
    }
    for(var m = 0; m < rows.length; m++){
        surplusReceiveId.remove(rows[m].receiveId);
    }

    if(surplusReceiveId.length === 0){
        topWin.layer.alert('明细不能全部删除', {icon: 0});
        return false;
    }

    // 校验选中的行是否可以删除
    var loading = topWin.layer.msg('校验选中的行是否可以删除, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/finance/receipt/voucher/rest/check/write/off',
        data: {
            supplierCode: $(el.supplierCode).textbox('getValue'),
            rvIds: JSON.stringify(surplusReceiveId),
            receiveType: $(el.orderType).val()
        },
        success: function () {
            topWin.layer.close(loading);
            topWin.layer.msg('删除成功', {icon: 1});

            for(var i = 0; i < rows.length; i++){
                var item = rows[i];

                // 入库明细ID为0表示手动添加的
                if(0 !== item.id){
                    el.delDetail.push(item);
                }
                var rowIndex = $(el.tbDetails).datagrid('getRowIndex', item);
                $(el.tbDetails).datagrid('deleteRow', rowIndex);
            }

            var dataRows = $(el.tbDetails).datagrid('getRows');
            calculationAmount(dataRows);
        },
        error: function (data) {
            topWin.layer.close(loading);
            var message = "以下入库凭证不能删除(原因:删除的凭证存在冲销的凭证仍然在明细中): </br>";
            topWin.layer.alert(message + data.responseJSON.message, {icon: 2});
        }
    });
}

function payableOutstanding() {

    var companyCode = $(el.companyCode).combobox('getValue');
    var  supplierCode = $(el.supplierCode).textbox('getValue');
    var  currencyCode = $(el.currencyCode).combobox('getValue');
    var  inStockEndDate = $(el.inStockEndDate).datebox('getValue');

    if(companyCode==''||supplierCode==''||currencyCode==''){
        topWin.layer.alert('请检查“公司”、“供应商”、“币种”是否已选', {icon: 0});
        return false;
    }
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/finance/account/statement/rest/payableOutstanding',
        async: false,
        data: {
            companyCode: companyCode,
            supplierCode: supplierCode,
            inStockEndDate: inStockEndDate,
            currency:currencyCode
        },
        success: function (data) {

            // $(el.localCurrency).textbox('setValue',formatterPrice(new BigNumber(data.AP_DMBTR)));
            $(el.originalCurrency).textbox('setValue',formatterPrice(new BigNumber(data.AP_WRBTR)));
            $(el.ledgerAccount).textbox('setValue',data.HKONT);
            $(el.ledgerAccountName).textbox('setValue',data.TXT20);
            // $(el.advanceLocalCurrency).textbox('setValue',new BigNumber(data.ppDmbtr).toFormat(2));
            // $(el.advanceOriginalCurrency).textbox('setValue',new BigNumber(data.ppWrbtr).toFormat(2));
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });


}
/**
 * 删除
 */
function remove(){
    var rows = $(el.tbDetails).datagrid('getSelections');
    if(rows.length === 0){
        topWin.layer.alert('请选中一条记录', {icon: 0});
        return false;
    }
    for(var i = 0; i < rows.length; i++){
        // el.removeList.push(rows[i].receiveCode+'_'+rows[i].receiveRowNo);
        el.removeList.push(rows[i].receiveId);
    }
    parent.layer.confirm('是否确认设置不参与？', function (index) {
        var queryParams = $(el.tbDetails).datagrid('options').queryParams;
        if (optType===1){
            queryParams.asId = $(el.id).val();
            queryParams.removeLists = el.removeList.join(',');
            queryParams.factoryCode = $(el.factoryCode).combobox('getValue');
            $(el.tbDetails).datagrid('options').url = g.ctx + 'pc/finance/account/statement/detail/rest/find/by/statement/id/factoryCode';
            $(el.tbDetails).datagrid('load');
            parent.layer.close(index);
            if (el.filterFlag){
                $(el.tbDetails).datagrid('enableFilter');
                $('.datagrid-htable .datagrid-filter-c input').attr('AutoComplete','off')
            }
        }
        if (optType===0){
            var companyCode = $(el.companyCode).combobox('getValue'), factoryCode = $(el.factoryCode).combobox('getValue'), taxCode = $(el.taxCode).combobox('getValue'),
                inStockStartDate = $(el.inStockStartDate).datebox('getValue'), inStockEndDate = $(el.inStockEndDate).datebox('getValue'),
                currencyCode = $(el.currencyCode).combobox('getValue'), supplierCode = $(el.supplierCode).textbox('getValue'),
                poType = getTextByJs($(el.poType).combobox('getValues')),
                voucherType = $(el.voucherType).combobox('getValues'),
                purchaseGroup = $('#purchaseGroup').combobox('getValue');
            if(!supplierCode){
                topWin.layer.alert('请选择供应商信息', {icon: 0});
                return false;
            }

            if(!currencyCode){
                topWin.layer.alert('请选择币种', {icon: 0});
                return false;
            }

            if(!companyCode){
                topWin.layer.alert('请选择采购公司', {icon: 0});
                return false;
            }

            if(!factoryCode){
                topWin.layer.alert('请选择工厂', {icon: 0});
                return false;
            }

            if(!inStockStartDate){
                topWin.layer.alert('请选择入库开始时间', {icon: 0});
                return false;
            }

            if(!inStockEndDate){
                topWin.layer.alert('请选择入库结束时间', {icon: 0});
                return false;
            }
            if(!voucherType){
                topWin.layer.alert('请选择凭证类型', {icon: 0});
                return false;
            }
            if(!taxCode){
                topWin.layer.alert('请选择税率', {icon: 0});
                return false;
            }

            if(moment(inStockStartDate) > moment(inStockEndDate)){
                topWin.layer.alert('入库开始时间不能大于结束时间', {icon: 0});
                return false;
            }
            queryParams.supplierCode = supplierCode;
            if (Number(voucherType)===1){
                queryParams.companyCode = companyCode;
            }
            queryParams.factoryCode = factoryCode;
            queryParams.currencyCode = currencyCode;
            queryParams.postTimeStart = inStockStartDate;
            queryParams.postTimeEnd = inStockEndDate;
            // queryParams.purchaseGroup = purchaseGroup;
            queryParams.poTypes = poType;
            queryParams.receiveType = $(el.orderType).val();
            queryParams.taxCode = taxCode;
            if (Number(voucherType)===1||Number(voucherType)===2){
                queryParams.voucherTypes = voucherType+',3';
            }else {
                queryParams.voucherType = voucherType;
            }
            queryParams.removeLists = el.removeList.join(',');
            queryParams.businessFalg = businessFalg;
            // queryParams.paymentTermCode = $(el.paymentTermCode).val();
            queryParams.accountStatementFlag = 1;
            $(el.tbDetails).datagrid('options').loadFilter = pagerFilter;
            $(el.tbDetails).datagrid('options').url = g.ctx + 'pc/finance/receipt/voucher/rest/provide/create/statement';
            $(el.tbDetails).datagrid('load');
            parent.layer.close(index);
            if (el.filterFlag){
                $(el.tbDetails).datagrid('enableFilter');
                $('.datagrid-htable .datagrid-filter-c input').attr('AutoComplete','off')
            }
        }
        // var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        // $.ajax({
        //     url: g.ctx + 'pc/inquiry/rest/remove',
        //     method: "post",
        //     data: {id: id},
        //     success: function () {
        //         parent.layer.close(index);
        //         $(el.tb).datagrid('reload');
        //         $(el.tb).datagrid('clearSelections');
        //     },
        //     complete: function(data) {
        //         top.layer.close(loading);
        //     },
        //     error: function (data) {
        //         parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        //     }
        // });
    });
}
function updateOther(){
    var rows = $(el.tbDetails).datagrid('getSelections');
    if (rows.length <= 0) {
        layer.msg("请选择需要修改的数据");
        return;
    }
    var receiveIds = [];
    var asItemIds = [];
    var url = '';
    //如果是新增，只修改物料凭证
    if (optType===0){
        $.each(rows, function (idx, itm) {
            asItemIds.push(itm.receiveId);
        })
        url = g.ctx+"pc/finance/receipt/voucher/rest/updateRatio";
    }
    if (optType!==0){
        $.each(rows, function (idx, itm) {
            receiveIds.push(itm.receiveId);
            asItemIds.push(itm.id);
        })
        url = g.ctx+"pc/finance/account/statement/detail/rest/updatePrice?ids=" + asItemIds.join(",")+'&receiveIds='+ receiveIds.join(",");
    }
    var updateRatioDialog = openDialog("updateRatioDialog", g.ctx+"pc/finance/receipt/voucher/updateRatioPage?ids=" + receiveIds.join(","), {
        title: '修改其他折扣',
        width: 400,
        height: '300',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            updateRatioDialog.dialog('destroy');
        },
        buttons: [{
            text: '确定',
            iconCls: 'icon-save',
            handler: function () {
                topWin.frames['updateRatioDialog'].page.getData((deductionRatio) => {
                    var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
                    $.ajax({
                        url: url,
                        method: "POST",
                        data: {deductionRatio:deductionRatio,ids:asItemIds.join(","),receiveIds:receiveIds.join(","),asId:$(el.id).val()},
                        success: function (data) {
                            topWin.layer.alert("修改成功", {icon: 1}, function (idx) {
                                topWin.layer.close(idx);
                                if (optType===0){
                                    var companyCode = $(el.companyCode).combobox('getValue'), factoryCode = $(el.factoryCode).combobox('getValue'), taxCode = $(el.taxCode).combobox('getValue'),
                                        inStockStartDate = $(el.inStockStartDate).datebox('getValue'), inStockEndDate = $(el.inStockEndDate).datebox('getValue'),
                                        currencyCode = $(el.currencyCode).combobox('getValue'), supplierCode = $(el.supplierCode).textbox('getValue'),
                                        poType = getTextByJs($(el.poType).combobox('getValues')),
                                        voucherType = $(el.voucherType).combobox('getValues'),
                                        purchaseGroup = $('#purchaseGroup').combobox('getValue');
                                    getVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,purchaseGroup,poType,taxCode,voucherType,businessFalg);
                                }else {
                                    $(el.tbDetails).datagrid('reload');
                                }

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

            }
        }, {
            text: '关闭',
            iconCls: 'icon-cancel',
            handler: function () {
                updateRatioDialog.dialog('close');
            }
        }]
    });
}

//取消折扣信息
function rebackDiscount(){
    var rows = $(el.tbDetails).datagrid('getSelections');
    if (rows.length <= 0) {
        layer.msg("请选择需要取消的凭证的数据!");
        return;
    }

    var receiveIds = [];
    var asItemIds = [];
    var url = '';
    //如果是新增，只修改物料凭证
    if (optType===0){
        $.each(rows, function (idx, itm) {
            asItemIds.push(itm.receiveId);
        })
        url = g.ctx+"pc/finance/receipt/voucher/rest/updateRatio";
    }
    if (optType!==0){
        layer.msg("只有新增对账单才可取消折扣信息!");
        return;
        $.each(rows, function (idx, itm) {
            receiveIds.push(itm.receiveId);
            asItemIds.push(itm.id);
        })
        url = g.ctx+"pc/finance/account/statement/detail/rest/updatePrice?ids=" + asItemIds.join(",")+'&receiveIds='+ receiveIds.join(",");
    }

    let title;
    if (optType===0) {
        title = "您确定要取消当前折扣信息?";
    } else {
        title ="您确定要取消当前折扣信息?"
    }
    topWin.layer.confirm(title, {icon: 3}, function (index) {
        var loading = topWin.layer.msg('折扣信息取消中......', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: url,
            method: "POST",
            // data: {ids:asItemIds.join(","),receiveIds:receiveIds.join(","),asId:$(el.id).val()},
            data: {deductionRatio:0,ids:asItemIds.join(","),receiveIds:receiveIds.join(","),asId:$(el.id).val()},
            success: function (data) {
                topWin.layer.alert("取消成功", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    if (optType===0){
                        var companyCode = $(el.companyCode).combobox('getValue'), factoryCode = $(el.factoryCode).combobox('getValue'), taxCode = $(el.taxCode).combobox('getValue'),
                            inStockStartDate = $(el.inStockStartDate).datebox('getValue'), inStockEndDate = $(el.inStockEndDate).datebox('getValue'),
                            currencyCode = $(el.currencyCode).combobox('getValue'), supplierCode = $(el.supplierCode).textbox('getValue'),
                            poType = getTextByJs($(el.poType).combobox('getValues')),
                            voucherType = $(el.voucherType).combobox('getValues'),
                            purchaseGroup = $('#purchaseGroup').combobox('getValue');
                        getVoucherData(companyCode, factoryCode, supplierCode, currencyCode, inStockStartDate, inStockEndDate,purchaseGroup,poType,taxCode,voucherType,businessFalg);
                    } else {
                        $(el.tbDetails).datagrid('reload');
                    }
                });
            },
            complete: function(data) {
                topWin.layer.close(loading);
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}

/**
 * 导入
 */
function importTaxPriceExcel() {
    var queryParams = {};
    var exportUrl = {};
    if (optType===0){
        var companyCode = $(el.companyCode).combobox('getValue'), factoryCode = $(el.factoryCode).combobox('getValue'), taxCode = $(el.taxCode).combobox('getValue'),
            inStockStartDate = $(el.inStockStartDate).datebox('getValue'), inStockEndDate = $(el.inStockEndDate).datebox('getValue'),
            currencyCode = $(el.currencyCode).combobox('getValue'), supplierCode = $(el.supplierCode).textbox('getValue'),
            poType = getTextByJs($(el.poType).combobox('getValues')),
            voucherType = $(el.voucherType).combobox('getValues'),
            purchaseGroup = $('#purchaseGroup').combobox('getValue');
        if(!supplierCode){
            topWin.layer.alert('请选择供应商信息', {icon: 0});
            return false;
        }

        if(!currencyCode){
            topWin.layer.alert('请选择币种', {icon: 0});
            return false;
        }

        if(!companyCode){
            topWin.layer.alert('请选择采购公司', {icon: 0});
            return false;
        }

        if(!factoryCode){
            topWin.layer.alert('请选择工厂', {icon: 0});
            return false;
        }

        if(!inStockStartDate){
            topWin.layer.alert('请选择入库开始时间', {icon: 0});
            return false;
        }

        if(!inStockEndDate){
            topWin.layer.alert('请选择入库结束时间', {icon: 0});
            return false;
        }
        if(!voucherType){
            topWin.layer.alert('请选择凭证类型', {icon: 0});
            return false;
        }
        if(!taxCode){
            topWin.layer.alert('请选择税率', {icon: 0});
            return false;
        }

        if(moment(inStockStartDate) > moment(inStockEndDate)){
            topWin.layer.alert('入库开始时间不能大于结束时间', {icon: 0});
            return false;
        }
        queryParams.supplierCode = supplierCode;
        queryParams.companyCode = companyCode;
        queryParams.factoryCode = factoryCode;
        queryParams.currencyCode = currencyCode;
        queryParams.postTimeStart = inStockStartDate;
        queryParams.postTimeEnd = inStockEndDate;
        // queryParams.purchaseGroup = purchaseGroup;
        queryParams.poTypes = poType;
        queryParams.receiveType = $(el.orderType).val();
        queryParams.taxCode = taxCode;
        if (Number(voucherType)===1||Number(voucherType)===2){
            queryParams.voucherTypes = voucherType+',3';
        }else {
            queryParams.voucherType = voucherType;
        }
        // queryParams.paymentTermCode = $(el.paymentTermCode).val();
        queryParams.accountStatementFlag = 1;
        exportUrl = 'pc/finance/receipt/voucher/rest/provide/create/statement/export'
    }else {
        var factoryCode = $(el.factoryCode).combobox('getValue');
        if(!factoryCode){
            topWin.layer.alert('请选择工厂', {icon: 0});
            return false;
        }
        queryParams.asId = $(el.id).val();
        queryParams.factoryCode = factoryCode;
        exportUrl = 'pc/finance/account/statement/detail/rest/find/by/statement/id/factoryCode/export'
    }
    var importDialog = openQueryImportExcelDialog(exportUrl,queryParams,'导入其他折扣',function(file){
        let formData = new FormData();
        formData.append("file", file);
        var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/finance/account/statement/detail/rest/price/import',
            method: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: function (data) {
                topWin.layer.alert("导入成功", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    $(el.tb).datagrid('reload');
                    importDialog.dialog('close');
                });
            },
            complete: function(data) {
                topWin.layer.close(loading);
            },
            error: function (data) {
                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
}

/**
 * 初始化页面输入框
 */
function initPageInput() {
    var isSupplier = $(el.isSupplier).val();
    var companyDataUrl = g.ctx + 'pc/sys/company/rest/listAll';

    // 初始化工厂代码下拉框
    $(el.factoryCode).combobox({
        url: g.ctx + 'pc/sys/factory/rest/listAll',
        editable: false,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        panelHeight: 'auto'
    });
    //采购组
    //采购组
    $(el.purchaseGroup).combobox({
        required: true,
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll?isAuthority='+(Number(isSupplier) === 0?'1':''),
        // onChange: function (data) {
        //     var oriCc = $(el.purchaseGroup).combobox('getValue');
        //     if(oriCc !== data.code){
        //         clearPageTableData();
        //     }
        // }
    });

    // 初始化公司代码下拉框
    $(el.companyCode).combobox({
        required: true,
        url: companyDataUrl,
        panelHeight: 'auto',
        valueField: 'companyCode',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        onSelect: function (data) {
            var oriCc = $(el.companyCode).combobox('getValue');
            if(oriCc !== data.companyCode){
                clearPageTableData();
                if (optType===1){
                    findSupplierPurchaseByCompanyCode(data.companyCode, $(el.supplierCode).textbox('getValue'));
                }
            }

            $(el.companyName).val(data.companyName);
            findFactoryDataByCompanyCode(data.companyCode, isSupplier);
            if (optType===0){
                findSupplierPurchaseByCompanyCode(data.companyCode, $(el.supplierCode).textbox('getValue'));
            }
        }
    });
    $(el.currencyCode).combobox({
        url: g.ctx + 'pc/sys/dict/getDicByType?type=currency',
        panelHeight: 'auto',
        limitToList: 'true',
        prompt: '-- 请选择 --',
        method: 'GET',
        valueField: 'code',
        textField: 'codeWithDesc',
        editable: false,
        onSelect: function (data) {
            getExchangeRate(data.code);
            clearPageTableData();
        },
        // onLoadSuccess: function () { //加载完成后,设置选中第一项
        //     var val = $(this).combobox("getData");
        //     for (var item in val[0]) {
        //         if (item === "code") {
        //             $(this).combobox("select", val[0][item]);
        //             getExchangeRate(val[0][item]);
        //         }
        //     }
        // }
    });
    if(Number(isSupplier) === 0){
        $(el.supplierCode).textbox({
            prompt: '请选择供应商',
            required: true,
            icons: [
                {
                    iconCls: 'icon-search',
                    handler: function () {
                        choseSupplier();
                    }
                }
            ]
        });
        $(el.supplierCode).textbox('textbox').css('cursor', 'pointer');
        $(el.supplierCode).textbox('textbox').bind('click', function () {
            choseSupplier();
        });
    }else{
        if (optType===0 || optType===1){
            const supplierCode = $(el.supplierCode).val();
            if (supplierCode!=='9999'){
                accountDateCheck();
            }
        }
    }
    $(el.supplierCode2).combobox({
        required: false,
        url: g.ctx + 'pc/sys/dict/getDicByType?type=customs_broker',
        method: 'GET',
        valueField: 'code',
        textField: 'name',
        prompt: '--- 请选择 ---',
        editable: false,
        onSelect: function (data) {
            //报关公司设置，如果是人民币，报关公司不可选择，且不可编辑。  如果是非人民币，不变。
            if ($(el.currencyCode).val() == "CNY") {
                $(el.supplierCode2).combobox('setValue','');
                $(el.supplierName2).val('');
                $(el.supplierCode2).combobox('disable');
            } else {
                $(el.supplierCode2).combobox('enable');
                $(el.supplierName2).val(data.name);
            }
        }
    });

    if (optType===0){
        // 初始化入库凭证开始日期
        $(el.inStockStartDate).datebox({
            value: moment(new Date()).subtract(1, 'months').startOf('month').format("YYYY-MM-DD"),
            onSelect: function(date){
                var curr = $(this).datebox('getValue'), update = moment(date).format("YYYY-MM-DD");
                if(curr !== update){
                    clearPageTableData();
                }
            }
        });

        // 初始化入库凭证结束日期
        $(el.inStockEndDate).datebox({
            value: moment(new Date()).subtract(1, 'months').endOf('month').format("YYYY-MM-DD"),
            onSelect: function(date){
                var curr = $(this).datebox('getValue'), update = moment(date).format("YYYY-MM-DD");
                $(el.accountStatementMonth).combobox('setValue', moment(date).format("MM"))
                if(curr !== update){
                    clearPageTableData();
                }
            }
        });
    }


    // 凭证类型
    $(el.voucherType).combobox({
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        required: true,
        data: [
            {'name': '材料', 'code': '1'},
            {'name': '寄售', 'code': '2'}
            // {'name': '其他', 'code': '3'}
        ],
        editable: true,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
        onSelect: function (data) {
            var oriCc = $(el.voucherType).combobox('getValue');
            if(oriCc !== data.code){
                clearPageTableData();
            }
            if(Number(data.code)===2){
                $(el.poType).combobox({ disabled: true});
            }else {
                $(el.poType).combobox({ disabled: false});
            }
        }
    });

    // 税率
    $(el.taxCode).combobox({
        required: true,
        panelHeight: 'auto',
        panelWidth: 200,
        limitToList: 'true',
        valueField: 'taxCode',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/tax/rest/listAll',
        onChange: function (data) {
            var oriCc = $(el.taxCode).combobox('getValue');
            if(oriCc !== data.taxCode){
                clearPageTableData();
            }
            $(el.tbDetails).datagrid('loadData', { total: 0, rows: [] });
            var rows = $(el.tbDetails).datagrid('getSelections');
            calculationAmount(rows);
        }
    });

    $(el.accountStatementYear).combobox({
        required: true,
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': moment().format('YYYY'), 'code': moment().format('YYYY')},
            {'name': moment().add(-12, 'month').format('YYYY'), 'code': moment().add(-12, 'month').format('YYYY')},
            {'name': moment().add(-24, 'month').format('YYYY'), 'code': moment().add(-24, 'month').format('YYYY')},
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });
    $(el.accountStatementMonth).combobox({
        required: true,
        valueField: 'code',
        textField: 'name',
        limitToList: 'true',
        data: [
            {'name': '01', 'code': '01'},
            {'name': '02', 'code': '02'},
            {'name': '03', 'code': '03'},
            {'name': '04', 'code': '04'},
            {'name': '05', 'code': '05'},
            {'name': '06', 'code': '06'},
            {'name': '07', 'code': '07'},
            {'name': '08', 'code': '08'},
            {'name': '09', 'code': '09'},
            {'name': '10', 'code': '10'},
            {'name': '11', 'code': '11'},
            {'name': '12', 'code': '12'},
        ],
        editable: false,
        prompt: '--- 请选择 ---',
        panelHeight: 'auto',
    });

    // 采购组
    $(el.purchaseGroupCode).combobox({
        required: true,
        valueField: 'code',
        textField: 'codeWithDesc',
        method: 'POST',
        // panelHeight: 200,
        // panelWidth: 240,
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll',
        onChange: function (data) {
            var oriCc = $(el.purchaseGroupCode).combobox('getValue');
            if(oriCc !== data.code){
                clearPageTableData();
            }
        }
    });

    // 付款条件
    $(el.paymentTermCode).combobox({
        required: true,
        panelHeight: '200',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        method: 'GET',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_method',
        // onChange: function (data) {
        //     var oriCc = $(el.paymentTermCode).combobox('getValue');
        //     if(oriCc !== data.code){
        //         clearPageTableData();
        //     }
        // }
    });
    // 付款方式
    $(el.paymentWay).combobox({
        required: true,
        panelHeight: '200',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        method: 'GET',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_way'
    });
    // 订单类型
    $(el.poType).combobox({
        panelHeight: 'auto',
        panelWidth: 200,
        valueField: 'code',
        multiple: true,
        method: 'GET',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=po_type',
        icons: [{
            iconCls: 'icon-delete',
            handler: function (e) {
                $(el.poType).combobox('clear');
                $(el.tbDetails).datagrid('loadData', { total: 0, rows: [] });
                var rows = $(el.tbDetails).datagrid('getSelections');
                calculationAmount(rows);
            }
        }],
        onChange: function (data) {
            var oriCc = $(el.poType).combobox('getValue');
            if(oriCc !== data.code){
                clearPageTableData();
            }
            $(el.tbDetails).datagrid('loadData', { total: 0, rows: [] });
            var rows = $(el.tbDetails).datagrid('getSelections');
            calculationAmount(rows);
        },
        // onLoadSuccess: function (record) {
        //     //全选
        //     if (optType===0){
        //         var valueField = $(el.poType).combobox("options").valueField;
        //         var data = $(el.poType).combobox("getData");
        //         var selectVaues = [];
        //         data.reduce(function(prev, current, index, array){
        //             selectVaues.push(current[valueField]);
        //         },selectVaues);
        //         $(el.poType).combobox('setValues', selectVaues);
        //     }
        // }
    });

    $(el.accountImgCode).textbox('textbox').css('cursor', 'pointer').css('color', '#0b94ea');
    $(el.accountImgCode).textbox('textbox').bind('click', function () {
        if(!$(el.accountImgCode).textbox('getValue')) return false;
        showImage($(el.accountImgCode).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 clearPageTableData() {
    $(el.tbDetails).datagrid('loadData', {total: 0, rows: []});

    // 顺便清空页面输入的值
    $(el.bpPayableBalance).textbox('setValue', '');
    $(el.bpEstimateBalance).textbox('setValue', '');
    $(el.etPayableBalance).textbox('setValue', '');
    $(el.etEstimateBalance).textbox('setValue', '');
    $(el.beginPeriodTotal).textbox('setValue', '');
    $(el.endPeriodTotal).textbox('setValue', '');
}

/**
 * 根据公司编码获取工厂代码下拉框数据
 *
 * @param companyCode 公司编码
 * @param isSupplier 是否供应商账号 0:否 1是
 */
function findFactoryDataByCompanyCode(companyCode, isSupplier) {
    var factoryDataUrl = g.ctx + 'pc/sys/factory/rest/listAll';
    $(el.factoryCode).combobox({
        url: factoryDataUrl,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        panelHeight: 300,
        panelWidth: 260,
        disabled: false,
        required: true,
        onLoadSuccess: function(data){
            for (var i = 0; i < data.length; i++) {
                if(data[i].companyCode === companyCode){
                    $(el.factoryCode).combobox('setValue', data[i].code);
                    $(el.factoryName).val(data[i].name);
                }
            }
        },
        onSelect: function (data) {
            var oriFc = $(el.factoryCode).combobox('getValue');
            if(oriFc !== data.code){
                clearPageTableData();
            }

            $(el.factoryName).val(data.name);
        }
    });
}
function findSupplierPurchaseByCompanyCode(companyCode, supplierCode) {
    if (companyCode&&supplierCode){
        $.ajax({
            url: g.ctx + 'pc/supplier/purchaseCategory/rest/getCompanyAndSupplierCode?supplierCode=' + supplierCode + '&companyCode=' + companyCode,
            type: 'GET',
            async: false,
            success: function (res) {
                if (res){
                    $(el.taxCode).combobox('setValue',res.taxCode);
                    $(el.purchaseGroupCode).combobox('setValue',res.purchaseCategoryCode);
                    $(el.paymentTermCode).combobox('setValue',res.paymentTerms);
                    $(el.paymentWay).combobox('setValue',res.paymentMethod);
                }
            }
        });
    }
}

/**
 * 计算页面相关金额
 */
function calculationAmount(rows) {

    var taxAmount = new BigNumber(0), notTaxAmount = new BigNumber(0), invoicedAmount = new BigNumber(0),
        surplusAmount = new BigNumber(0), storageQuantity = new BigNumber(0), statementQuantity = new BigNumber(0);
    for (var j = 0; j < rows.length; j++) {
        var item = rows[j];
        taxAmount = taxAmount.plus(item.taxAmount);
        notTaxAmount = notTaxAmount.plus(item.notTaxAmount);
        invoicedAmount = invoicedAmount.plus(item.invoicedAmount);
        surplusAmount = surplusAmount.plus(item.surplusAmount);
        storageQuantity = storageQuantity.plus(item.receiveNum);
        statementQuantity = statementQuantity.plus(item.asQuantity);
    }

    $(el.taxAmount).textbox('setValue', taxAmount.toFormat(2));
    $(el.notTaxAmount).textbox('setValue',notTaxAmount.toFormat(2));

    if(0 !== rows.length){

        // 更新页脚行的值并刷新
        var footers = $(el.tbDetails).datagrid('getFooterRows');
        footers[0]['taxAmount'] = taxAmount.toFormat(2);
        footers[0]['notTaxAmount'] = notTaxAmount.toFormat(2);
        footers[0]['diffTaxAmount'] = taxAmount.minus(notTaxAmount).toFormat(2);
        footers[0]['invoicedAmount'] = invoicedAmount.toFormat(2);
        footers[0]['surplusAmount'] = surplusAmount.toFormat(2);
        footers[0]['receiveNum'] = storageQuantity.toFixed(3);
        footers[0]['asQuantity'] = statementQuantity.toFixed(3);
        $(el.tbDetails).datagrid('reloadFooter');
    }else {
        // 更新页脚行并载入新数据
        $(el.tbDetails).datagrid('reloadFooter', [
            {
                taxAmount: 0,
                notTaxAmount: 0,
                diffTaxAmount: 0,
                invoicedAmount: 0,
                surplusAmount: 0,
                receiveNum: 0,
                asQuantity: 0
            }
        ]);
    }
}

/**
 * 选择供应商
 */
function choseSupplier() {
    // var url = g.ctx + "pc/supplier/supplierSelect?single=1";
    var url = g.ctx + "pc/supplier/purchaseCategory/page/selector?single=1";
    el.choseSupplierDialog = openDialog('choseSupplier', url, {
        title: '供应商选择',
        width: '80%',
        height: '70%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.choseSupplierDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseSupplier'].chooseRow(function (data) {
                        console.log(data)
                        var oriSupCode = $(el.supplierCode).textbox('getValue');
                        if(oriSupCode !== data[0].supplierCode){
                            clearPageTableData();
                        }
                        $(el.supplierCode).textbox('setValue', data[0].supplierCode);
                        $(el.supplierGroup).val(data[0].supplierGroup);
                        if (optType===0 || optType===1){
                            if (data[0].supplierCode!=='9999'){
                                accountDateCheck();
                            }
                        }
                        $(el.supplierName).textbox('setValue', data[0].supplierName);
                        $(el.currencyCode).combobox('setValue',data[0].currencyCode);
                        //报关公司设置，如果是人民币，报关公司不可选择，且不可编辑。  如果是非人民币，不变。
                        if (data[0].currencyCode == "CNY") {
                            $(el.supplierCode2).combobox('setValue','');
                            $(el.supplierName2).val('');
                            $(el.supplierCode2).combobox('disable');
                        } else {
                            $(el.supplierCode2).combobox('enable');
                        }
                        $(el.companyCode).combobox('setValue',data[0].companyCode);
                        $(el.taxCode).combobox('setValue',data[0].taxCode);
                        $(el.paymentTermCode).combobox('setValue',data[0].paymentTerms);
                        $(el.paymentWay).combobox('setValue',data[0].paymentMethod);
                        $(el.purchaseGroup).combobox('setValue',data[0].purchaseGroupCode);
                        // 销毁现有的物料表格
                        try {
                            $(el.tbAttachmentCheck).datagrid('destroy');
                        } catch (error) {
                            console.warn('发生异常，已忽略:', error.message);
                            // 或发送到错误监控系统
                        }
                        initTbAttachmentCheck();
                        el.choseSupplierDialog.dialog('close');
                        //TODO
                        // initPaymentTermCode(data[0].supplierCode)
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.choseSupplierDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 数据保存
 *
 * @param type 0:暂存 1：提交
 * @param callback 回调函数
 */
async function dataSave(type,callback) {
    var id = $(el.id).val(), files = $(el.files).attr('data-fileIds'),orderType = $(el.orderType).val(), supplierCode = $(el.supplierCode).textbox('getValue'),
        supplierName = $(el.supplierName).textbox('getValue'), currencyCode = $(el.currencyCode).combobox('getValue'),voucherType = $(el.voucherType).combobox('getValue'),
        companyCode = $(el.companyCode).combobox('getValue'), companyName = $(el.companyName).val(),
        factoryCode = $(el.factoryCode).combobox('getValue'), factoryName = $(el.factoryName).val(),
        taxAmount = $(el.taxAmount).textbox('getValue'), notTaxAmount = $(el.notTaxAmount).val(),
        purchaseGroup = $('#purchaseGroup').combobox('getValue'),
        paymentTermCode = $(el.paymentTermCode).combobox('getValue'),
        paymentWay = $(el.paymentWay).combobox('getValue'),
        poType = getTextByJs($(el.poType).combobox('getValues')),
        accountStatementYear = $(el.accountStatementYear).combobox('getValue'),
        accountStatementMonth = $(el.accountStatementMonth).combobox('getValue'),
        deductionAmount = "", rebateAmount = "",
        bpPayableBalance ="", bpEstimateBalance = "",
        etPayableBalance = "", etEstimateBalance = "",
        fileId = $(el.fileId).val(),
        inStockStartDate = $(el.inStockStartDate).datebox('getValue'), inStockEndDate = $(el.inStockEndDate).datebox('getValue'),
        remark = $(el.remark).textbox('getValue'), currPaymentAmount = "",
        // localCurrency = $(el.localCurrency).textbox('getValue'),
        originalCurrency = $(el.originalCurrency).textbox('getValue'),
        // advanceLocalCurrency = $(el.advanceLocalCurrency).textbox('getValue'),
        // advanceOriginalCurrency = $(el.advanceOriginalCurrency).textbox('getValue'),
        ledgerAccount = $(el.ledgerAccount).textbox('getValue'),
        ledgerAccountName = $(el.ledgerAccountName).textbox('getValue'),
        supplierName2 = $(el.supplierName2).val(),
        supplierCode2 = $(el.supplierCode2).combobox('getValue');

    if (optType===0 || optType===1){
        if (supplierCode!=='9999'){
            if (!await accountDateCheck()) return;
        }
    }
    if($.isEmptyObject(originalCurrency)||$.isEmptyObject(ledgerAccount)||$.isEmptyObject(ledgerAccountName)){
        topWin.layer.alert('请获取"应清未付金额"', {icon: 0});
        return false;
    }
    // localCurrency = Number(localCurrency.replace(/,/g,'')),
    originalCurrency = Number(originalCurrency.replace(/,/g,''))
    // advanceLocalCurrency = Number(advanceLocalCurrency.replace(/,/g,'')),
    // advanceOriginalCurrency = Number(advanceOriginalCurrency.replace(/,/g,''))
    ;
    if (!companyCode) {
        topWin.layer.alert('请选择采购公司', {icon: 0});
        return false;
    }
    if (!inStockStartDate) {
        topWin.layer.alert('请选择入库开始日期', {icon: 0});
        return false;
    }
    if (!inStockEndDate) {
        topWin.layer.alert('请选择入库结束日期', {icon: 0});
        return false;
    }
    if (!currencyCode) {
        topWin.layer.alert('请选择币种', {icon: 0});
        return false;
    }
    if (currencyCode!=='CNY'&&!supplierCode2) {
        topWin.layer.alert('请选择报关公司', {icon: 0});
        return false;
    }
    if (!purchaseGroup) {
        topWin.layer.alert('请选择采购组', {icon: 0});
        return false;
    }
    // if (!poType) {
    //     topWin.layer.alert('请选择订单类型', {icon: 0});
    //     return false;
    // }
    if (!voucherType) {
        topWin.layer.alert('请选择凭证类型', {icon: 0});
        return false;
    }
    if (!accountStatementYear) {
        topWin.layer.alert('请选择对账单年份', {icon: 0});
        return false;
    }
    if (!accountStatementMonth) {
        topWin.layer.alert('请选择对账单月份', {icon: 0});
        return false;
    }
    if (!paymentTermCode) {
        topWin.layer.alert('请选择付款条件', {icon: 0});
        return false;
    }
    if (!paymentWay) {
        topWin.layer.alert('请选择付款方式', {icon: 0});
        return false;
    }
    if (currencyCode && currencyCode == 'USD' && (!supplierCode2 || supplierCode2 == '')) {
        topWin.layer.alert('请选择报送公司', {icon: 0});
        return false;
    }

    //报送公司检验


    // if (!remark) {
    //     topWin.layer.alert('请填写备注', {icon: 0});
    //     return false;
    // }
// 入库明细
    // var detail = $(el.tbDetails).datagrid('getOriginalRows'), statementItem = [];
    var detail = el.originalRows, statementItem = [];
    if (detail.length === 0) {
        topWin.layer.alert('请选择入库凭证明细', {icon: 0});
        return false;
    }
    let receiveCode = "", receiveRowNo = "", receiveYear = "", headUpText = "";
    for(let i = 0; i < detail.length; i++){
        if(i !== 0 &&
            receiveCode === detail[i].receiveCode &&
            receiveRowNo === detail[i].receiveRowNo &&
            receiveYear === detail[i].receiveYear){
            topWin.layer.alert("存在重复凭证信息，暂存失败，请确认（入库凭证号："+ receiveCode +"，入库凭证行号："+ receiveRowNo +"，年度："+ receiveYear +"）");
            return false;
        }
        receiveCode = detail[i].receiveCode;
        receiveRowNo = detail[i].receiveRowNo;
        receiveYear = detail[i].receiveYear;
        headUpText = detail[i].headUpText;

        if (!isBlank(detail[i].returnConfirmStatus)){
            if (Number(detail[i].returnConfirmStatus)===1){
                topWin.layer.alert("（入库凭证号："+ receiveCode +"，入库凭证行号："+ receiveRowNo +"，年度："+ receiveYear +"）存在退货未确认的送货单"+headUpText+"，请先完成退货确认");
                return false;
            }
        }
    }
    var headData = {};
    headData.id = id;
    headData.files = files;
    headData.orderType = orderType;
    headData.companyCode = companyCode;
    headData.supplierCode2 = supplierCode2;
    headData.supplierName2 = supplierName2;
    headData.companyName = companyName;
    headData.accountStatementYear = accountStatementYear;
    headData.accountStatementMonth = accountStatementMonth;
    headData.factoryCode = factoryCode;
    headData.factoryName = factoryName;
    headData.inStockStartDate = inStockStartDate;
    headData.inStockEndDate = inStockEndDate;
    headData.currencyCode = currencyCode;
    headData.supplierCode = supplierCode;
    headData.taxCode = $(el.taxCode).combobox('getValue');
    headData.supplierName = supplierName;
    headData.paymentTermCode = paymentTermCode;
    headData.paymentWay = paymentWay;
    headData.voucherType = voucherType;
    headData.poType = poType;
    headData.taxAmount = Number(taxAmount.replace(/,/g,''));
    headData.notTaxAmount = Number(notTaxAmount.replace(/,/g,''));
    headData.deductionAmount = deductionAmount;
    headData.rebateAmount = rebateAmount;
    headData.bpPayableBalance = Number(bpPayableBalance.replace(/,/g,''));
    headData.bpEstimateBalance = Number(bpEstimateBalance.replace(/,/g,''));
    headData.etPayableBalance = Number(etPayableBalance.replace(/,/g,''));
    headData.etEstimateBalance = Number(etEstimateBalance.replace(/,/g,''));
    headData.currPaymentAmount = Number(currPaymentAmount.replace(/,/g,''));
    headData.purchaseGroup = purchaseGroup;
    headData.remark = remark;
    // headData.localCurrency = localCurrency;
    headData.originalCurrency = originalCurrency;
    // headData.advanceLocalCurrency = advanceLocalCurrency;
    // headData.advanceOriginalCurrency = advanceOriginalCurrency;
    headData.ledgerAccount = ledgerAccount;
    headData.ledgerAccountName = ledgerAccountName;
    headData.fileId = fileId;
    headData.paymentExpireDate = detail[0].paymentExpireDate;
    headData.invoicedCode = detail[0].invoicedCode;



    //校验税码和付款条件
    let taxCode = "",payTermCode = "",pgCode = "";
    let supplierName22 ="";
    let supplierCode22 ="";
    var itSumAmount = new BigNumber(0);
    for(var i = 0; i < detail.length; i++){
        if(i !== 0 && taxCode !== detail[i].taxCode){
            layer.msg("所选税率必须一致");
            return false;
        }
        //报关公司校验，如果是外币，报关公司必选，且校验第一条报关公司是否与选择的报关公司一致。
        if (i == 0) {
            if (currencyCode == 'USD' && supplierName2 && detail[0].supplierName2){
                if(supplierName2 !=='中华人民共和国凤岗海关' && supplierName2 !== detail[i].supplierName2) {
                    layer.msg("所选报关公司必须一致");
                    return false;
                }
            }
        }

        // if(i !== 0 && payTermCode !== detail[i].paymentTermCode){
        //     layer.msg("所选付款条件必须一致");
        //     return false;
        // }
        // if(i !== 0 && pgCode !== detail[i].pgCode){
        //     layer.msg("所选采购组必须一致");
        //     return false;
        // }
        taxCode = detail[i].taxCode;
        // if (detail[i].supplierName2){
        //     supplierName22 = detail[i].supplierName2;
        //     supplierCode22 = detail[i].supplierCode2;
        //     headData.supplierCode2 = supplierCode22;
        //     headData.supplierName2 = supplierName22;
        // }

        // payTermCode = detail[i].paymentTermCode;
        pgCode = detail[i].pgCode;
        // headData.purchaseGroup = pgCode;

        var row = detail[i], obj = {};

        obj.asId = id;
        obj.receiveId = row.receiveId;
        obj.receiveCode = row.receiveCode;
        obj.receiveRowNo = row.receiveRowNo;
        obj.receiveNum = row.receiveNum;
        obj.headUpText = row.headUpText;
        obj.asQuantity = row.asQuantity;
        obj.taxCode = row.taxCode;
        obj.taxValue = row.taxValue;
        obj.notTaxPrice = row.notTaxPrice;
        obj.taxPrice = row.taxPrice;
        obj.notTaxAmount = row.notTaxAmount;
        obj.taxAmount = row.taxAmount;
        obj.diffTaxAmount = row.diffTaxAmount;
        obj.priceUnit = row.priceUnit;
        obj.editFlag = row.editFlag;
        obj.minStatementQuantity = row.minStatementQuantity;
        obj.paymentExpireDate = row.paymentExpireDate;
        obj.invoicedCode = row.invoicedCode;
        obj.subjectTypeCode = row.subjectTypeCode;
        obj.rowTypeCode = row.rowTypeCode;
        statementItem.push(obj);

        itSumAmount = itSumAmount.plus(row.taxAmount);
    }

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

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

    // 需要校验凭证汇总含税金额 - (扣款金额 + 返利金额) > 0
    // var diff = itSumAmount.plus(deductionAmount).plus(rebateAmount);
    // if(diff.lt(0)){
    //     topWin.layer.alert('选择入库凭证明细的含税金额汇总小于选择的扣款金额', {icon: 0});
    //     return false;
    // }
    var satisfyFlagExist = false;
    let uploadAttachmentFileDataList = Number(tbAttachmentLookFlag)===1?[]:$(el.tbAttachment).datagrid("getData").rows;
    uploadAttachmentFileDataList = await getAllBusinessData(uploadAttachmentFileDataList);
    uploadAttachmentFileDataList.forEach(item=>{
        if (item.satisfyFlag===0){
            satisfyFlagExist = true;
        }
    })
    if (Number(tbAttachmentLookFlag)!==1&&uploadAttachmentFileDataList.length===0){
        layer.confirm('附件检查中缺少附件,是否继续？', {
            btn: ['确定','取消'] //按钮
        }, function(){
            layer.closeAll()
            dataSaveAjax(headData, statementItem,uploadAttachmentFileDataList,callback);
            return false;
        }, function(){
            layer.closeAll()
            return false;
        });
    }else {
        if (satisfyFlagExist){
            layer.confirm('附件检查中存在附件未满足,是否继续？', {
                btn: ['确定','取消'] //按钮
            }, function(){
                layer.closeAll()
                dataSaveAjax(headData, statementItem,uploadAttachmentFileDataList,callback);
                return false;
            }, function(){
                return false;
            });
        }else {
            dataSaveAjax(headData, statementItem,uploadAttachmentFileDataList,callback);
        }
    }


}


function dataSaveAjax(headData,statementItem,uploadAttachmentFileDataList,callback) {
    let title;
    // if(type === 0){
        title = "您确定要保存对账单?";
    // }else{
    //     title ="您确定要保存对账单,并提交财务确认?"
    // }
    topWin.layer.confirm(title, {icon: 3}, function (index) {
        topWin.layer.close(index);

        var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'pc/finance/account/statement/rest/saveOrUpdate',
            type: 'POST',
            data: {
                optType: optType,
                headData: JSON.stringify(headData),
                statementItem: JSON.stringify(statementItem),
                businessAttachmentItem:  JSON.stringify(uploadAttachmentFileDataList),
                // deductionIds: deductionIds.length === 0 ? '' : JSON.stringify(deductionIds),
                // rebateIds: rebateIds.length === 0 ? '' : JSON.stringify(rebateIds)
            },
            success: function (data) {
                topWin.layer.close(loading);
                callback(data.id);
            },
            error: function (data) {
                topWin.layer.close(loading);
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    });
}

/**
 * 主管确认
 * @param approveStatus 审批结果 0:拒绝 1:同意
 * @param callback 回调函数
 */
async function purchaseSave(callback,approveStatus) {
    var id = $(el.id).val(), remark = $(el.remark).val(), taxAmount = $(el.taxAmount).textbox('getValue'),
        notTaxAmount = $(el.notTaxAmount).val(), deductionAmount = "",
        rebateAmount = "", approveOpinion = $(el.approveOpinion).val(),
        bpPayableBalance = "", bpEstimateBalance = "",
        etPayableBalance = "", etEstimateBalance = "",
        currPaymentAmount = "";
    if(!approveOpinion){
        topWin.layer.alert('请您输入审批意见', {icon: 0});
        return false;
    }
    // if(!remark){
    //     topWin.layer.alert('请您输入备注', {icon: 0});
    //     return false;
    // }


    var headData = {};
    headData.id = id;
    headData.taxAmount = Number(taxAmount.replace(/,/g,''));
    headData.notTaxAmount = Number(notTaxAmount.replace(/,/g,''));
    // headData.deductionAmount = deductionAmount;
    // headData.rebateAmount = rebateAmount;
    headData.remark = remark;
    headData.bpPayableBalance = Number(bpPayableBalance.replace(/,/g,''));
    headData.bpEstimateBalance = Number(bpEstimateBalance.replace(/,/g,''));
    headData.etPayableBalance = Number(etPayableBalance.replace(/,/g,''));
    headData.etEstimateBalance = Number(etEstimateBalance.replace(/,/g,''));
    headData.currPaymentAmount = Number(currPaymentAmount.replace(/,/g,''));

    // 对账单明细
    var detail = $(el.tbDetails).datagrid('getRows'),
        statementItem = [], dsiId = [], taxData = [],paymentTermCode =  [];
    if (detail.length === 0) {
        topWin.layer.alert('入库明细无数据, 请添加', {icon: 0});
        return false;
    }
    for(var i0 = 0; i0 < detail.length; i0++) {
        var ri = $(el.tbDetails).datagrid('getRowIndex', detail[i0]);
        $(el.tbDetails).datagrid('endEdit', ri);
    }

    var itSumAmount = new BigNumber(0);
    for(var i1 = 0; i1 < detail.length; i1++){
        var item = detail[i1];
        // 校验数量不能超过剩余可开票数量: 本次对账确认数量 <= 凭证可用数量
        if(Number(item.asQuantity) > Number(item.surplusNum)){
            topWin.layer.alert('入库凭证: ' + item.receiveCode + '#' + item.receiveRowNo + ', 填写的确认对账数量不能大于可用数量', {icon: 0});
            return false;
        }

        taxData.push(item.taxCode);
        paymentTermCode.push(item.paymentTermCode);
        statementItem.push(item);

        itSumAmount = itSumAmount.plus(item.taxAmount);
    }


    // 检查对账单明细中对账税率是否都相同
    if(!checkIsAllEqual(taxData)){
        topWin.layer.alert('对账单明细中税率不相同', {icon: 0});
        return false;
    }
    // 检查对账单明细中付款条件是否都相同  20240730 财务月底对账，暂不作校验
    if(!checkIsAllEqual(paymentTermCode)){
        //topWin.layer.alert('对账单明细中付款条件不相同', {icon: 0});
        //return false;
    }
    // 明细删除
    for(var i2 = 0; i2 < el.delDetail.length; i2++){
        dsiId.push(el.delDetail[i2].id);
    }

    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', 4);
                topWin.layer.alert('请确认并选择人工检查项', {icon: 0});
                return false;
            }
        }
    }
    var mainData = {};
    mainData.approveOpinion = approveOpinion;
    mainData.headData = headData;
    mainData.statementItem = statementItem;
    mainData.manualCheckList = manualCheckList;
    mainData.delSiIds = dsiId;

    var satisfyFlagExist = false;
    let uploadAttachmentFileDataList = (Number(tbAttachmentLookFlag)===1)?[]:$(el.tbAttachment).datagrid("getData").rows;
    uploadAttachmentFileDataList = await getAllBusinessData(uploadAttachmentFileDataList);
    if (uploadAttachmentFileDataList.length>0){
        uploadAttachmentFileDataList.forEach(item=>{
            if (item.satisfyFlag===0){
                satisfyFlagExist = true;
            }
        })
    }
    if (satisfyFlagExist){
        topWin.layer.alert('附件检查中存在附件未满足,请补充对应附件', {icon: 0});
        return false;
    }

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

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

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

}

/**
 * 数据保存
 *
 * @param callback 回调函数
 */
function financeSave(callback,approveStatus) {
    var id = $(el.id).val(), approveOpinion = $(el.approveOpinion).val(),
        bpPayableBalance = "", bpEstimateBalance = "",
        etPayableBalance = "", etEstimateBalance = "",
        currPaymentAmount = "";
    if(!approveOpinion){
        topWin.layer.alert('请输入审批意见', {icon: 0});
        return false;
    }

    var headData = {};
    headData.id = id;
    headData.bpPayableBalance = Number(bpPayableBalance.replace(/,/g,''));
    headData.bpEstimateBalance = Number(bpEstimateBalance.replace(/,/g,''));
    headData.etPayableBalance = Number(etPayableBalance.replace(/,/g,''));
    headData.etEstimateBalance = Number(etEstimateBalance.replace(/,/g,''));
    headData.currPaymentAmount = Number(currPaymentAmount.replace(/,/g,''));
    endManualEditing();
    var manualCheckList = $(el.tbAttachmentManualCheck).datagrid('getRows');
    //判断manualCheckList中人工检查是否选择
    if (manualCheckList.length>0&&approveStatus===1){
        for (var i = 0; i < manualCheckList.length; i++) {
            if (isBlank(manualCheckList[i].manualCheck)) {
                $(el.dataTabs).tabs('select', 4);
                topWin.layer.alert('请确认并选择人工检查项', {icon: 0});
                return false;
            }
        }
    }
    var result = {};
    result.approveOpinion = approveOpinion;
    result.headData = headData;
    result.manualCheckList = manualCheckList;
    result.statementItem = [];
    result.delSiIds = [];
    result.addDeductionIds = [];
    result.delDeductionIds = [];
    result.addRebateIds = [];
    result.delRebateIds = [];

    callback(result);
}

/**
 * 主管拒绝对账单
 *
 * @param callback 回调函数
 */
function purchaseRefuseStatement(callback) {
    var id = $(el.id).val(), remark = $(el.remark).val(), taxAmount = $(el.taxAmount).textbox('getValue'),
        notTaxAmount = $(el.notTaxAmount).val(), deductionAmount = "",
        rebateAmount = "", approveOpinion = $(el.approveOpinion).val();
    if(!approveOpinion){
        topWin.layer.alert('请您输入审批意见', {icon: 0});
        return false;
    }

    var headData = {};
    headData.id = id;
    headData.taxAmount = Number(taxAmount.replace(/,/g,''));
    headData.notTaxAmount = Number(notTaxAmount.replace(/,/g,''));
    // headData.deductionAmount = deductionAmount;
    // headData.rebateAmount = rebateAmount;
    headData.remark = remark;

    var result = {};
    result.approveOpinion = approveOpinion;
    result.headData = headData;
    result.statementItem = [];
    result.delSiIds = [];
    result.addDeductionIds = [];
    result.delDeductionIds = [];
    result.addRebateIds = [];
    result.delRebateIds = [];

    callback(result);
}

/**
 * 检查数组元素是否都相同
 *
 * @param array 待检查数组
 * @returns {boolean} 结果
 */
function checkIsAllEqual(array) {
    if (array.length > 0) {
        return !array.some(function (value, index) {
            return value !== array[0];
        });
    } else {
        return true;
    }
}

// 分页数据的操作
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 pagerSignFilter(data) {
    if (typeof data.length == 'number' && typeof data.splice == 'function')     {   // is array
        data = {
            total: data.length,
            rows: data
        }
    }
    var dg = $(this);
    var opts = dg.datagrid('options');
    var pager = dg.datagrid('getPager');
    pager.pagination({
        onSelectPage: function (pageNum, pageSize) {
            opts.pageNumber = pageNum;
            opts.pageSize = pageSize;
            pager.pagination('refresh', {
                pageNumber: pageNum,
                pageSize: pageSize
            });
            dg.datagrid('loadData', data);
        }
    });
    if (!data.originalSignRows) {
        data.originalSignRows = (data.rows);
        el.originalSignRows = (data.rows);
    }
    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
    var end = start + parseInt(opts.pageSize);
    data.rows = (data.originalSignRows.slice(start, end));
    return data;
}

function btnFilter() {
    if (el.filterFlag){
        el.filterFlag = false;
        $(el.tbDetails).datagrid('disableFilter');
    }else {
        el.filterFlag = true;
        $(el.tbDetails).datagrid('enableFilter');
        $('.datagrid-htable .datagrid-filter-c input').attr('AutoComplete','off')
    }
}

function  accountDateCheck() {
    return (async () => {
        try {
            var currentDate = new Date();
            var day = padZero(currentDate.getDate());
            var daySum = parseInt(day, 10);

            const accountDate = await new Promise((resolve, reject) => {
                $.ajax({
                    url: g.ctx + 'pc/sys/dict/getDicByTypes',
                    type: "GET",
                    data: {types: 'accountDate'},
                    success: resolve,
                    error: reject
                });
            });

            if (daySum < accountDate.accountDate[0].code) {
                topWin.layer.alert('当前日期不能创建对账单，请确认！', {icon: 0});
                return false;
            }
            return true;

        } catch (error) {
            topWin.layer.alert('获取账户日期配置失败！', {icon: 2});
            return false;
        }
    })();
}

function padZero(num) {
    return num < 10 ? '0' + num : num;
}

/**
 * 重新加载退货单行数据，根据送货单是否有退货单来判断是在人工检查表里否显示
 * @param rows
 */
function reloadReturnOrderRow(rows) {
    if (!rows || rows.length === 0) {
        return;
    }

    // 有id的行，说明已经保存过了，不需要处理
    if (rows[0].id) {
        return;
    }

    if (!el.uniqueDetail || el.uniqueDetail.length === 0) {
        return;
    }

    let returnOrderExistFlag = false;
    for (let i = 0; i < el.uniqueDetail.length; i++) {
        const uniqueDetail = el.uniqueDetail[i];
        if (uniqueDetail.returnConfirmStatus) {
            returnOrderExistFlag = true;
            break;
        }
    }

    // 不存在任何送货单有退货单
    if (!returnOrderExistFlag) {
        for (let i = 0; i < rows.length; i++) {
            const row = rows[i];

            // 但是人工检查明细里有
            if (row.type === 'return_order') {
                // 删除该行
                const dg = $(el.tbAttachmentManualCheck);
                const rowIndex = dg.datagrid('getRowIndex', row);
                dg.datagrid('deleteRow', rowIndex);
            }
        }
    }
}
/**
 * 获取所有业务附件
 */
async function getAllBusinessData(rows) {
    if (rows.length === 0) return [];
    const url = $(el.tbAttachment).datagrid('options').url;
    if (isBlank(url)) return [];
    const detailRows = await new Promise((resolve, reject) => {
        $.ajax({
            url: url,
            type: "GET",
            success: resolve,
            error: reject
        });
    });
    return detailRows.rows;
}