/**
 * 对账模块-开票申请单新增页面JS
 *
 * Created by li.kui on 2020/8/14.
 */
'use strict';
var el = {
    dataPanel: '#dataPanel',
    dataDiv: '#dataDiv',
    id: '#id',
    orderType: '#orderType',
    strikePriceAmount: '#strikePriceAmount',
    inStockStartDate: '#inStockStartDate',
    inStockEndDate: '#inStockEndDate',
    isSupplier: '#isSupplier',
    supplierCode: '#supplierCode',
    supplierName: '#supplierName',
    companyCode: '#companyCode',
    companyName: '#companyName',
    factoryCode: '#factoryCode',
    factoryName: '#factoryName',
    currencyCode: '#currencyCode',
    deductionAmount: '#deductionAmount',
    dntAmount: '#dntAmount',
    rebateAmount: '#rebateAmount',
    rntAmount: '#rntAmount',
    invoiceNetAmount: '#invoiceNetAmount',
    invoiceTaxAmount: '#invoiceTaxAmount',
    allBudInnerMoney: '#allBudInnerMoney',
    invoiceNum: '#invoiceNum',
    invoiceNo: '#invoiceNo',
    remark: '#remark',
    dataTabs: '#dataTabs',
    tbDetails: '#tbDetails',
    tbDeduction: '#tbDeduction',
    tbAdvance: '#tbAdvance',
    tbRebate: '#tbRebate',
    diffAmount1: '#diffAmount1',
    choseSupplierDialog: null,
    supplierCurrencyCode: null,
    supplierTaxRate: null,
    supplierBusinessRegisterNo: null,
    userTableColumn: [],
    bodyHeight: document.documentElement.clientHeight,

    iaNo: '#invoiceApplyNo',
    tbInvoice: '#tbInvoice',
    tbFile: '#tbFile',
    invoiceTotalAmount: '#invoiceTotalAmount',
    invoiceTaxTotalAmount: '#invoiceTaxTotalAmount',
    diffAmount: '#diffAmount',
    delInvoice: [],
    delDetail : [],
    typeName : 'add_fast'
};


/**
 * 文档就绪
 */
$(function () {
    $(el.dataPanel).panel({
        collapsible: true,
        onCollapse: function () {
            $(el.dataTabs).tabs('select', 0);

            $(el.tbDetails).datagrid('resize', {height: el.bodyHeight - 80});
            $(el.tbRebate).datagrid('resize', {height: el.bodyHeight - 80});
            $(el.tbDeduction).datagrid('resize', {height: el.bodyHeight - 80});
            $(el.tbAdvance).datagrid('resize', {height: el.bodyHeight - 80});
        },
        onExpand: function () {
            $(el.dataTabs).tabs('select', 0);

            var dataDiv = $(el.dataDiv).outerHeight() + 90;
            $(el.tbDetails).datagrid('resize', {height: el.bodyHeight - dataDiv});
            $(el.tbRebate).datagrid('resize', {height: el.bodyHeight - dataDiv});
            $(el.tbDeduction).datagrid('resize', {height: el.bodyHeight - dataDiv});
            $(el.tbAdvance).datagrid('resize', {height: el.bodyHeight - dataDiv});
        }
    });

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

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

    // initTbDeduction();
    // initTbRebate();
    initTbDetails();
    // initTbAdvance();
});


/**
 * 初始化页面输入框
 */
