var el = {
    form : '#form',
    optType : '#optType',
    isSupplier : '#isSupplier',
    tbApproveLog : '#tbApproveLog',
    dataDiv: '#dataDiv',
    inStockStartDate : '#inStockStartDate',
    inStockEndDate : '#inStockEndDate',
    tbPaymentNotice : '#tbPaymentNotice',
    tariffTotalAmount : '#tariffTotalAmount',
    valueAddedTaxTotalAmount : '#valueAddedTaxTotalAmount',
    freightAndMiscellaneousFeeIncludingTaxTotal : '#freightAndMiscellaneousFeeIncludingTaxTotal',
    customsPaymentCertificateTaxAmount : '#customsPaymentCertificateTaxAmount',
    domesticTaxTotalAmount : '#domesticTaxTotalAmount',
    sharedExpenseAmount : '#sharedExpenseAmount',
    totalReimbursementAmount : '#totalReimbursementAmount',
    tbDetails : '#tbDetails',
    id : '#id',
    choseSupplierDialog: null,
    dataPanel: '#dataPanel',
    dataTabs: '#dataTabs',
    purchaseGroup : '#purchaseGroup',
    accountStatementYear : '#accountStatementYear',
    accountStatementMonth : '#accountStatementMonth',
    paymentTermCode : '#paymentTermCode',
    paymentWay : '#paymentWay',
    companyCode : '#companyCode',
    taxCode : '#taxCode',
    approveOpinion : '#approveOpinion',
    files : '#files',
    currencyCode : '#currencyCode',
    taxAmount : '#taxAmount',
    invoiceAmount : '#invoiceAmount',
    paymentMethod : '#paymentMethod',
    purchaseOrgCode : '#purchaseOrgCode',
    type : '#type',
    paymentNoticeDetailCode : '#paymentNoticeDetailCode',
    invoiceDate : '#invoiceDate',
    postDate : '#postDate',
    supplierName : '#supplierName',
    supplierCode : '#supplierCode',
    shortName : '#shortName',
    purchaseCategoryCode: '#purchaseCategoryCode',
    spotFlag: '#spotFlag',
    businessAgreeFlag: '#businessAgreeFlag',
    customerBearFlag: '#customerBearFlag',
    behalfCode: '#behalfCode',
    bearRatio: '#bearRatio',
    limitPrice: '#limitPrice',
    originalPaymentNoticeRows: [],
    originalRows: [],
    filterPaymentNoticeFlag: false,
    filterFlag: false,
    bodyHeight: document.documentElement.clientHeight
};
let editor = undefined;

$(function () {
    initDict('payment_method,po_type,po_item_type,po_item_subject,unit,businessFileType,sign_order,sign_type')
    initNecessaryDatas('pc/sys/purchaseCategory/rest/listAll,pc/sys/tax/rest/listAll,pc/sys/factory/rest/allList')
    $(el.dataPanel).panel({
        collapsible: true,
        onCollapse: function () {
            $(el.dataTabs).tabs('select', 0);
            $(el.tbDetails).datagrid('resize', {height: el.bodyHeight - 100});
            if (optType!==0){
                // $(el.tbApproveLog).datagrid('resize', {height: el.bodyHeight - 100});
            }
        },
        onExpand: function () {
            var dataDiv = $(el.dataDiv).outerHeight() + 90;
            $(el.dataTabs).tabs('select', 0);
            $(el.tbDetails).datagrid('resize', {height: 400});
            if (optType!==0){
                // $(el.tbApproveLog).datagrid('resize', {height: el.bodyHeight - dataDiv});
            }
        }
    });
    initCombo();
    initTbDetails();
    if (optType!==0){
        // initTbApproveLog();
    }
});

/**
 * 加载下拉框数据
 */
