/**
 * 对账模块-对账单采购审批页面
 *
 * Created by li.kui on 2020/8/4.
 */
'use strict';
var el = {
    dataPanel: '#dataPanel',
    dataDiv: '#dataDiv',
    id: '#id',
    orderType: '#orderType',
    supplierCode: '#supplierCode',
    companyCode: '#companyCode',
    factoryCode: '#factoryCode',
    currencyCode: '#currencyCode',
    deductionAmount: '#deductionAmount',
    rebateAmount: '#rebateAmount',
    inStockStartDate: '#inStockStartDate',
    inStockEndDate: '#inStockEndDate',
    notTaxAmount: '#notTaxAmount',
    taxAmount: '#taxAmount',
    remark: '#remark',

    bpPayableBalance: '#bpPayableBalance',
    bpEstimateBalance: '#bpEstimateBalance',
    etPayableBalance: '#etPayableBalance',
    etEstimateBalance: '#etEstimateBalance',
    currPaymentAmount: '#currPaymentAmount',
    invoiceFileId: '#invoiceFileId',
    invoiceFiles: '#invoiceFiles',

    approveOpinion: '#approveOpinion',
    dataTabs: '#dataTabs',
    tbDetails: '#tbDetails',
    tbDeduction: '#tbDeduction',
    tbRebate: '#tbRebate',
    tbApproveLog: '#tbApproveLog',
    purchaseGroup: '#purchaseGroup',
    poType: '#poType',
    paymentTermCode: '#paymentTermCode',
    addDetailDialog: null,
    choseRebateDataDialog: null,
    choseDeductionDataDialog: null,
    delDetail: [],
    delDeduction: [],
    delRebate: [],
    editIndex: undefined,
    taxDict: [],
    userTableColumn: [],
    bodyHeight: document.documentElement.clientHeight
};


/**
 * 文档就绪
 */