function initPageInput() {
    var isSupplier = $(el.isSupplier).val();
    // var companyUrl = g.ctx + 'pc/sys/company/rest/listAll?isAuthority=1';
    // if(Number(isSupplier) === 1){
    var companyUrl = g.ctx + 'pc/sys/company/rest/listAll?isAuthority=0';
    // }

    // 初始化工厂代码下拉框
    $(el.factoryCode).combobox({
        panelHeight: 300,
        limitToList: 'true',
        panelWidth: 260,
        prompt: '--- 请先选择采购公司 ---',
        disabled: true,
        required: false
    });

    // 初始化公司代码下拉框
    $(el.companyCode).combobox({
        required: true,
        url: companyUrl,
        panelHeight: 300,
        panelWidth: 340,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        onSelect: function (data) {
            var oriCc = $(el.companyCode).combobox('getValue');
            if(oriCc !== data.companyCode){
                clearPageTableData();
            }

            $(el.companyName).val(data.companyName);
            findFactoryDataByCompanyCode(data.companyCode, isSupplier);
        },
        onLoadSuccess: function () { //加载完成后,设置选中第一项
            $(this).combobox("select", $('#deptCode').val());
        }
    });

    // 初始化税率代码下拉框
    $('#taxCode').combobox({
        required: true,
        panelHeight: 300,
        panelWidth: 340,
        limitToList: 'true',
        valueField: 'taxCode',
        method: 'GET',
        textField: 'codeWithDesc',
        url: g.ctx + 'pc/sys/tax/rest/listAll',
        prompt: '--- 请选择 ---'
    });
    // 付款条件
    $('#paymentTermCode').combobox({
        required: true,
        limitToList: 'true',
        panelHeight: 'auto',
        panelWidth: 200,
        method: 'GET',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=payment_method',
    });
    // 初始化币种下拉框
    $(el.currencyCode).combobox({
        panelHeight: 'auto',
        panelWidth: 200,
        limitToList: 'true',
        valueField: 'code',
        textField: 'codeWithDesc',
        method: 'GET',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=currency',
        onSelect: function (data) {
            getExchangeRate(data.dicId);
        },
        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 {
        // findCurrencyDataBySupplierCode($(el.supplierCode).textbox('getValue'));
    }
    // 订单类型
    $('#poType').combobox({
        required: true,
        limitToList: 'true',
        panelHeight: 'auto',
        panelWidth: 200,
        method: 'GET',
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/dict/getDicByType?type=po_type',
    });
}


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

    $(el.tbDetails).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        singleSelect: false,
        rownumbers: true,
        showFooter: true,
        pagination: false,
        queryParams: {},
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                }
            ]
        ],
        columns: [
            tableColumns
        ],
        toolbar: [
            {
                text: '获取对账明细',
                iconCls: 'icon-add',
                handler: function () {
                    findStatementDetail();
                }
            },
            '-',
            {
                text: '导出',
                iconCls: 'icon-download',
                handler: function () {
                    detailDataExport();
                }
            }
        ],
        onLoadSuccess: function () {
            // 默认全部选中
            $(el.tbDetails).datagrid('selectAll');
            refreshRebateAndDeduction();
            var detail = $(el.tbDetails).datagrid('getRows');
            let flag = true, msg = [];
            // for (let i = 0 ; i < detail.length ; i ++){
            //     if (!detail[i].poId){
            //         msg.push('SAP订单号：' +detail[i].poCode + '，订单行号：'+detail[i].poItemNo+'未找到该采购订单;');
            //         flag = false;
            //         continue;
            //     }
            //     if (!detail[i].finConf || Number(detail[i].finConf)===0){
            //         msg.push('SAP订单号：' +detail[i].poCode + '，订单行号：'+detail[i].poItemNo+ 'SC订单号：' + detail[i].zlsdh +
            //             '财务未确认;');
            //         flag = false;
            //     }
            // }
            if(!flag){
                layer.confirm(msg.join('<br/>'), {icon: 2, title: '温馨提示',area:['600px','200px']});
                return false;
            }
        },
        onSelect: function () {
            refreshRebateAndDeduction();
        },
        onUnselect: function () {
            refreshRebateAndDeduction();
        },
        onSelectAll: function () {
            refreshRebateAndDeduction();
        },
        onUnselectAll: function () {
            refreshRebateAndDeduction();
        }
    });
}

/**
 * 初始化预付款明细表格
 */