function initCombo() {
    var isSupplier = $(el.isSupplier).val();
    //采购组
    $(el.purchaseGroup).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll'
    });
    $(el.companyCode).combobox({
        valueField: 'code',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/company/rest/listAll',
        onSelect: function (data) {
            var oriCc = $(el.companyCode).combobox('getValue');
            if(oriCc !== data.companyCode){
                clearPageTableData();
                if (optType===1){
                    findSupplierPurchaseByCompanyCode(data.companyCode, $(el.supplierCode).textbox('getValue'));
                }
            }
            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) {
            clearPageTableData();
        },
    });

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

    $(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.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.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'
    });
}
/**
 * 选择供应商
 */
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) {
                        var oriSupCode = $(el.supplierCode).textbox('getValue');
                        if(oriSupCode !== data[0].supplierCode){
                            clearPageTableData();
                        }
                        $(el.supplierCode).textbox('setValue', data[0].supplierCode);
                        $(el.supplierName).textbox('setValue', data[0].supplierName);
                        $(el.currencyCode).combobox('setValue',data[0].currencyCode);
                        $(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);
                        el.choseSupplierDialog.dialog('close');
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.choseSupplierDialog.dialog('close');
                }
            }
        ]
    });
}

function initTbDetails() {
    var url = '';
    if ($(el.id).val()){
        url = g.ctx + 'pc/finance/company/account/statement/detail/rest/find/by/statement/id?asId='+$(el.id).val();
    }
    var toolbar = [];
    if (optType===0){
        toolbar.push(
            {
                text: "获取明细",
                iconCls: 'icon-add',
                handler: function () {
                    getReceiveVoucher();
                }
            },
            "-",
            {
                text: '过滤',
                id: 'btn_filter',
                iconCls: 'icon-filter',
                handler: function () {
                    btnReceiveVoucherFilter();
                }
            },
            "-",
            {
                text: "剔除",
                iconCls: 'icon-remove',
                handler: function () {
                    endEditing();
                    let rows = $(el.tbDetails).datagrid('getSelections');
                    if (rows.length===0) {
                        layer.alert("请选择数据");
                        return;
                    }
                    //循环删除
                    for (let i = 0; i < rows.length; i++) {
                        let row = rows[i];
                        let index = $(el.tbDetails).datagrid('getRowIndex', row);
                        $(el.tbDetails).datagrid('deleteRow', index);
                        el.originalRows = el.originalRows.filter(oldRow => oldRow.costMatchingPaymentNoticeRelationId !== row.costMatchingPaymentNoticeRelationId);
                    }
                    if (el.filterFlag){
                        $(el.tbDetails).datagrid('enableFilter');
                        $('.datagrid-htable .datagrid-filter-c input').attr('AutoComplete','off')
                    }
                }
            },
            "-",
            {
                text: "导出",
                iconCls: 'icon-download',
                handler: function () {
                    var rows = $(el.tbDetails).datagrid('getRows');
                    $(el.tbDetails).datagrid('toExcel', {
                        filename: '对账明细数据.xls',
                        rows: rows,
                        worksheet: '对账明细'
                    });
                }
            }
        );
    }else if (optType===1){
        toolbar.push(
            {
                text: '过滤',
                id: 'btn_filter',
                iconCls: 'icon-filter',
                handler: function () {
                    btnReceiveVoucherFilter();
                }
            },
            "-",
            {
                text: "剔除",
                iconCls: 'icon-remove',
                handler: function () {
                    endEditing();
                    let rows = $(el.tbDetails).datagrid('getSelections');
                    if (rows.length===0) {
                        layer.alert("请选择数据");
                        return;
                    }
                    //循环删除
                    for (let i = 0; i < rows.length; i++) {
                        let row = rows[i];
                        let index = $(el.tbDetails).datagrid('getRowIndex', row);
                        $(el.tbDetails).datagrid('deleteRow', index);
                        el.originalRows = el.originalRows.filter(oldRow => oldRow.costMatchingPaymentNoticeRelationId !== row.costMatchingPaymentNoticeRelationId);
                    }
                    if (el.filterFlag){
                        $(el.tbDetails).datagrid('enableFilter');
                        $('.datagrid-htable .datagrid-filter-c input').attr('AutoComplete','off')
                    }
                    if (optType===0||optType===1){
                        calculateTaxAmount();
                    }
                }
            },
            "-",
            {
                text: "导出",
                iconCls: 'icon-download',
                handler: function () {
                    var rows = $(el.tbDetails).datagrid('getRows');
                    $(el.tbDetails).datagrid('toExcel', {
                        filename: '对账明细数据.xls',
                        rows: rows,
                        worksheet: '对账明细'
                    });
                }
            }
        );
    }else {
        toolbar.push({
            text: "导出",
            iconCls: 'icon-download',
            handler: function () {
                var rows = $(el.tbDetails).datagrid('getRows');
                $(el.tbDetails).datagrid('toExcel', {
                    filename: '对账明细数据.xls',
                    rows: rows,
                    worksheet: '对账明细'
                });
            }}
        )
    }
    var searchHeight = $(el.form).outerHeight();
    $(el.tbDetails).datagrid({
        iconCls: 'icon-list',
        height: el.bodyHeight - searchHeight -80,
        singleSelect: false,
        pagination: true,
        pageSize: 500,
        pageList: [10, 50, 100, 200, 500, 1000,2000,3000],
        loadMsg: "数据加载中......",
        rownumbers: true,
        nowrap: true,
        striped: true,
        url: url,
        columns: [[
            {
                field: 'ck',
                checkbox: true
            },
            {
                field: 'customerPo',
                title: '客户PO',
                width: '140',
                align: 'left'
            },
            {
                field: 'salesOrderType',
                title: '订单类型',
                width: '80',
                align: 'left'
            },
            {
                field: 'salesOrder',
                title: '订单',
                width: '100',
                align: 'left'
            },
            {
                field: 'salesOrderRowNo',
                title: '订单行号',
                width: '100',
                align: 'left'
            },
            {
                field: 'shipmentDate',
                title: '出货日期',
                width: '100',
                align: 'left',
                // formatter: function (value) {
                //     if (value) {
                //         return new Date(value).format('yyyy-MM-dd');
                //     }
                //     return value;
                // }
            },
            {
                field: 'deliveryNote',
                title: '交货单',
                width: '100',
                align: 'left'
            },
            {
                field: 'deliveryNoteRowNo',
                title: '交货单行号',
                width: '100',
                align: 'left'
            },
            {
                field: 'materialCode',
                title: '物料编码',
                width: '140',
                align: 'left'
            },
            {
                field: 'materialGroupName',
                title: '物料组描述',
                width: '120',
                align: 'left'
            },
            {
                field: 'materialName',
                title: '物料描述',
                width: '150',
                align: 'left'
            },
            {
                field: 'customerMaterialNumber',
                title: '客户料号',
                width: '100',
                align: 'left'
            },
            {
                field: 'invoiceProductName',
                title: '开票品名',
                width: '100',
                align: 'left'
            },
            {
                field: 'specificationModel',
                title: '规格型号',
                width: '140',
                align: 'left'
            },
            {
                field: 'reconciliationQuantity',
                title: '对账数量',
                width: '100',
                align: 'left'
            },
            {
                field: 'invoiceQuantity',
                title: '开票数量',
                width: '100',
                align: 'left'
            },
            {
                field: 'unit',
                title: '单位',
                width: '100',
                align: 'left'
            },
            {
                field: 'taxCode',
                title: '税率',
                width: '140',
                align: 'left',
                formatter: function (value) {
                    return getNecessaryDataName('pc/sys/tax/rest/listAll',value);
                }
            },
            {
                field: 'taxPrice',
                title: '含税单价',
                width: '100',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            },
            {
                field: 'notTaxAmount',
                title: '未税金额',
                width: '100',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            },
            {
                field: 'diffTaxAmount',
                title: '税额',
                width: '100',
                align: 'left',
                // formatter: function (value) {
                //     return formatterPrice(value)
                // }
            },
            {
                field: 'taxAmount',
                title: '含税金额',
                width: '100',
                align: 'left',
                formatter: function (value) {
                    return formatterPrice(value)
                }
            }
        ]],
        onLoadSuccess: function (data) {
            if (optType===0||optType===1){
                calculateTaxAmount();
            }
        },
        loadFilter: pagerFilter,
        onClickRow: function (index, rowData) {
            if(optType !== 2){
                if (editor !== index) {
                    if (endEditing()) {
                        editor = index;
                        $(el.tbDetails).datagrid('updateRow', {index: index, row: {state: 2}})
                        $(el.tbDetails).datagrid('selectRow', index).datagrid('beginEdit', index);
                        editor = index;
                    } else {
                        editor = index;
                        $(el.tbDetails).datagrid('selectRow', editor);
                    }
                } else {
                    $(el.tbDetails).datagrid('updateRow', {index: index, row: {state: 2}})
                    $(el.tbDetails).datagrid('selectRow', index).datagrid('beginEdit', index);
                    editor = index;
                }
            }
            if(optType === 0){
                calculateTaxAmount();
            }

        },
        onSelect: function (index, rowData) {
            if(optType === 0){
                calculateTaxAmount();
            }
        },

        toolbar: toolbar,
    });
}