$(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.tbApproveLog).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.tbApproveLog).datagrid('resize', {height: el.bodyHeight - dataDiv});
        }
    });


    // 获取当前用户配置的列表列顺序
    findUserTableColumn();

    // 获取系统税率数据
    findTaxDictData();

    // 初始化对账单明细表格
    initTbDetails();
    // 初始化对账单返利表格
    // initTbRebate();
    // 初始化对账单扣款表格
    // initTbDeduction();
    // 初始化对账单审批记录表格
    initTbApproveLog();

    // 付款条件
    $(el.paymentTermCode).combobox({
        panelHeight: 'auto',
        panelWidth: 200,
        valueField: 'dicCode',
        textField: 'dicTxt',
        prompt: '--- 请选择 ---',
        url: '/dic/getDicByType?type=supplier_fktj'
    });
    //采购组
    $(el.purchaseGroup).combobox({
        editable: true,
        required: false,
        valueField: 'purchaseGroupCode',
        textField: 'purchaseGroupName',
        panelHeight: '150',
        url: '/purchase/group/rest/list/all'
    });

    $(el.poType).combobox({
        panelHeight: 'auto',
        panelWidth: 200,
        valueField: 'dicCode',
        textField: 'dicTxt',
        multiple: true,
        prompt: '--- 请选择 ---',
        url: '/dic/getDicByType?type=po_type'
    });
    getExchangeRate($(el.currencyCode).textbox('getValue'));
});


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

    $(el.tbDetails).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'fin/account/statement/detail/rest/find/by/statement/id',
        singleSelect: false,
        showFooter: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        queryParams: {
            asId: $(el.id).val()
        },
        frozenColumns: [
            [
                {
                    field: 'ck',
                    checkbox: true
                }
            ]
        ],
        columns: [
            tableColumns
        ],
        toolbar: [
            // {
            //     text: '添加',
            //     iconCls: 'icon-add',
            //     handler: function () {
            //         addVoucherData();
            //     }
            // },
            // '-',
            // {
            //     text: '删除',
            //     iconCls: 'icon-remove',
            //     handler: function () {
            //         delStatementItem();
            //     }
            // },
            '-',
            {
                text: '导出',
                iconCls: 'icon-download',
                handler: function () {
                    detailExport();
                }
            },
            // '-',
            // {
            //     text: '调整布局',
            //     iconCls: 'icon-man',
            //     handler: function () {
            //         adjustTableColumn();
            //     }
            // }
        ],
        onLoadSuccess: function (data) {
            calculationAmount(data.rows);
        },
        onClickRow: function (index, row) {
            if (el.editIndex !== undefined) {
                if(endEditor()){
                    if(Number(row.editFlag) === 0){
                        topWin.layer.msg('该行不可以编辑');
                        return false;
                    }
                    $(el.tbDetails).datagrid('beginEdit', index);
                    el.editIndex = index;
                }
            }else {
                if(Number(row.editFlag) === 0){
                    topWin.layer.msg('该行不可以编辑');
                    return false;
                }
                $(el.tbDetails).datagrid('beginEdit', index);
                el.editIndex = index;
            }
        }
    });
}




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

    $(el.tbApproveLog).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'fin/account/statement/detail/rest/find/as/approve/log',
        singleSelect: false,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        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>';
                            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 addVoucherData() {
    var companyCode = $(el.companyCode).val(), factoryCode = $(el.factoryCode).val(), currencyCode = $(el.currencyCode).val(),
        supplierCode = $(el.supplierCode).val(), inStockStartDate = $(el.inStockStartDate).datebox('getValue'),
        inStockEndDate = $(el.inStockEndDate).datebox('getValue'), orderType = $(el.orderType).val();
    var rows = $(el.tbDetails).datagrid('getRows'), alreadyExistId = [];
    for(var i = 0; i < rows.length; i++){
        alreadyExistId.push(rows[i].receiveId);
    }

    var url = g.ctx + 'fin/account/statement/chose/voucher/dialog' +
        '?orderType=' + orderType + '&companyCode=' + companyCode + '&factoryCode=' + factoryCode +
        '&supplierCode=' + supplierCode + '&currencyCode=' + currencyCode + '&inStockStartDate=' + inStockStartDate +
        '&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.itemNo = '';
                            row.asId = $(el.id).val();
                            row.asQuantity = item.asQuantity;
                            row.surplusNum = item.surplusNum;
                            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.paymentTermCode = item.paymentTermCode;
                            row.paymentTermName = item.paymentTermName;
                            row.paymentTermCodeName = item.paymentTermCodeName;
                            row.paymentWayCode = item.paymentWayCode;
                            row.paymentWayDesc = item.paymentWayDesc;
                            row.paymentWayCodeDesc = item.paymentWayCodeDesc;
                            row.poCode = item.poCode;
                            row.poItemNo = item.poItemNo;
                            row.priceUnit = item.priceUnit;
                            row.seekPgCode = item.seekPgCode;
                            row.seekPgName = item.seekPgName;
                            row.seekPgCodeName = item.seekPgCodeName;
                            row.orderNotTaxPrice = item.orderNotTaxPrice;
                            row.orderTaxPrice = item.orderTaxPrice;
                            row.orderNotTaxAmount = item.orderNotTaxAmount;
                            row.orderTaxAmount = item.orderTaxAmount;
                            row.orderTaxCode = item.orderTaxCode;
                            row.orderTaxValue = item.orderTaxValue;
                            row.orderTaxDesc = item.orderTaxDesc;
                            row.orderTaxCodeDesc = item.orderTaxCodeDesc;
                            row.taxCode = item.taxCode;
                            row.taxValue = item.taxValue;
                            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.asDiffPrice = 0;
                            row.asDiffAmount = 0;
                            row.materialSupplierCode = item.materialSupplierCode;
                            row.materialSupplierName = item.materialSupplierCode;
                            row.freightType = item.freightType;
                            row.editFlag = item.editFlag;
                            row.invoicedAmount = item.invoicedAmount;
                            row.surplusAmount = item.surplusAmount;
                            row.asNtAmount = (item.surplusNum * item.orderNotTaxPrice).toFixed(2);
                            row.asItAmount = (item.surplusNum * item.orderTaxPrice).toFixed(2);

                            $(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 + 'fin/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 addDeductionData() {
    var companyCode = $(el.companyCode).val(), supplierCode = $(el.supplierCode).val();
    var tempDelDmId = [];
    for(var i = 0; i < el.delDeduction.length; i++){
        tempDelDmId.push(el.delDeduction[i].deductionId);
    }

    // 获取已存在的返利数据
    var rows = $(el.tbDeduction).datagrid('getRows'), didArray = [];
    for(var m = 0; m < rows.length; m++){
        didArray.push(rows[m].deductionId);
    }

    var url = g.ctx + 'fin/account/statement/chose/deduction/dialog' +
        '?companyCode=' + companyCode + '&supplierCode=' + supplierCode +
        '&selectedDmId=' + didArray.join(',') + '&tempDelDmId=' + tempDelDmId.join(',');

    el.choseDeductionDataDialog = openDialog('choseDeductionData', url, {
        title: '扣款信息选择',
        width: '70%',
        height: '560px',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.choseDeductionDataDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseDeductionData'].confirmChose(function (data) {
                        for(var n = 0; n < data.length; n++){
                            var item = data[n], row = {};
                            row.id = 0;
                            row.asId = $(el.id).val();
                            row.deductionId = item.id;
                            row.deductionNo = item.deductionNo;
                            row.deductionType = item.deductionType;
                            row.deductionTypeDesc = item.deductionTypeDesc;
                            row.associatedNo = item.associatedNo;
                            row.associatedRowNo = item.associatedRowNo;
                            row.associatedOaNo = item.associatedOaNo;
                            row.companyCode = item.companyCode;
                            row.companyName = item.companyName;
                            row.createTime = item.createTime;
                            row.createUserCode = item.createUserCode;
                            row.createUserName = item.createUserName;
                            row.createUserId = item.createUserId;
                            row.deductionAmount = item.deductionAmount;
                            row.taxValue = item.taxValue;
                            row.taxCode = item.taxCode;
                            row.taxCodeDesc = item.taxCodeDesc;
                            row.deductionAmount = item.deductionAmount;
                            row.supplierCode = item.supplierCode;
                            row.supplierName = item.supplierName;
                            row.deductionReason = item.deductionReason;
                            row.deductionTime = item.deductionTime;

                            if($.inArray(item.id, didArray) === -1){
                                $(el.tbDeduction).datagrid('appendRow', row);
                            }
                        }

                        calculationDeductionAmount($(el.tbDeduction).datagrid('getRows'));
                        el.choseDeductionDataDialog.dialog('close');
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.choseDeductionDataDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 删除扣款信息
 */
function delStatementDeduction() {
    var rows = $(el.tbDeduction).datagrid('getSelections');
    if(rows.length === 0){
        topWin.layer.alert('请选择您要删除的扣款信息', {icon: 0});
        return false;
    }

    for(var i = 0; i < rows.length; i++){
        var row = rows[i];
        if(row.id){
            el.delDeduction.push(row);
        }
        var rowIndex = $(el.tbDeduction).datagrid('getRowIndex', row);
        $(el.tbDeduction).datagrid('deleteRow', rowIndex);
    }

    calculationDeductionAmount($(el.tbDeduction).datagrid('getRows'));
}


/**
 * 添加返利数据
 */
function addRebateData() {
    var companyCode = $(el.companyCode).val(), supplierCode = $(el.supplierCode).val();
    var tempDelRmId = [];
    for(var i = 0; i < el.delRebate.length; i++){
        tempDelRmId.push(el.delRebate[i].rebateId);
    }

    // 获取已存在的返利数据
    var rows = $(el.tbRebate).datagrid('getRows'), ridArray = [];
    for(var m = 0; m < rows.length; m++){
        ridArray.push(rows[m].rebateId);
    }

    var url = g.ctx + 'fin/account/statement/chose/rebate/dialog' +
        '?companyCode=' + companyCode + '&supplierCode=' + supplierCode +
        '&selectedRmId=' + ridArray.join(',') + '&tempDelRmId=' + tempDelRmId.join(',');

    el.choseRebateDataDialog = openDialog('choseRebateData', url, {
        title: '返利信息选择',
        width: '70%',
        height: '560px',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.choseRebateDataDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['choseRebateData'].confirmChose(function (data) {
                        for(var n = 0; n < data.length; n++){
                            var item = data[n], row = {};
                            row.id = 0;
                            row.asId = $(el.id).val();
                            row.companyCode = item.companyCode;
                            row.companyName = item.companyName;
                            row.createTime = item.createTime;
                            row.createUserCode = item.createUserCode;
                            row.createUserName = item.createUserName;
                            row.createUserId = item.createUserId;
                            row.rebateAmount = item.rebateAmount;
                            row.rebateId = item.id;
                            row.rebateNo = item.rebateNo;
                            row.rebateReason = item.rebateReason;
                            row.rebateType = item.rebateType;
                            row.rebateTime = item.rebateTime;
                            row.supplierCode = item.supplierCode;
                            row.supplierName = item.supplierName;
                            row.taxCode = item.taxCode;
                            row.taxValue = item.taxValue;
                            row.taxCodeDesc = item.taxCodeDesc;

                            if($.inArray(item.id, ridArray) === -1){
                                $(el.tbRebate).datagrid('appendRow', row);
                            }
                        }

                        calculationRebateAmount($(el.tbRebate).datagrid('getRows'));
                        el.choseRebateDataDialog.dialog('close');
                    });
                }
            },
            {
                text: '关闭',
                iconCls: 'icon-cancel',
                handler: function () {
                    el.choseRebateDataDialog.dialog('close');
                }
            }
        ]
    });
}


/**
 * 删除返利数据
 */
function delStatementRebateData() {
    var rows = $(el.tbRebate).datagrid('getSelections');
    if(rows.length === 0){
        topWin.layer.alert('请选择您要删除的返利信息', {icon: 0});
        return false;
    }

    for(var i = 0; i < rows.length; i++){
        var row = rows[i];
        if(row.id){
            el.delRebate.push(row);
        }
        var rowIndex = $(el.tbRebate).datagrid('getRowIndex', row);
        $(el.tbRebate).datagrid('deleteRow', rowIndex);
    }

    calculationRebateAmount($(el.tbRebate).datagrid('getRows'));
}


/**
 * 数据保存
 *
 * @param callback 回调函数
 */
function dataSave(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(),
        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;
        }

        // 存在冲销凭证的正向凭证需校验
        // if(Number(item.editFlag) === 1){
        //     // 当 minStatementQuantity小于0时, 说明入库凭证为退货订单(161)
        //     if(Number(item.minStatementQuantity) < 0){
        //         if(Number(item.asQuantity) >= 0){
        //             topWin.layer.alert('入库凭证: ' + item.receiveCode + '#' + item.receiveRowNo + ', 确认对账数量不能大于等于0', {icon: 0});
        //             return false;
        //         }
        //         if(Number(item.asQuantity) < Number(item.minStatementQuantity)){
        //             topWin.layer.alert('入库凭证: ' + item.receiveCode + '#' + item.receiveRowNo + ', 确认对账数量不能小于可用数量', {icon: 0});
        //             return false;
        //         }
        //     }else {
        //         if(Number(item.asQuantity) <= 0){
        //             topWin.layer.alert('入库凭证: ' + item.receiveCode + '#' + item.receiveRowNo + ', 确认对账数量不能小于等于0', {icon: 0});
        //             return false;
        //         }
        //         if(Number(item.asQuantity) <= Number(item.minStatementQuantity)){
        //             topWin.layer.alert('入库凭证: ' + item.receiveCode + '#' + item.receiveRowNo + ', 存在冲销, 故确认对账数量不能小于等于冲销数量. 冲销数量合计为: ' + item.minStatementQuantity, {icon: 0});
        //             return false;
        //         }
        //     }
        // }

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

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

    // 需要校验凭证汇总含税金额 - (扣款金额 + 返利金额) > 0
    // var diff = itSumAmount.plus(deductionAmount).plus(rebateAmount);
    // if(diff.lt(0)){
    //     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;
    }
    // 明细删除
    for(var i2 = 0; i2 < el.delDetail.length; i2++){
        dsiId.push(el.delDetail[i2].id);
    }

    // 返利数据: reDate->返利表格数据; rebateIds->新增的返利记录ID; drId->删除的返利记录ID
    // var reDate = $(el.tbRebate).datagrid('getRows'), rebateIds = [], drId = [];
    // for(var k1 = 0; k1 < el.delRebate.length; k1++){
    //     drId.push(el.delRebate[k1].rebateId);
    // }
    // for(var k2 = 0; k2 < reDate.length; k2++){
    //     var reItem = reDate[k2];
    //     if(!reItem.id){
    //         rebateIds.push(reDate[k2].rebateId);
    //     }
    //
    //     if(taxData.indexOf(reItem.taxCode) < 0){
    //         topWin.layer.alert('对账单绑定的返利记录中税率不一致情况, 返利单号: ' + reItem.rebateNo, {icon: 0});
    //         return false;
    //     }
    // }

    // 扣款数据: debate->扣款表格数据; deductionIds->新增的扣款记录ID; ddId->删除的扣款记录ID
    // var deDate = $(el.tbDeduction).datagrid('getRows'), deductionIds = [], ddId = [];
    // for(var j1 = 0; j1 < el.delDeduction.length; j1++){
    //     ddId.push(el.delDeduction[j1].deductionId);
    // }
    // for(var j2 = 0; j2 < deDate.length; j2++){
    //     var deItem = deDate[j2];
    //     if(!deItem.id){
    //         deductionIds.push(deDate[j2].deductionId);
    //     }
    //
    //     if(taxData.indexOf(deItem.taxCode) < 0){
    //         topWin.layer.alert('对账单绑定的扣款记录中税率不一致情况, 扣款单号: ' + deItem.deductionNo, {icon: 0});
    //         return false;
    //     }
    // }

    var result = {};
    result.approveOpinion = approveOpinion;
    result.headData = headData;
    result.statementItem = statementItem;
    result.delSiIds = dsiId;
    // result.addDeductionIds = deductionIds;
    // result.delDeductionIds = ddId;
    // result.addRebateIds = rebateIds;
    // result.delRebateIds = drId;

    callback(result);
}