function initTbAdvance() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90, orderType = $(el.orderType).val();
    $(el.tbAdvance).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        singleSelect: false,
        rownumbers: true,
        showFooter: true,
        pagination: true,
        queryParams: {},
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                // {
                //     field: 'seekPgName',
                //     title: '业务员',
                //     width: 80,
                //     sortable: true
                // },
                {
                    field: 'poCode',
                    title: '采购订单',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'poItemNo',
                    title: '订单行号',
                    width: 65,
                    sortable: true
                },
                {
                    field: 'poNum',
                    title: '订单数量',
                    width: 65,
                    sortable: true
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'quantityRange',
                    title: '容差',
                    hidden:true
                },
                {
                    field: 'factoryCode',
                    title: '工厂',
                    width: 80,
                    sortable: true
                },
                {
                    field: 'materialDesc',
                    title: '物料描述',
                    width: 300,
                    sortable: true
                },
                {
                    field: 'taxCodeDesc',
                    title: '税码',
                    width: 160,
                    sortable: true
                },
                // {
                //     field: 'ntPrice',
                //     title: '不含税单价',
                //     width: 100,
                //     sortable: true
                // },
                {
                    field: 'itPrice',
                    title: '含税单价',
                    width: 100,
                    sortable: true,
                    formatter:function (value) {
                        if (!value) {
                            return '';
                        }
                        return  formatNumber(value, 4, 1);
                    }
                },
                {
                    field: 'itAmount',
                    title: '订单含税金额',
                    width: 100,
                    sortable: true,
                    formatter:function (value) {
                        if (!value) {
                            return '';
                        }
                        return  formatNumber(value, 4, 1);
                    }
                },
                {
                    field: 'applyAmount',
                    title: '可申请金额',
                    width: 100,
                    sortable: true,
                    formatter:function (value) {
                        if (!value) {
                            return '';
                        }
                        return  formatNumber(value, 4, 1);
                    }
                },
                {
                    field: 'budInnerMoney',
                    title: '申请金额',
                    width: 100,
                    sortable: true,
                    styler: function (value, row) {
                        if(row.poCode !== '合计'){
                            return 'background-color:#E1E1E1;';
                        }
                        return '';
                    },
                    editor: {
                        type: 'numberbox',
                        options: {
                            precision: 4,
                            onChange: function (nv) {
                                updateRowData(nv,'budInnerMoney');
                            }
                        }
                    }
                },
                {
                    field: 'alreadyApplyAmount',
                    title: '已申请金额',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'alreadyAdvanceAmount',
                    title: '已预付金额',
                    width: 100,
                    sortable: true
                },
                {
                    field: 'pcCodeName',
                    title: '付款条件名称',
                    width: 200,
                    sortable: true
                },
                // {
                //     field: 'itemRemark',
                //     title: '摘要',
                //     width: 200,
                //     styler: function (value, row) {
                //         if(row.poCode !== '合计'){
                //             return 'background-color:#E1E1E1;';
                //         }
                //         return '';
                //     },
                //     editor: {type: 'textbox'}
                // },
                // {
                //     field: 'contractNo',
                //     title: '合同号',
                //     width:120
                // },
                // {
                //     field: 'contractName',
                //     title: '合同名称',
                //     width:120
                // },
                // {
                //     field: 'emptyColumn',
                //     title: '',
                //     width: 20
                // }
            ]
        ],
        onLoadSuccess: function () {
            $(el.tbAdvance).datagrid('selectAll');
            calculationAdvancePageAmount();
        },
        onSelect: function () {
            calculationAdvancePageAmount();
        },
        onUnselect: function () {
            calculationAdvancePageAmount();
        },
        onSelectAll: function () {
            calculationAdvancePageAmount();
        },
        onUnselectAll: function () {
            calculationAdvancePageAmount();
        }
    });
}


/**
 * 获取对账单明细数据
 */
function findStatementDetail() {
    var companyCode = $(el.companyCode).combobox('getValue'), factoryCode = $(el.factoryCode).combobox('getValue'),taxCode = $('#taxCode').combobox('getValue'), poType = getTextByJs($('#poType').combobox('getValues')),
        currencyCode = $(el.currencyCode).combobox('getValue'),paymentTermCode = $('#paymentTermCode').combobox('getValue'),supplierCode = $(el.supplierCode).textbox('getValue'),
    inStockStartDate = $(el.inStockStartDate).datebox('getValue'), inStockEndDate = $(el.inStockEndDate).datebox('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;
    }
    console.log(poType)
    if(!poType){
        topWin.layer.alert('请选择订单类型', {icon: 0});
        return false;
    }
    if(!taxCode){
        topWin.layer.alert('请选择税率', {icon: 0});
        return false;
    }
    if(!paymentTermCode){
        topWin.layer.alert('请选择付款条件', {icon: 0});
        return false;
    }
    var queryParams = $(el.tbDetails).datagrid('options').queryParams;
    queryParams.supplierCode = supplierCode;
    queryParams.companyCode = companyCode;
    queryParams.factoryCode = factoryCode;
    queryParams.currencyCode = currencyCode;
    queryParams.poTypes = poType;
    queryParams.inStockStartDate = inStockStartDate;
    queryParams.inStockEndDate = inStockEndDate;
    queryParams.taxCode = taxCode;
    queryParams.paymentTermCode = paymentTermCode;
    queryParams.orderType = $(el.orderType).val();
    $(el.tbDetails).datagrid('options').url = g.ctx + 'pc/finance/account/statement/detail/rest/provide/create/invoiced/apply';
    $(el.tbDetails).datagrid('load');

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

}


/**
 * 刷新返利和扣款表格数据
 */