/**
 * 初始化审批记录表格
 */
function initTbApproveLog() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;

    $(el.tbApproveLog).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'pc/finance/company/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 clearPageTableData() {
    $(el.tbDetails).datagrid('loadData', {total: 0, rows: []});
}
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 getReceiveVoucher() {
    var supplierCode = $(el.supplierCode).textbox('getValue');
    if(!supplierCode){
        topWin.layer.alert('请选择供应商信息', {icon: 0});
        return false;
    }
    var inStockStartDate = $(el.inStockStartDate).datebox('getValue');
    var inStockEndDate = $(el.inStockEndDate).datebox('getValue');
    if(!inStockStartDate){
        topWin.layer.alert('请选择报关开始时间', {icon: 0});
        return false;
    }

    if(!inStockEndDate){
        topWin.layer.alert('请选择报关结束时间', {icon: 0});
        return false;
    }
    var companyCode = $(el.companyCode).textbox('getValue');
    if(!companyCode){
        topWin.layer.alert('请选择交易主体', {icon: 0});
        return false;
    }
    $(el.tbDetails).datagrid('options').queryParams = {
        supplierCode: supplierCode,
        companyCode: companyCode,
        inStockStartDate: inStockStartDate,
        inStockEndDate: inStockEndDate
    };
    $(el.tbDetails).datagrid('options').loadFilter = pagerFilter;
    $(el.tbDetails).datagrid('options').url = g.ctx + 'pc/finance/cost/matching/payment/notice/relation/rest/create/noPage/list';
    $(el.tbDetails).datagrid('load');
}