/**
 * 拒绝对账单
 *
 * @param callback 回调函数
 */
function refuseStatement(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);
}


/**
 * 计算页面相关金额
 */
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), availableQuantity = new BigNumber(0),
        asNtAmount = new BigNumber(0), asItAmount = new BigNumber(0), asDiffAmount = 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);
        asDiffAmount = asDiffAmount.plus(item.asDiffAmount);
        asNtAmount = asNtAmount.plus(item.asNtAmount);
        asItAmount = asItAmount.plus(item.asItAmount);

        invoicedAmount = invoicedAmount.plus(item.invoicedAmount);
        surplusAmount = surplusAmount.plus(item.surplusAmount);

        storageQuantity = storageQuantity.plus(item.receiveNum);
        statementQuantity = statementQuantity.plus(item.asQuantity);
        availableQuantity = availableQuantity.plus(item.surplusNum);
    }

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

    // 更新页脚行的值并刷新
    var footers = $(el.tbDetails).datagrid('getFooterRows');
    footers[0]['taxAmount'] = taxAmount.toFixed(2);
    footers[0]['notTaxAmount'] = notTaxAmount.toFixed(2);
    footers[0]['diffTaxAmount'] = taxAmount.minus(notTaxAmount).toFixed(2);
    footers[0]['asDiffAmount'] = asDiffAmount.toFixed(2);
    footers[0]['invoicedAmount'] = invoicedAmount.toFixed(2);
    footers[0]['surplusAmount'] = surplusAmount.toFixed(2);
    footers[0]['asNtAmount'] = asNtAmount.toFixed(2);
    footers[0]['asItAmount'] = asItAmount.toFixed(2);
    footers[0]['surplusNum'] = availableQuantity.toFixed(2);
    footers[0]['receiveNum'] = storageQuantity.toFixed(3);
    footers[0]['asQuantity'] = statementQuantity.toFixed(3);
    $(el.tbDetails).datagrid('reloadFooter');
}