function refreshRebateAndDeduction() {
    var rows = $(el.tbDetails).datagrid('getSelections'), asIds = [], purchaseOrderDetailIds = [];
    for(var i = 0; i < rows.length; i++){
        asIds.push(rows[i].asId);
        purchaseOrderDetailIds.push(rows[i].purchaseOrderDetailId);
    }

    // var queryParams1 = $(el.tbDeduction).datagrid('options').queryParams;
    // queryParams1.asIds = JSON.stringify(asIds);
    // queryParams1.aeSdIds = '';
    // queryParams1.tdSdIds = '';
    // $(el.tbDeduction).datagrid('options').url = g.ctx + 'fin/account/statement/detail/rest/cia/find/statement/deduction';
    // $(el.tbDeduction).datagrid('load');
    //
    // var queryParams2 = $(el.tbRebate).datagrid('options').queryParams;
    // queryParams2.asIds = JSON.stringify(asIds);
    // queryParams2.aeSrIds = '';
    // queryParams2.tdSrIds = '';
    // $(el.tbRebate).datagrid('options').url = g.ctx + 'fin/account/statement/detail/rest/cia/find/statement/rebate';
    // $(el.tbRebate).datagrid('load');

    // var queryParams3 = $(el.tbAdvance).datagrid('options').queryParams;
    // queryParams3.supplierCode = $(el.supplierCode).textbox('getValue');
    // $(el.tbAdvance).datagrid('options').url = g.ctx + 'fin/payment/advance/apply/rest/find/paa/findPaaDetailBySupplierCode';
    // $(el.tbAdvance).datagrid('load');
    //
    calculationPageAmount();
}


/**
 * 数据保存
 *
 * @param callback 回调函数
 */