function btnReceiveVoucherFilter() {
    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 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 endEditing() {
    if (editor === undefined) {
        calculateTaxAmount();
        return true
    }
    if ($(el.tbDetails).datagrid('endEdit', editor)) {
        editor = undefined;
        calculateTaxAmount();
        return true;
    } else {
        return false;
    }
}
function calculateTaxAmount(){
    var allRows = $(el.tbDetails).datagrid('getRows');
    //增值税
    var totalCustomsPaymentCertificateTaxAmount = new BigNumber(0);
    //关税
    var totalTariffPrice = new BigNumber(0);
    //国内税额合计
    var totalDomesticTaxTotalAmount = new BigNumber(0);
    //分摊费用金额
    var totalSharedExpenseAmount = new BigNumber(0);
    for (let i = 0; i < allRows.length; i++) {
        if (allRows[i].valueAddedTaxPrice){
            totalCustomsPaymentCertificateTaxAmount = new BigNumber(allRows[i].valueAddedTaxPrice).plus(totalCustomsPaymentCertificateTaxAmount);
        }
        if (allRows[i].tariffPrice){
            totalTariffPrice = new BigNumber(allRows[i].tariffPrice).plus(totalCustomsPaymentCertificateTaxAmount);
        }
        totalDomesticTaxTotalAmount =  new BigNumber(allRows[i].feeTaxAmountPrice?allRows[i].feeTaxAmountPrice:0).plus(new BigNumber(allRows[i].freightTaxAmountPrice?allRows[i].freightTaxAmountPrice:0)).plus(totalDomesticTaxTotalAmount);
        totalSharedExpenseAmount = new BigNumber(allRows[i].agencyFeePrice?allRows[i].agencyFeePrice:0)
            .plus(new BigNumber(allRows[i].domesticFeePrice?allRows[i].domesticFeePrice:0))
            .plus(new BigNumber(allRows[i].overseasFeePrice?allRows[i].overseasFeePrice:0))
            .plus(new BigNumber(allRows[i].freightPrice?allRows[i].freightPrice:0))
            .plus(new BigNumber(allRows[i].otherFeePrice?allRows[i].otherFeePrice:0))
            .plus(totalSharedExpenseAmount);
    }
    $(el.tariffTotalAmount).textbox('setValue',totalTariffPrice);
    $(el.valueAddedTaxTotalAmount).textbox('setValue',totalCustomsPaymentCertificateTaxAmount);
    $(el.freightAndMiscellaneousFeeIncludingTaxTotal).textbox('setValue',totalSharedExpenseAmount);
    $(el.domesticTaxTotalAmount).textbox('setValue',totalDomesticTaxTotalAmount);
    $(el.taxAmount).textbox('setValue',totalSharedExpenseAmount.plus(totalDomesticTaxTotalAmount));
}

function copy(type) {
    $(el.tb).datagrid('endEdit', editor);
    let allRows = $(el.tb).datagrid('getRows');
    for (let i = 0;i<allRows.length;i++){
        $(el.tb).datagrid('endEdit', i);

    }
    for (let i = 0; i < allRows.length; i++) {
        $(el.tb).datagrid('updateRow', {
            index: i,
            row: {
                [type]: allRows[0][type]
            }
        });
    }
}


function saveOrUpdate(call){
    if($(el.form).form('validate')){
        var formData = $(el.form).serializeJson();
        formData.id = optType===3?'':$(el.id).val();
        formData.files = $(el.files).attr('data-fileIds');
        endEditing();
        let rows = $(el.tbDetails).datagrid('getRows');
        if (rows.length <= 0) {
            layer.msg('请获取明细', {time: 2000});
            return false;
        }
        formData.detailList = rows;
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/finance/company/account/statement/rest/saveOrUpdate',
            method: 'post',
            data: JSON.stringify(formData),
            contentType: 'application/json',
            success: function (data) {
                call();
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    }else {
        layer.msg('检验未通过!请检查红框未填');
        return false;
    }
}

/**
 * 采购保存
 *
 * @param approveStatus 审批结果 0:拒绝 1:同意
 * @param call 回调函数
 */
function purchaseConfirm(approveStatus,call) {
    var approveOpinion = $(el.approveOpinion).val();
    var formData = {};
    formData.id = $(el.id).val();
    formData.approveStatus = approveStatus;
    formData.approveOpinion = approveOpinion;
    if(approveStatus===0&&!approveOpinion){
        topWin.layer.alert('请输入审批意见', {icon: 0});
        return false;
    }
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/finance/company/account/statement/rest/purchase/approve',
        method: 'post',
        data: JSON.stringify(formData),
        contentType: 'application/json',
        success: function (data) {
            call();
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}

/**
 * 财务保存
 *
 * @param approveStatus 审批结果 0:拒绝 1:同意
 * @param call 回调函数
 */
function financeConfirm(approveStatus,call) {
    var approveOpinion = $(el.approveOpinion).val();
    var formData = {};
    formData.id = $(el.id).val();
    formData.approveStatus = approveStatus;
    formData.approveOpinion = approveOpinion;
    if(approveStatus===0&&!approveOpinion){
        topWin.layer.alert('请输入审批意见', {icon: 0});
        return false;
    }
    var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
    $.ajax({
        url: g.ctx + 'pc/finance/company/account/statement/rest/finance/approve',
        method: 'post',
        data: JSON.stringify(formData),
        contentType: 'application/json',
        success: function (data) {
            call();
        },
        complete: function(data) {
            top.layer.close(loading);
        },
        error: function (data) {
            parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });
}