/**
 * 计算返利金额
 *
 * @param data 返利表格数据
 */
function calculationRebateAmount(data) {
    var rebateAmount = new BigNumber(0);
    for(var j = 0; j < data.length; j++){
        // 1:购方对供方返利 2:供方对购方返利
        if(Number(data[j].rebateType) === 1){
            rebateAmount = rebateAmount.plus(data[j].rebateAmount);
        }else {
            rebateAmount = rebateAmount.minus(data[j].rebateAmount);
        }
    }

    $(el.rebateAmount).numberbox('setValue', rebateAmount.toFixed());

    // 更新页脚行的值并刷新
    var footers = $(el.tbRebate).datagrid('getFooterRows');
    footers[0]['rebateAmount'] = rebateAmount.toFixed();
    $(el.tbRebate).datagrid('reloadFooter');
}


/**
 * 计算扣款金额
 *
 * @param rows 扣款表格数据
 */
function calculationDeductionAmount(rows) {
    var deductionAmount = new BigNumber(0);
    for(var i = 0; i < rows.length; i++){
        deductionAmount = deductionAmount.plus(rows[i].deductionAmount);
    }

    $(el.deductionAmount).numberbox('setValue', deductionAmount.toFixed());

    // 更新页脚行的值并刷新
    var footers = $(el.tbDeduction).datagrid('getFooterRows');
    footers[0]['deductionAmount'] = deductionAmount.toFixed();
    $(el.tbDeduction).datagrid('reloadFooter');
}


/**
 * 获取税率字典数据
 */
function findTaxDictData() {
    $.ajax({
        type: 'GET',
        url: g.ctx + 'pc/sys/tax/rest/listAll',
        async: false,
        success: function (data) {
            for(var i = 0; i < data.length; i++){
                var obj = {};
                obj.itemCode = data[i].taxCode;
                obj.itemName = data[i].taxName;
                obj.itemValue = data[i].taxValue;
                obj.itemRemark = data[i].taxName
                el.taxDict.push(obj);
            }
        }
    });
}


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

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


/**
 * 结束编辑
 *
 * @return {boolean}
 */
function endEditor() {
    // 结束行编辑
    $(el.tbDetails).datagrid('endEdit', el.editIndex);
    $(el.tbDetails).datagrid('unselectRow', el.editIndex);
    el.editIndex = undefined;
    return true;
}


/**
 * 更新行数数据
 *
 * @param data 修改后的数据
 * @param editColumn 编辑的列名
 */