function dataSave(callback) {
    endInvoiceEditor();
    // addOrDelInvoice();
    var orderType = $(el.orderType).val(), supplierCode = $(el.supplierCode).textbox('getValue'),
        supplierName = $(el.supplierName).textbox('getValue'), currencyCode = $(el.currencyCode).combobox('getValue'),
        companyCode = $(el.companyCode).combobox('getValue'), companyName = $(el.companyName).val(),
        poType = getTextByJs($('#poType').combobox('getValues')),
        factoryName = $(el.factoryName).val(),
        factoryCode = $(el.factoryCode).combobox('getValue'),
        invoiceNetAmount = $(el.invoiceNetAmount).textbox('getValue'),
        invoiceTaxAmount = $(el.invoiceTaxAmount).textbox('getValue'),
        // allBudInnerMoney = $(el.allBudInnerMoney).textbox('getValue'),
        invoiceTaxTotalAmount = $(el.invoiceTaxTotalAmount).textbox('getValue'),
        invoiceTotalAmount = $(el.invoiceTotalAmount).textbox('getValue'),
        deductionAmount = "", rebateAmount = "",taxCode = $('#taxCode').combobox('getValue'),paymentTermCode1 = $('#paymentTermCode').combobox('getValue'),
        invoiceNum = $(el.invoiceNum).numberbox('getValue'), invoiceNo = $(el.invoiceNo).textbox('getValue'),
        remark = $(el.remark).textbox('getValue'), dntAmount = $(el.dntAmount).val(), rntAmount = $(el.rntAmount).val();

    if (!currencyCode) {
        topWin.layer.alert('请选择币种', {icon: 0});
        return false;
    }
    if (!companyCode) {
        topWin.layer.alert('请选择采购公司', {icon: 0});
        return false;
    }
    if (!taxCode) {
        topWin.layer.alert('请选择税率', {icon: 0});
        return false;
    }
    if (!paymentTermCode1) {
        topWin.layer.alert('请选择付款条件', {icon: 0});
        return false;
    }
    // if(!invoiceNum){
    //     topWin.layer.alert('请填写发票张数', {icon: 0});
    //     return false;
    // }
    // if(!invoiceNo){
    //     topWin.layer.alert('请填写发票号', {icon: 0});
    //     return false;
    // }
    // // 发票号填写的字符串长度不能超过30位字符
    // if(invoiceNo.length > 30){
    //     topWin.layer.alert('发票号填写的字符串长度不能超过30位字符', {icon: 0});
    //     return false;
    // }

    // 对账单明细
    var detail = $(el.tbDetails).datagrid('getSelections'), statementItem = [],
        invoicedReceipt = $(el.tbInvoice).datagrid('getRows'),leshuiItem = []
        ,taxData = [],paymentTermCode =  [],is101Flag = false;
    if (detail.length === 0) {
        topWin.layer.alert('请先选择获取对账单明细', {icon: 0});
        return false;
    }
    // SAP发票明细行不得超过999行
    // if(detail.length > 900){
    //     topWin.layer.alert('由于系统原因, 开票申请明细不得超过900行', {icon: 0});
    //     return false;
    // }
    if (invoicedReceipt.length === 0) {
        topWin.layer.alert('请添加关联发票信息', {icon: 0});
        return false;
    }
    for (let i = 0 ; i < invoicedReceipt.length ; i ++){
        // if(!invoicedReceipt[i].deductionCodeType){
        //     layer.msg("关联发票信息：第"+ ++i+"行可抵扣编号不能为空");
        //     return false;
        // }
        if(!invoicedReceipt[i].invoiceDate){
            layer.msg("关联发票信息：第"+ ++i+"行发票日期不能为空");
            return false;
        }
        // if(!invoicedReceipt[i].invoiceCode){
        //     layer.msg("关联发票信息：第"+ ++i+"行发票代码不能为空");
        //     return false;
        // }
        if(!invoicedReceipt[i].invoiceNumber){
            layer.msg("关联发票信息：第"+ ++i+"行发票号码不能为空");
            return false;
        }
        if(!invoicedReceipt[i].dutyParagraph){
            layer.msg("关联发票信息：第"+ ++i+"行税号不能为空");
            return false;
        }
        if(!invoicedReceipt[i].taxRate){
            layer.msg("关联发票信息：第"+ ++i+"行税率不能为空");
            return false;
        }
        if(!invoicedReceipt[i].currencyCode){
            layer.msg("关联发票信息：第"+ ++i+"行币种不能为空");
            return false;
        }
        if(!invoicedReceipt[i].taxAmount){
            layer.msg("关联发票信息：第"+ ++i+"行含税金额不能为空");
            return false;
        }
        if(!invoicedReceipt[i].noTaxAmount&&invoicedReceipt[i].noTaxAmount!==0){
            layer.msg("关联发票信息：第"+ ++i+"行未税金额不能为空");
            return false;
        }
        // if(!invoicedReceipt[i].fileId){
        //     layer.msg("关联发票信息：第"+ ++i+"行发票附件不能为空");
        //     return false;
        // }
    }

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

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

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

    if(Number(invoiceTaxAmount) <= 0 && is101Flag){
        // topWin.layer.alert('开票含税总金额必须大于零', {icon: 0});
        // return false;
    }
    // 检查对账单明细中对账税率是否都相同
    if(!checkIsAllEqual(taxData)){
        topWin.layer.alert('明细中税率不相同', {icon: 0});
        return false;
    }
    // 检查对账单明细中付款条件是否都相同
    if(!checkIsAllEqual(paymentTermCode)){
        topWin.layer.alert('明细中付款条件不相同', {icon: 0});
        return false;
    }

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

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

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

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

    var headData = {};
    headData.id = $(el.id).val();
    headData.invoiceApplyNo = $(el.iaNo).val();
    headData.orderType = orderType;
    headData.companyCode = companyCode;
    headData.companyName = companyName;
    headData.poType = poType;
    headData.taxCode = taxCode;
    headData.paymentTermCode = paymentTermCode1;
    headData.factoryCode = factoryCode;
    headData.factoryName = factoryName;
    headData.currencyCode = currencyCode;
    headData.supplierCode = supplierCode;
    headData.supplierName = supplierName;
    headData.invoiceNetAmount = Number(invoiceNetAmount.replace(/,/g,''));
    headData.invoiceTaxAmount = Number(invoiceTaxAmount.replace(/,/g,''));
    // headData.allBudInnerMoney = Number(allBudInnerMoney.replace(/,/g,''));
    headData.invoiceTaxTotalAmount = Number(invoiceTaxTotalAmount.replace(/,/g,''));
    headData.invoiceTotalAmount = Number(invoiceTotalAmount.replace(/,/g,''));
    headData.invoiceDiffAmount = Number(headData.invoiceTaxAmount) - Number(headData.invoiceNetAmount);
    headData.dntAmount = dntAmount;
    headData.deductionAmount = deductionAmount;
    headData.rntAmount = rntAmount;
    headData.rebateAmount = rebateAmount;
    headData.invoiceNum = invoiceNum;
    headData.invoiceNo = invoiceNo;
    headData.remark = remark;
    headData.statementNum = statementNum;
    headData.purchaseGroup = purchaseGroup;

    var dataParams = {};
    dataParams.headData = headData;
    dataParams.detailDate = statementItem;
    dataParams.invoicedReceiptData = invoicedReceipt;
    // dataParams.deductionDetailData = getDeductionDetail();
    // endFileEditor();
    // var fileJson = $(el.tbFile).datagrid('getRows')
    // dataParams.fileJson = JSON.stringify(fileJson);
    // dataParams.addSdIds = sdIds;
    // dataParams.addSrIds = srIds;
    // dataParams.addPaIds = paIds;

    var url = '';
    if(headData.id > 0){
        url = g.ctx + 'pc/finance/invoiced/apply/rest/saveHead';
    }else{
        url = g.ctx + 'pc/finance/invoiced/apply/rest/save';
    }

    var loading = topWin.layer.msg('数据保存中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: url,
        type: 'POST',
        data: JSON.stringify(dataParams),
        contentType: 'application/json',
        success: function (data) {
            topWin.layer.close(loading);
            callback(data);
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
        }
    });


}


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