function updateRowData(data, editColumn) {
    var row = {}, rows = $(el.tbDetails).datagrid('getRows');
    for(var i = 0; i < rows.length; i++){
        var rowIndex = $(el.tbDetails).datagrid('getRowIndex', rows[i]);
        if(rowIndex === el.editIndex){
            row = rows[i];
            break;
        }
    }

    // 税率转换: 1 + 税率
    var taxConvert = new BigNumber(1).plus(row.taxValue / 100);

    // 对账数量 -> 联动变更的行数据 对账未税金额、对账含税金额、对账税额、订单未税金额、订单含税金额
    if('asQuantity' === editColumn){
        // 修改后的数据
        var ud1 = new BigNumber(data);

        // 对账含税金额 = 对账确认数量 * 含税单价
        var taxAmount1 = ud1.multipliedBy(row.taxPrice);
        // 对账未税金额 = 对账含税金额 / (1 + 税率)
        var notTaxAmount1 = taxAmount1.div(taxConvert);
        // // 对账税额 = 对账含税金额 - 对账不含税金额
        // var diffTaxAmount1 = taxAmount1.sub(notTaxAmount1);
        // 对账税额 = 对账含税金额(四舍五入保留2位) - 对账不含税金额(四舍五入保留2位)
        var diffTaxAmount1 = Number(taxAmount1.toFixed(2)) - Number(notTaxAmount1.toFixed(2));
        // 对账差异含税金额 = 对账数量 * 对账差异含税单价
        var asDiffAmount1 = ud1.multipliedBy(row.asDiffPrice);
        // 对账时订单含税金额
        var asItAmount = ud1.multipliedBy(row.orderTaxPrice);
        // 对账时订单未税金额
        var asNtAmount = ud1.multipliedBy(row.orderNotTaxPrice);

        // 更新Editor列数据(initValue 不触发numberBox的onChange事件)
        var notTaxAmountTarget1 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex, field: 'notTaxAmount'}).target;
        notTaxAmountTarget1.numberbox('initValue', Number(notTaxAmount1.toFixed(2)));
        var diffTaxAmountTarget1 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex, field: 'diffTaxAmount'}).target;
        diffTaxAmountTarget1.numberbox('initValue', Number(diffTaxAmount1.toFixed(2)));

        // 更新非Editor列数据
        var columns1 = ['taxAmount', 'asDiffAmount', 'asItAmount', 'asNtAmount'];
        var columnsData1 = [
            Number(taxAmount1.toFixed(2)), Number(asDiffAmount1.toFixed(2)), Number(asItAmount.toFixed(2)),
            Number(asNtAmount.toFixed(2))
        ];
        var ed1 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'asQuantity'});
        updatePageShowValue($(ed1.target).parents('td[field="asQuantity"]'), row, columns1, columnsData1);

        row.asQuantity = ud1.toNumber();
        row.notTaxAmount = Number(notTaxAmount1.toFixed(2));
        row.diffTaxAmount = Number(diffTaxAmount1.toFixed(2));
    }

    // 对账含税单价 -> 联动变更的行数据: 对账不含税单价、对账差异含税单价、对账不含税金额、对账含税金额、对账差异含税金额、对账税额
    if('taxPrice' === editColumn){
        // 修改后的数据
        var ud2 = new BigNumber(data);

        // 对账不含税单价 = 对账含税单价 / (1 + 税率)
        var notTaxPrice2 = ud2.div(taxConvert);
        // 对账差异含税单价 = 对账含税单价 - 原对账含税单价
        var asDiffPrice2 = ud2.minus(row.orderTaxPrice);
        // 对账含税金额 = 对账确认数量 * 对账含税单价
        var taxAmount2 = ud2.mul(row.asQuantity);
        // 对账未税金额 = 对账含税金额 / (1 + 税率)
        var notTaxAmount2 = taxAmount2.div(taxConvert);
        // 对账差异含税金额 = 对账数量 * 对账差异含税单价
        var asDiffAmount2 = asDiffPrice2.mul(row.asQuantity);
        // // 对账税额 = 对账含税金额 - 对账未税金额
        // var diffTaxAmount2 = taxAmount2.sub(notTaxAmount2);
        // 对账税额 = 对账含税金额(四舍五入保留2位) - 对账不含税金额(四舍五入保留2位)
        var diffTaxAmount2 = Number(taxAmount2.toFixed(2)) - Number(notTaxAmount2.toFixed(2));

        // 更新Editor列数据(initValue 不触发numberBox的onChange事件)
        var notTaxAmountTarget2 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'notTaxAmount'}).target;
        notTaxAmountTarget2.numberbox('initValue', Number(notTaxAmount2.toFixed(2)));
        var diffTaxAmountTarget2 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex, field: 'diffTaxAmount'}).target;
        diffTaxAmountTarget2.numberbox('initValue', Number(diffTaxAmount2.toFixed(2)));

        // 更新非Editor列数据
        var columns2 = ['asDiffPrice', 'taxAmount', 'asDiffAmount', 'notTaxPrice'];
        var columnsData2 = [
            Number(asDiffPrice2.toFixed(6)), Number(taxAmount2.toFixed(2)), Number(asDiffAmount2.toFixed(2)),
            Number(notTaxPrice2.toFixed(6))
        ];
        var ed2 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'taxPrice'});
        updatePageShowValue($(ed2.target).parents('td[field="taxPrice"]'), row, columns2, columnsData2);

        row.taxPrice = ud2.toNumber();
        row.notTaxAmount = Number(notTaxAmount2.toFixed(2));
        row.diffTaxAmount = Number(diffTaxAmount2.toFixed(2));
    }

    // 对账未税金额 -> 联动变更的行数据 对账含税金额、对账差异含税金额、对账含税单价、对账不含税单价、对账差异含税单价
    if('notTaxAmount' === editColumn){
        // 修改后的数据
        var ud3 = new BigNumber(data);

        // 对账含税金额 = 对账未税金额 + 税额
        var taxAmount3 = ud3.plus(row.diffTaxAmount);
        // 对账含税单价 = 对账含税金额 / 对账数量
        var taxPrice3 = taxAmount3.div(row.asQuantity);
        // 对账未税单价 = 对账含税单价 / (1 + 税率)
        var notTaxPrice3 = taxPrice3.div(taxConvert);
        // 对账差异含税单价 = 对账含税单价 - 原对账含税单价
        var asDiffPrice3 = taxPrice3.minus(row.orderTaxPrice);
        // 对账差异含税金额 = 对账数量 * 对账差异含税单价
        var asDiffAmount3 = asDiffPrice3.mul(row.asQuantity);

        // 更新Editor列数据(initValue 不触发numberBox的onChange事件)
        var taxPriceTarget1 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'taxPrice'}).target;
        taxPriceTarget1.numberbox('initValue', Number(taxPrice3.toFixed(6)));

        // 更新非Editor列数据
        var columns3 = ['taxAmount', 'asDiffAmount', 'notTaxPrice', 'asDiffPrice'];
        var columnsData3 = [
            Number(taxAmount3.toFixed(2)), Number(asDiffAmount3.toFixed(2)), Number(notTaxPrice3.toFixed(6)),
            Number(asDiffPrice3.toFixed(6))
        ];
        var ed3 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'notTaxAmount'});
        updatePageShowValue($(ed3.target).parents('td[field="notTaxAmount"]'), row, columns3, columnsData3);

        row.notTaxAmount = ud3.toNumber();
        row.taxPrice = Number(taxPrice3.toFixed(6));
    }

    // 对账税率 -> 联动变更的行数据 对账未税单价、对账未税金额、对账税额
    if('taxCodeDesc' === editColumn){
        var taxData = {};
        for(var j = 0; j < el.taxDict.length; j++){
            if(el.taxDict[j].itemName === data){
                taxData = el.taxDict[j];
                break;
            }
        }
        // 税率转换
        var tax = taxData.itemValue.replace('%', '');
        taxConvert = new BigNumber(1).plus(tax / 100);

        // 对账未税单价 = 含税单价 / (1 + 税率)
        var notTaxPrice4 = new BigNumber(row.taxPrice).div(taxConvert);
        // 对账未税金额 = 对账未税单价 * 数量
        var notTaxAmount4 = new BigNumber(row.taxAmount).div(taxConvert);
        // // 对账税额 = 对账含税金额 - 对账未税金额
        // var diffTaxAmount4 = new BigNumber(row.taxAmount).sub(notTaxAmount4);
        // 对账税额 = 对账含税金额(四舍五入保留2位) - 对账不含税金额(四舍五入保留2位)
        var diffTaxAmount4 = Number(row.taxAmount.toFixed(2)) - Number(notTaxAmount4.toFixed(2));

        // 更新Editor列数据(initValue 不触发numberBox的onChange事件)
        var notTaxAmountTarget4 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'notTaxAmount'}).target;
        notTaxAmountTarget4.numberbox('initValue', Number(notTaxAmount4.toFixed(2)));

        var diffTaxAmountTarget4 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'diffTaxAmount'}).target;
        diffTaxAmountTarget4.numberbox('initValue', Number(diffTaxAmount4.toFixed(2)));

        // 更新非Editor列数据
        var columns4 = ['notTaxPrice'];
        var columnsData4 = [Number(notTaxPrice4.toFixed(6))];
        var ed4 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'taxCodeDesc'});
        updatePageShowValue($(ed4.target).parents('td[field="taxCodeDesc"]'), row, columns4, columnsData4);

        // 更新非页面显示列数据
        row.taxCode = taxData.itemCode;
        row.taxValue = Number(tax);
        row.notTaxAmount = Number(notTaxAmount4.toFixed(2));
        row.diffTaxAmount = Number(diffTaxAmount4.toFixed(2));
    }

    // 对账税额 -> 联动变更的行数据 对账含税金额、对账差异含税金额、对账含税单价、对账差异含税单价
    if('diffTaxAmount' === editColumn){
        // 修改后的数据
        var ud5 = new BigNumber(data);

        // 对账含税金额 = 对账未税金额 + 税额
        var taxAmount5 = ud5.plus(row.notTaxAmount);
        // 对账含税单价 = 对账含税金额 / 对账数量
        var taxPrice5 = taxAmount5.div(row.asQuantity);
        // 对账差异含税单价 = 对账含税单价 - 原对账含税单价
        var asDiffPrice5 = taxPrice5.minus(row.orderTaxPrice);
        // 对账差异含税金额 = 对账数量 * 对账差异含税单价
        var asDiffAmount5 = asDiffPrice5.mul(row.asQuantity);

        // 更新Editor列数据(initValue 不触发numberBox的onChange事件)
        var taxPriceTarget5 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'taxPrice'}).target;
        taxPriceTarget5.numberbox('initValue', Number(taxPrice5.toFixed(6)));

        // 更新非Editor列数据
        var columns5 = ['taxAmount', 'asDiffAmount', 'asDiffPrice'];
        var columnsData5 = [
            Number(taxAmount5.toFixed(2)), Number(asDiffAmount5.toFixed(2)), Number(asDiffPrice5.toFixed(2))
        ];
        var ed5 = $(el.tbDetails).datagrid('getEditor', {index: el.editIndex,field: 'diffTaxAmount'});
        updatePageShowValue($(ed5.target).parents('td[field="diffTaxAmount"]'), row, columns5, columnsData5);

        row.diffTaxAmount = ud5.toNumber();
        row.taxPrice = Number(taxPrice5.toFixed(6));
    }

    calculationAmount($(el.tbDetails).datagrid('getRows'));
}


/**
 * 更新页面表格显示列值
 *
 * @param girdTr 表格行DOM
 * @param oriRowData 原表格行数据
 * @param columns 需要更新的列名
 * @param columnsData 列名对应的值
 */
function updatePageShowValue(girdTr, oriRowData, columns, columnsData) {
    for(var i = 0; i < columns.length; i++){
        var value = columnsData[i], column = columns[i], htmlValue = '';
        var valueNumber = new BigNumber(value);
        if(Number(value) < 0){
            htmlValue = '<span style="color: red;">' + valueNumber.toFormat() + '</span>'
        }else {
            htmlValue = valueNumber.toFormat();
        }
        girdTr.siblings('td[field="' + column + '"]').find('div').html(htmlValue);
        oriRowData[column] = valueNumber.toNumber();
    }
}


/**
 * 查看扣款或返利附件
 *
 * @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');
                }
            }
        ]
    });
}


/**
 * 检查数组元素是否都相同
 *
 * @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 adjustTableColumn() {
    var url = g.ctx + 'fin/common/adjust/table/column?pageTable=2';
    el.adjustTableColumnDialog = openDialog('adjustTableColumn', url, {
        title: '调整表格列布局',
        width: '970px',
        height: '80%',
        cache: false,
        modal: true,
        border: 'thin',
        onClose: function () {
            el.adjustTableColumnDialog.dialog('destroy');
        },
        buttons: [
            {
                text: '确定并保存设置',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['adjustTableColumn'].confirmAndSaveSetUp(function (data) {
                        el.userTableColumn = [];
                        for(var i = 0; i < data.length; i++){
                            el.userTableColumn.push(data[i].columnField);
                        }

                        initTbDetails();
                        el.adjustTableColumnDialog.dialog('close');
                    });
                }
            },
            {
                text: '确定',
                iconCls: 'icon-ok',
                handler: function () {
                    topWin.frames['adjustTableColumn'].confirmSetUp(function (data) {
                        el.userTableColumn = [];
                        for(var i = 0; i < data.length; i++){
                            el.userTableColumn.push(data[i].columnField);
                        }

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

//下载
function downloadInvoiceFile(filePath,fileName) {
    if (fileName.indexOf(".pdf") != -1) {
        previewPDF(filePath,fileName);
    }else if (fileName.indexOf(".jpg") != -1 || fileName.indexOf(".png") != -1) {
        previewImgNew(filePath,fileName);
    }else {
        window.location.href = '/files/download?fileName=' + filePath + '&realName=' + encodeURI(fileName);
    }
}
function previewPDF(filePath, fileName) {
    localStorage.pdf_url = '/files/download?fileName=' + filePath + '&realName=' + encodeURI(fileName);
    openMainLayerWin("PDF文件预览", '/static/pdfjs1/web/viewer.html', "1000px;", "100%");
}
function previewImgNew(filePath, fileName) {
    layer.photos({
        photos: {
            "title": "图片预览",
            "start": 0,
            "data": [
                {
                    "alt": fileName,
                    "pid": 5,
                    "src": '/files/download?fileName=' + filePath + '&realName=' + encodeURI(fileName)
                }
            ]
        }
    });
}

/**
 * 获取当前用户表格列布局
 */