/**
 * 选择供应商弹框主动关闭弹框
 *
 * @param data 选中的结果
 */
function choseSupDialogConfirm(data) {
    var oriSupCode = $(el.supplierCode).textbox('getValue');
    if(oriSupCode !== data.supplierCode){
        clearPageTableData();
        // findCurrencyDataBySupplierCode(data.supplierCode);
    }

    $(el.supplierCode).textbox('setValue', data.supplierCode);
    $(el.supplierName).textbox('setValue', data.supplierName);
    el.choseSupplierDialog.dialog('close');
}


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

    $(el.factoryCode).combobox({
        url: factoryDataUrl,
        valueField: 'code',
        textField: 'codeWithDesc',
        prompt: '--- 请选择 ---',
        panelHeight: 300,
        panelWidth: 260,
        disabled: false,
        required: true,
        onLoadSuccess: function(data){
            console.log(JSON.stringify(data))
            for (var i = 0; i < data.length; i++) {
                if(data[i].companyCode === companyCode){
                    $(el.factoryCode).combobox('setValue', data[i].factoryCode);
                    $(el.factoryName).val(data[i].factoryName);
                }
            }
        },
        onSelect: function (data) {
            var oriFc = $(el.factoryCode).combobox('getValue');
            if(oriFc !== data.factoryCode){
                clearPageTableData();
            }

            $(el.factoryName).val(data.factoryName);
        }
    });
}


/**
 * 根据供应商编码获取币种下拉框数据
 *
 * @param supplierCode 供应商编码
 */
// function findCurrencyDataBySupplierCode(supplierCode) {
//     $(el.currencyCode).combobox({
//         url: g.ctx + 'fin/common/rest/find/supplier/currency?supplierCode=' + supplierCode,
//         valueField: 'currencyCode',
//         textField: 'currencyCode',
//         prompt: '--- 请选择 ---',
//         panelHeight: 'auto',
//         panelWidth: 260,
//         editable: false,
//         disabled: false,
//         required: true,
//         onLoadSuccess: function(data){
//             if(data.length === 1){
//                 $(el.currencyCode).combobox('setValue', data[0].currencyCode);
//             }
//         }
//     });
// }
function  calculationAdvancePageAmount(){
    var advanceDetail = $(el.tbAdvance).datagrid('getRows');
    var allBudInnerMoney = new BigNumber(0);
    for (var i = 0; i < advanceDetail.length; i++) {
        var item2 = advanceDetail[i];
        allBudInnerMoney = allBudInnerMoney.plus(item2.alreadyAdvanceAmount);
        $(el.allBudInnerMoney).textbox('setValue', allBudInnerMoney.toFormat(2));
    }
}

/**
 * 计算页面上相关金额
 * 发票含税金额 = 对账明细含税金额合计 - 含税扣款金额 + 含税返利金额
 */
function  calculationPageAmount() {
    // 需要处理统计行中 未税金额 != 含税金额 / (1 + 税率)
    var taxValue = new BigNumber(1), itSumAmount = new BigNumber(0), ntSumAmount = new BigNumber(0);
    var maxAmount = new BigNumber(0), maxAmountRowIndex = -1, maxAdtAmount = new BigNumber(0), maxAntAmount = new BigNumber(0);
    var rows = $(el.tbDetails).datagrid('getSelections');
    for (var n = 0; n < rows.length; n++) {
        var item = rows[n];
        ntSumAmount = ntSumAmount.plus(item.asNotTaxAmount);
        itSumAmount = itSumAmount.plus(item.asTaxAmount);
        taxValue = new BigNumber(item.asTaxValue);

        if(maxAmount.eq(0)){
            maxAmount = new BigNumber(item.asTaxAmount);
            maxAdtAmount = new BigNumber(item.asDiffTaxAmount);
            maxAntAmount = new BigNumber(item.asNotTaxAmount);
            maxAmountRowIndex = $(el.tbDetails).datagrid('getRowIndex', item);
        }
        if(!maxAmount.eq(0) && maxAmount.lt(item.asTaxAmount)){
            maxAmount = new BigNumber(item.asTaxAmount);
            maxAdtAmount = new BigNumber(item.asDiffTaxAmount);
            maxAntAmount = new BigNumber(item.asNotTaxAmount);
            maxAmountRowIndex = $(el.tbDetails).datagrid('getRowIndex', item);
        }
    }

    // 创建的时候不需要一下逻辑(下面的逻辑:保证表体合计含税金额=表体合计未税金额*(1+税率))
    // var tax = taxValue.div(100).plus(1);
    // // 表体明细相加的含税金额除以税率减去表体明细相加的未税金额, 如果差异超过±0.01(包含±0.01), 需要将差异加到表体含税金额最大一行中
    // var diff = itSumAmount.div(tax).sub(ntSumAmount);
    // var diffNum = Number(diff.abs().toFixed(2));
    // if(diffNum >= 0.01){
    //     var adtAmount = maxAdtAmount.sub(diff).toFixed(2);
    //     var antAmount = maxAntAmount.plus(diff).toFixed(2);
    //
    //     $(el.tbDetails).datagrid('updateRow', {
    //         index: maxAmountRowIndex,
    //         row: {
    //             asDiffTaxAmount: adtAmount,
    //             asNotTaxAmount: antAmount
    //         }
    //     });
    // }

    var detail = $(el.tbDetails).datagrid('getSelections'), rebate = "", deduction = "";
    var itAmount = new BigNumber(0), ntAmount = new BigNumber(0), statementNum = new BigNumber(0);
    for (var i = 0; i < detail.length; i++) {
        var item1 = detail[i];
        ntAmount = ntAmount.plus(item1.asNotTaxAmount);
        itAmount = itAmount.plus(item1.asTaxAmount);
        statementNum = statementNum.plus(item1.statementNum);
    }

    // var advanceDetail = $(el.tbAdvance).datagrid('getRows');
    // var allBudInnerMoney = new BigNumber(0);
    // for (var i = 0; i < advanceDetail.length; i++) {
    //     var item2 = advanceDetail[i];
    //     allBudInnerMoney = allBudInnerMoney.plus(item2.alreadyAdvanceAmount);
    // }


    if(0 !== rows.length){
        // 更新页脚行的值并刷新
        var footers = $(el.tbDetails).datagrid('getFooterRows');
        footers[0]['asNotTaxAmount'] = ntAmount.toFormat(2);
        footers[0]['asTaxAmount'] = itAmount.toFormat(2);
        footers[0]['asDiffTaxAmount'] = itAmount.minus(ntAmount).toFormat(2);
        footers[0]['statementNum'] = statementNum.toNumber();
        $(el.tbDetails).datagrid('reloadFooter');
    }else {
        // 更新页脚行并载入新数据
        $(el.tbDetails).datagrid('reloadFooter', [
            {
                asNotTaxAmount: 0,
                asTaxAmount: 0,
                asDiffTaxAmount: 0,
                statementNum: 0
            }
        ]);
    }

    // ntAmount = ntAmount.plus(rntAmount).plus(dntAmount);
    // itAmount = itAmount.plus(rtAmount).plus(dtAmount);
    $(el.invoiceNetAmount).textbox('setValue', ntAmount.toFormat(2));
    $(el.invoiceTaxAmount).textbox('setValue', itAmount.toFormat(2));
    $(el.diffAmount).textbox('setValue', itAmount.minus(ntAmount).toFormat(2));
    // $(el.allBudInnerMoney).textbox('setValue', allBudInnerMoney.toFormat(2));
}


/**
 * 明细导出
 */
function detailDataExport() {
    var rows = $(el.tbDetails).datagrid('getRows');
    $(el.tbDetails).datagrid('toExcel', {
        filename: '对账明细数据.xls',
        rows: rows,
        worksheet: '对账明细'
    });
}


/**
 * 查看扣款或返利附件
 *
 * @param ele 当前操作DOM节点
 */