function findUserTableColumn() {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'fin/table/column/rest/user/setting?pageTable=2&isAuthority=1',
        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: 'itemNo',
        title: '对账单行号',
        width: 80,
        sortable: true
    },
    {
        field: 'receiveCode',
        title: '入库凭证',
        width: 90,
        sortable: true
    },
    {
        field: 'receiveRowNo',
        title: '行号',
        width: 60,
        sortable: true
    },
    {
        field: 'receiveDate',
        title: '入库日期',
        width: 110,
        sortable: true
    },
    {
        field: 'inOutFlag',
        title: '出入库标识',
        width: 85,
        sortable: true
    },
    {
        field: 'receiveNum',
        title: '入库数量',
        width: 70,
        sortable: true,
        formatter: function (value) {
            if (value < 0) {
                return '<span style="color: red;">' + value + '</span>';
            }else {
                return value;
            }
        }
    },
    {
        field: 'surplusNum',
        title: '可用数量',
        width: 70,
        sortable: true,
        formatter: function (value, row) {
            if (value < 0) {
                return '<span style="color: red;">' + value + '</span>';
            }else {
                if(row.sapMoveType === '161' || row.sapMoveType === '122'){
                    return '<span style="color: red;">' + (value * -1) + '</span>';
                }
                return value;
            }
        }
    },
    {
        field: 'asQuantity',
        title: '确认对账数量',
        width: 90,
        sortable: true,
        formatter: function (value) {
            if (value < 0) {
                return '<span style="color: red;">' + value + '</span>';
            }else {
                return value;
            }
        },
        styler: function (value, row) {
            if(Number(row.editFlag === 1)){
                return 'background-color:#E1E1E1;';
            }
            return '';
        },
        // editor: {
        //     type: 'numberbox',
        //     options: {
        //         precision: 3,
        //         onChange: function (nv, ov) {
        //             if(ov && nv !== ov){
        //                 updateRowData(nv, 'asQuantity');
        //             }
        //         }
        //     }
        // }
    },
    {
        field: 'notTaxPrice',
        title: '未税单价',
        width: 90,
        sortable: true
    },
    {
        field: 'taxPrice',
        title: '对账含税单价',
        width: 90,
        sortable: true,
        styler: function (value, row) {
            if(Number(row.editFlag === 1)){
                return 'background-color:#E1E1E1;';
            }
            return '';
        },
        // editor: {
        //     type: 'numberbox',
        //     options: {
        //         precision: 6,
        //         onChange: function (nv, ov) {
        //             if(ov && nv !== ov){
        //                 updateRowData(nv, 'taxPrice');
        //             }
        //         }
        //     }
        // }
    },
    // {
    //     field: 'asDiffPrice',
    //     title: '对账差异单价',
    //     width: 90,
    //     sortable: true
    // },
    {
        field: 'notTaxAmount',
        title: '对账未税金额',
        width: 100,
        sortable: true,
        formatter: function (value) {
            if (value < 0) {
                return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
            }else {
                return formatNumber(value, 2, 1);
            }
        },
        styler: function (value, row) {
            if(Number(row.editFlag === 1)){
                return 'background-color:#E1E1E1;';
            }
            return '';
        },
        // editor: {
        //     type: 'numberbox',
        //     options: {
        //         precision: 2,
        //         editable: false
        //     }
        // }
    },
    {
        field: 'taxCodeDesc',
        title: '对账税率',
        width: 160,
        sortable: true,
        styler: function (value, row) {
            if(Number(row.editFlag === 1)){
                return 'background-color:#E1E1E1;';
            }
            return '';
        },
        // editor: {
        //     type: 'combobox',
        //     options: {
        //         valueField: 'itemName',
        //         textField: 'itemRemark',
        //         data: el.taxDict,
        //         panelHeight: 200,
        //         panelWidth: 180,
        //         onChange: function (nv, ov) {
        //             if(ov && nv !== ov){
        //                 updateRowData(nv, 'taxCodeDesc');
        //             }
        //         }
        //     }
        // }
    },
    {
        field: 'taxAmount',
        title: '对账含税金额',
        width: 100,
        sortable: true,
        formatter: function (value) {
            if (value < 0) {
                return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
            }else {
                return formatNumber(value, 2, 1);
            }
        }
    },
    // {
    //     field: 'asDiffAmount',
    //     title: '对账差异含税金额',
    //     width: 130,
    //     sortable: true,
    //     formatter: function (value) {
    //         if (value < 0) {
    //             return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
    //         }else {
    //             return formatNumber(value, 2, 1);
    //         }
    //     }
    // },
    {
        field: 'diffTaxAmount',
        title: '对账税额',
        width: 90,
        sortable: true,
        formatter: function (value) {
            if (!value) {
                return '';
            }
            return formatNumber(value, 2, 1);
        },
        styler: function (value, row) {
            if(Number(row.editFlag === 1)){
                return 'background-color:#E1E1E1;';
            }
            return '';
        },
        // editor: {
        //     type: 'numberbox',
        //     options: {
        //         precision: 2,
        //         editable: false,
        //     }
        // }
    },
    {
        // 累计开票金额 = 申请开票金额 + 采购确认金额 + 财务过账金额
        field: 'invoicedAmount',
        title: '累计开票金额',
        width: 100,
        sortable: true,
        formatter: function (value) {
            if (!value) {
                return '0.00';
            }
            return formatNumber(value, 2, 1);
        }
    },
    {
        // 剩余可开票金额 = (入库数量-对账数量) * 订单含税单价
        field: 'surplusAmount',
        title: '剩余可开票金额',
        width: 100,
        sortable: true,
        formatter: function (value) {
            if (!value) {
                return '0.00';
            }
            return formatNumber(value, 2, 1);
        }
    },
    {
        field: 'zlsdh',
        title: 'SC订单号',
        width: 90,
        sortable: true
    },
    {
        field: 'poCode',
        title: 'SAP订单号',
        width: 90,
        sortable: true
    },
    {
        field: 'poItemNo',
        title: '订单行号',
        width: 70,
        sortable: true
    },
    {
        field: 'materialCode',
        title: '物料编码',
        width: 90,
        sortable: true
    },
    {
        field: 'materialName',
        title: '物料名称',
        width: 180,
        sortable: true
    },
    {
        field: 'specs',
        title: '规格',
        width: 120
    },
    {
        field: 'materialUnit',
        title: '单位',
        width: 60,
        sortable: true
    },
    // {
    //     field: 'seekPgCodeName',
    //     title: '询源采购组',
    //     width: 110,
    //     sortable: true
    // },
    {
        field: 'orderNotTaxPrice',
        title: '订单未税单价',
        width: 90,
        sortable: true
    },
    {
        field: 'orderTaxPrice',
        title: '订单含税单价',
        width: 90,
        sortable: true
    },
    {
        field: 'poTypeName',
        title: '订单类型名称',
        width: 100
    },
    {
        field: 'orderTaxCodeDesc',
        title: '订单税率',
        width: 160,
        sortable: true
    },
    // {
    //     field: 'asNtAmount',
    //     title: '订单未税金额',
    //     width: 100,
    //     sortable: true,
    //     formatter: function (value) {
    //         if (value < 0) {
    //             return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
    //         }else {
    //             return formatNumber(value, 2, 1);
    //         }
    //     }
    // },
    // {
    //     field: 'asItAmount',
    //     title: '订单含税金额',
    //     width: 100,
    //     sortable: true,
    //     formatter: function (value) {
    //         if (value < 0) {
    //             return '<span style="color: red;">' + formatNumber(value, 2, 1) + '</span>';
    //         }else {
    //             return formatNumber(value, 2, 1);
    //         }
    //     }
    // },
    {
        field: 'paymentTermCodeName',
        title: '付款条件',
        width: 200,
        sortable: true
    },
    // {
    //     field: 'paymentWayCodeDesc',
    //     title: '付款方式',
    //     width: 200,
    //     sortable: true
    // },
    // 承运商对账
    // {
    //     field: 'materialSupplierCode',
    //     title: '材料商编码',
    //     width: 90,
    //     sortable: true
    // },
    // {
    //     field: 'materialSupplierName',
    //     title: '材料商名称',
    //     width: 180,
    //     sortable: true
    // },
    // {
    //     field: 'freightType',
    //     title: '运费类型',
    //     width: 80,
    //     sortable: true
    // },
    // 集采订单信息
    // {
    //     field: 'jcPoCode',
    //     title: '集采SAP订单号',
    //     width: 110,
    //     sortable: true
    // },
    // {
    //     field: 'jcPoItemNo',
    //     title: '行号',
    //     width: 70,
    //     sortable: true
    // },
    // {
    //     field: 'jcFactoryCode',
    //     title: '集采工厂',
    //     width: 80,
    //     sortable: true
    // }
];