function lookDrAttachment(ele) {
    var drId = $(ele).data('id'), attType = $(ele).data('type');
    var url = g.ctx + 'fin/common/look/dr/attachment?drId=' + drId + '&attType=' + attType;
    var lookDrAttDialog = openDialog('lookDrAtt', url, {
        title: '附件查看',
        width: '35%',
        height: '45%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            lookDrAttDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    lookDrAttDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 清空页面表格数据
 */
function clearPageTableData() {
    $(el.tbDetails).datagrid('loadData', {total: 0, rows: []});
    $(el.tbDeduction).datagrid('loadData', {total: 0, rows: []});
    $(el.tbRebate).datagrid('loadData', {total: 0, rows: []});

    // 顺便清空页面输入的值
    $(el.deductionAmount).numberbox('setValue', 0);
    $(el.dntAmount).val('');
    $(el.rebateAmount).numberbox('setValue', 0);
    $(el.rntAmount).val('');
    $(el.invoiceNetAmount).textbox('setValue', '');
    $(el.invoiceTaxAmount).textbox('setValue', '');
}


/**
 * 获取当前用户表格列布局
 */
function findUserTableColumn() {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'fin/table/column/rest/user/setting?pageTable=3&isAuthority=0',
        async: false,
        success: function (data) {
            for(var i = 0; i < data.length; i++){
                el.userTableColumn.push(data[i].columnField);
            }
        }
    });
}


/**
 * 动态表格列
 */
function dynamicColumns(orderType) {
    var result = [];
    for(var i = 0; i < el.userTableColumn.length; i++){
        var columnField = el.userTableColumn[i];

        for(var j = 0; j < tableColumns.length; j++){
            var column =  tableColumns[j];
            if(column.field === columnField){

                if(column.field === 'materialSupplierCode' || column.field === 'materialSupplierName' || column.field === 'freightType'){
                    column.hidden = Number(orderType) === 1;
                }

                result.push(column);
                break;
            }
        }
    }
    return result;
}


// 报表所有列
var tableColumns = [
    {
        field: 'statementNum',
        title: '对账数量',
        width: 70,
        sortable: true,
        formatter: function (value) {
            if(Number(value) < 0){
                return '<span style="color: red;">' + value + '</span>';
            }
            return value;
        }
    },
    {
        field: 'asTaxCodeDesc',
        title: '对账税率',
        width: 160,
        sortable: true
    },
    {
        field: 'asTaxPrice',
        title: '对账含税单价',
        width: 100,
        sortable: true
    },
    {
        field: 'asTaxAmount',
        title: '对账含税金额',
        width: 100,
        sortable: true,
        formatter: function (value) {
            if(Number(value) < 0){
                return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
            }
            return formatNumber(value, 2, 1);
        }
    },
    {
        field: 'asNotTaxPrice',
        title: '对账未税单价',
        width: 100,
        sortable: true
    },
    {
        field: 'asNotTaxAmount',
        title: '对账未税金额',
        width: 100,
        sortable: true,
        formatter: function (value) {
            if(Number(value) < 0){
                return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
            }
            return formatNumber(value, 2, 1);
        }
    },
    {
        field: 'asDiffTaxAmount',
        title: '对账税额',
        width: 100,
        sortable: true,
        formatter: function (value) {
            if(Number(value) < 0){
                return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
            }
            return formatNumber(value, 2, 1);
        }
    },
    {
        field: 'zlsdh',
        title: 'SC订单号',
        width: 100,
        sortable: true
    },
    {
        field: 'poCode',
        title: 'SAP订单号',
        width: 100,
        sortable: true
    },
    {
        field: 'poItemNo',
        title: '订单行号',
        width: 70,
        sortable: true
    },
    {
        field: 'pgCode',
        title: '采购组编码',
        width: 70,
        sortable: true
    },
    {
        field: 'pgName',
        title: '采购组名称',
        width: 70,
        sortable: true
    },
    {
        field: 'materialCode',
        title: '物料编码',
        width: 90,
        sortable: true
    },
    {
        field: 'materialName',
        title: '物料名称',
        width: 320,
        sortable: true
    },
    {
        field: 'specs',
        title: '规格',
        width: 120
    },
    {
        field: 'receiveCode',
        title: '入库凭证号',
        width: 100,
        sortable: true
    },
    {
        field: 'receiveRowNo',
        title: '凭证行号',
        width: 70,
        sortable: true
    },
    {
        field: 'receiveDate',
        title: '入库日期',
        width: 100,
        sortable: true
    },
    {
        field: 'inOutFlag',
        title: '出入库标识',
        width: 85,
        sortable: true
    },
    {
        field: 'asNo',
        title: '对账单号',
        width: 120,
        sortable: true
    },
    {
        field: 'asdItemNo',
        title: '对账单行号',
        width: 80,
        sortable: true
    },
    {
        field: 'paymentTermCodeName',
        title: '付款条件',
        width: 80,
        sortable: true
    },
    {
        field: 'contractNo',
        title: '合同号',
        width: 120
    },
    {
        field: 'purchaseUser',
        title: '采购员',
        width: 120
    }
];
/**
 * 检查数组元素是否都相同
 *
 * @param array 待检查数组
 * @returns {boolean} 结果
 */
function checkIsAllEqual(array) {
    if (array.length > 0) {
        return !array.some(function (value, index) {
            return value !== array[0];
        });
    } else {
        return true;
    }
}

