/**
 * 对账模块-对账单编辑页面JS
 *
 * Created by li.kui on 2020/8/3.
 */
'use strict';
var el = {
    dataPanel: '#dataPanel',
    dataDiv: '#dataDiv',
    id: '#id',
    fileId: '#fileId',
    asNo: '#accountStatementNo',
    orderType: '#orderType',
    isSupplier: '#isSupplier',
    supplierCode: '#supplierCode',
    companyCode: '#companyCode',
    factoryCode: '#factoryCode',
    currencyCode: '#currencyCode',
    deductionAmount: '#deductionAmount',
    rebateAmount: '#rebateAmount',
    inStockStartDate: '#inStockStartDate',
    inStockEndDate: '#inStockEndDate',
    notTaxAmount: '#notTaxAmount',
    taxAmount: '#taxAmount',
    remark: '#remark',
    dataTabs: '#dataTabs',
    tbDetails: '#tbDetails',
    tbDeduction: '#tbDeduction',
    tbRebate: '#tbRebate',
    taxCode: '#taxCode',
    taxCodeDesc: '#taxCodeDesc',
    paymentTermCode: '#paymentTermCode',
    poType: '#poType',
    purchaseGroup: '#purchaseGroup',
    paymentTermDesc: '#paymentTermDesc',
    invoiceFileInput: '#invoiceFileInput',
    localCurrency: '#localCurrency',
    originalCurrency: '#originalCurrency',
    advanceLocalCurrency: '#advanceLocalCurrency',
    advanceOriginalCurrency: '#advanceOriginalCurrency',
    choseRebateDataDialog: null,
    addDetailDialog: null,
    delDetail: [],
    delRebate: [],
    userTableColumn: [],
    bodyHeight: document.documentElement.clientHeight
};


/**
 * 文档就绪
 */
$(function () {
    // 获取当前用户在本页面中表格列配置
    findUserTableColumn();

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

    // initFileDetail();
    initTbDetails();

    // 税率
    $(el.taxCode).combobox({
        panelHeight: 'auto',
        limitToList: 'true',
        panelWidth: 200,
        valueField: 'dicCode',
        textField: 'newItemCodeAndName',
        prompt: '--- 请选择 ---',
        url: '/dic/getDicByType?type=tax'
    });
    // 付款条件
    // $(el.paymentTermCode).combobox({
    //     panelHeight: 'auto',
    //     // panelWidth: 200,
    //     valueField: 'dicCode',
    //     textField: 'dicTxt',
    //     prompt: '--- 请选择 ---',
    //     url: '/dic/getDicByType?type=supplier_fktj'
    // });
    $(el.paymentTermCode).combobox({
        panelHeight: 'auto',
        limitToList: 'true',
        // panelWidth: 200,
        valueField: 'dicCode',
        textField: 'dicTxt',
        prompt: '--- 请选择 ---',
        url: '/fin/common/rest/getSupplierProductTypeBySupplierCode?supplierCode='+ $(el.supplierCode).textbox('getValue')
    });
    //采购组
    $(el.purchaseGroup).combobox({
        editable: true,
        required: false,
        limitToList: 'true',
        valueField: 'purchaseGroupCode',
        textField: 'purchaseGroupName',
        panelHeight: '150',
        url: '/purchase/group/rest/list/all',
        // onChange: function (data) {
        //     $(el.tbDetails).datagrid('loadData', { total: 0, rows: [] });
        //     var rows = $(el.tbDetails).datagrid('getSelections');
        //     calculationAmount(rows);
        // }
    });
    // 订单类型
    $(el.poType).combobox({
        panelHeight: 'auto',
        panelWidth: 200,
        valueField: 'dicCode',
        textField: 'dicTxt',
        multiple: true,
        prompt: '--- 请选择 ---',
        url: '/dic/getDicByType?type=po_type',
        // onChange: function (data) {
        //     $(el.tbDetails).datagrid('loadData', { total: 0, rows: [] });
        //     var rows = $(el.tbDetails).datagrid('getSelections');
        //     calculationAmount(rows);
        // }
    });

    getExchangeRate($(el.currencyCode).textbox('getValue'));
    // initTbRebate();

    // initTbDeduction();
});
function initFileDetail(){
    $.ajax({
        url: '/fin/account/statement/rest/find/statement/file/list?id='+$(el.id).val(), //单文件上传
        type: 'GET',
        success: function (result) {
            console.log(result)
            if (result.length>0){
                console.log(result)
                $("#invoiceFileInput").filebox('setText',result[0].fileName);
            }
            $(el.id).val(result);
        },
        error: function (xhr, status, error) {
            $("#invoiceFileInput").filebox('setText','');
            layer.alert('文件上传失败', {icon: 2, title: '温馨提示'})
        }
    });
}
// $("#_easyui_textbox_input14").click(function () {
//     console.log(1)
// });
function uploadFile() {
    var filebox = $("#invoiceFileInput").filebox("files");
    if (filebox.length == 1) {
        var formData = new FormData();
        formData.append("file", filebox[0]);
        var index = layer.load(1, {
            shade: [0.1, '#eee'] //0.1透明度的白色背景
        });
        var index_wait;
        $.ajax({
            url: '/files/invoiceUploadFile', //单文件上传
            type: 'POST',
            processData: false,
            contentType: false,
            data: formData,
            beforeSend: function(){
                index_wait = layer.load(0, {  //发送请求前调用load方法
                    shade: [0.5, '#fff'],  //0.5透明度的白色背景
                });
            },
            complete: function () {
                layer.close(index_wait);
            },
            success: function (result) {
                // $('#fileDisplay').children('a').remove()
                $("#invoiceFileInput").filebox('setText','');
                // $(el.fileId).val(result);

                let fjId = [], fileMessages = '';
                if($(el.fileId).val()){
                    fjId = $(el.fileId).val().split(',')
                }
                fjId.push(result);
                $(el.fileId).val(fjId.join(','));
                // $('#fileDisplay').append('<a style="margin-left: 10px;color: black">'+getFileName($("#invoiceFileInput").filebox('getValue'))+'</a>')
                $('#fileDisplay').append('<span class="fileSpan">\n' +
                    '                            <a  href="javascript:" style="margin-left: 10px;color: black">' + getFileName($("#invoiceFileInput").filebox('getValue'))+
                    '                            </a>\n' +
                    '                            <a id="'+result+'" class="deleteFile" onclick="deleteFile1()">\n' +
                    '                                <img src="/static/img/89-Minus.png" style="width: 20px;height: 20px;">\n' +
                    '                            </a> &nbsp;&nbsp;\n' +
                    '                            </span>')
                layer.msg('上传成功', {icon: 1, title: '温馨提示'});
            },
            error: function (xhr, status, error) {
                $("#invoiceFileInput").filebox('setText','');
                layer.alert('文件上传失败', {icon: 2, title: '温馨提示'})
            }
        });
    }
}

function deleteFile1() {
    $('#fileDisplay').on('click','.deleteFile',function () {
        let $this = $(this);
        let fileId = $this.attr('id');
        var fjId = [];
        if ($(el.fileId).val()) {
            fjId = $(el.fileId).val().split(',')
        }
        fjId.remove(fileId + "");

        $(el.fileId).val(fjId.join(','));

        $this.closest('span').remove();
        layer.msg('删除成功');
    });
}
function getFileName(o){
    var pos=o.lastIndexOf("\\");
    return o.substring(pos+1);
}

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) {
    lookPicture('/files/download?fileName=' + filePath + '&realName=' + encodeURI(fileName));
}
/**
 * 初始化入库明细表格
 */
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 + 'pc/finance/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-ok',
                handler: function () {
                    payableOutstanding();
                }
            }
        ]
    });
}
function payableOutstanding() {

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

    if(companyCode==''||supplierCode==''||currencyCode==''){
        topWin.layer.alert('请检查“公司”、“供应商”、“本币”是否已选', {icon: 0});
        return false;
    }
    $.ajax({
        type: 'POST',
        url: g.ctx + 'fin/account/statement/rest/payableOutstanding',
        async: false,
        data: {
            companyCode: companyCode,
            supplierCode: supplierCode,
            inStockEndDate: inStockEndDate,
            currency:currencyCode
        },
        success: function (data) {

            $(el.localCurrency).textbox('setValue',data.apDmbtr);
            $(el.originalCurrency).textbox('setValue',data.apWrbtr);
            $(el.advanceLocalCurrency).textbox('setValue',data.ppDmbtr);
            $(el.advanceOriginalCurrency).textbox('setValue',data.ppWrbtr);


        }
    });


}
/**
 * 初始化扣款信息表格
 */
function initTbDeduction() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;

    $(el.tbDeduction).datagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'fin/account/statement/rest/find/statement/deduction/list',
        singleSelect: false,
        showFooter: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        queryParams: {
            asId: $(el.id).val()
        },
        frozenColumns: [
            [
                {
                    field: 'deductionId',
                    title: '附件查看',
                    width: 80,
                    formatter: function (value) {
                        if(value){
                            return '<a href="javascript:void(0)" onclick="lookDrAttachment(this)" data-type="1" data-id="' + value + '">查看</a>';
                        }
                        return '';
                    }
                },
                {
                    field: 'deductionNo',
                    title: '扣款编号',
                    width: 140,
                    sortable: true
                },
                {
                    field: 'deductionTypeDesc',
                    title: '扣款类型',
                    width: 90,
                    sortable: true
                },
                {
                    field: 'deductionAmount',
                    title: '含税扣款金额(元)',
                    width: 110,
                    sortable: true,
                    formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return formatNumber(value, 2, 1);
                    }
                },
                {
                    field: 'taxCodeDesc',
                    title: '税率',
                    width: 160,
                    sortable: true
                },
                {
                    field: 'deductionTime',
                    title: '扣款时间',
                    width: 90,
                    sortable: true,
                    formatter: function (value) {
                        if (value) {
                            return moment(value).format("YYYY-MM-DD");
                        }
                        return '';
                    }
                }
            ]
        ],
        columns: [
            [
                {
                    field: 'deductionReason',
                    title: '扣款原因',
                    width: 300
                },
                {
                    field: 'companyCode',
                    title: '公司代码',
                    width: 80
                },
                {
                    field: 'companyName',
                    title: '公司名称',
                    width: 180
                },
                {
                    field: 'supplierCode',
                    title: '供应商编码',
                    width: 90
                },
                {
                    field: 'supplierName',
                    title: '供应商名称',
                    width: 270
                },
                {
                    field: 'associatedNo',
                    title: 'SRM业务单据',
                    width: 140,
                    formatter: function (value, row) {
                        if(!row.associatedRowNo){
                            return value;
                        }else {
                            return value + '|' + row.associatedRowNo;
                        }
                    }
                },
                {
                    field: 'associatedOaNo',
                    title: 'OA流程单号',
                    width: 120,
                    sortable: true
                },
                {
                    field: 'createTime',
                    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'),
        purchaseGroup = $('#purchaseGroup').val(), taxCode = $(el.taxCode).combobox('getValue'),
        poType = getTextByJs($(el.poType).combobox('getValues')),
        inStockEndDate = $(el.inStockEndDate).datebox('getValue'), asNo = $(el.asNo).textbox('getValue'), orderType = $(el.orderType).val();
    if(!poType){
        topWin.layer.alert('请选择订单类型', {icon: 0});
        return false;
    }
    var rows = $(el.tbDetails).datagrid('getRows'), alreadyExistId = [];
    for(var i = 0; i < rows.length; i++){
        alreadyExistId.push(rows[i].receiveId);
    }

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

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

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


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

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

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

    // 校验选中的行是否可以删除
    var loading = topWin.layer.msg('校验选中的行是否可以删除, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        type: 'POST',
        url: g.ctx + '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 addRebateData() {
    var companyCode = $(el.companyCode).val(), supplierCode = $(el.supplierCode).val(), 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 delRebateData() {
    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'));
}


/**
 * 数据保存 type 0:暂存 1：提交
 */
function dataSave(type,callback) {
    var id = $(el.id).val(), remark = $(el.remark).textbox('getValue'), taxAmount = $(el.taxAmount).textbox('getValue'),purchaseGroup = $('#purchaseGroup').combobox('getValue'),
        notTaxAmount = $(el.notTaxAmount).val(), rebateAmount = '',localCurrency = $(el.localCurrency).textbox('getValue'),
        originalCurrency = $(el.originalCurrency).textbox('getValue'),
        advanceLocalCurrency = $(el.advanceLocalCurrency).textbox('getValue'), fileId = $(el.fileId).val(),
        advanceOriginalCurrency = $(el.advanceOriginalCurrency).textbox('getValue');
    localCurrency = Number(localCurrency.replace(/,/g,'')),
        originalCurrency = Number(originalCurrency.replace(/,/g,'')),
        advanceLocalCurrency = Number(advanceLocalCurrency.replace(/,/g,'')),
        advanceOriginalCurrency = Number(advanceOriginalCurrency.replace(/,/g,''));

    var headData = {};
    headData.id = id;
    headData.taxAmount = Number(taxAmount.replace(/,/g,''));
    headData.notTaxAmount = Number(notTaxAmount.replace(/,/g,''));
    headData.rebateAmount = rebateAmount;
    headData.purchaseGroup = purchaseGroup;
    headData.remark = remark;
    headData.paymentTermCode = $(el.paymentTermCode).combobox('getValue');
    headData.poType = getTextByJs($(el.poType).combobox('getValues'));

    headData.localCurrency = localCurrency;
    headData.originalCurrency = originalCurrency;
    headData.advanceLocalCurrency = advanceLocalCurrency;
    headData.advanceOriginalCurrency = advanceOriginalCurrency;
    headData.fileId = fileId;

    // 入库明细
    var detail = $(el.tbDetails).datagrid('getRows'), statementItem = [], dsiId = [];
    if (detail.length === 0) {
        topWin.layer.alert('请选择入库凭证明细', {icon: 0});
        return false;
    }
    if (!remark) {
        topWin.layer.alert('请填写备注', {icon: 0});
        return false;
    }

    var itSumAmount = new BigNumber(0);
    let taxCode = "",payTermCode = "";
    for(var i = 0; i < detail.length; i++){
        if(i !== 0 && taxCode !== detail[i].taxCode){
            layer.msg("所选税率必须一致");
            return false;
        }
        if(i !== 0 && payTermCode !== detail[i].paymentTermCode){
            layer.msg("所选付款条件必须一致");
            return false;
        }
        taxCode = detail[i].taxCode;
        payTermCode = detail[i].paymentTermCode;
        if(0 === detail[i].id){
            statementItem.push(detail[i]);
        }

        itSumAmount = itSumAmount.plus(detail[i].taxAmount);
    }
    for(var n = 0; n < el.delDetail.length; n++){
        dsiId.push(el.delDetail[n].id);
    }

    // 返利数据
    var rebate = '', rebateIds = [], drId = [];
    // for(var j = 0; j < el.delRebate.length; j++){
    //     drId.push(el.delRebate[j].rebateId);
    // }
    // for(var k = 0; k < rebate.length; k++){
    //     if(!rebate[k].id){
    //         rebateIds.push(rebate[k].rebateId);
    //     }
    // }
    // 需要校验凭证汇总含税金额 - (扣款金额 + 返利金额) > 0
    // var diff = itSumAmount.plus(deductionAmount).plus(rebateAmount);
    // if(diff.lt(0)){
    //     topWin.layer.alert('选择入库凭证明细的含税金额汇总小于选择的扣款和返利的合计', {icon: 0});
    //     return false;
    // }
    let title;
    if(type === 0){
        title = "您确定要保存对账单?";
    }else{
        title ="您确定要保存对账单,并提交财务确认?"
    }
    topWin.layer.confirm(title, {icon: 3}, function (index) {
        topWin.layer.close(index);

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


/**
 * 计算页面相关金额
 */
function calculationAmount(rows) {
    var taxAmount = new BigNumber(0), notTaxAmount = new BigNumber(0), invoicedAmount = new BigNumber(0),
        surplusAmount = new BigNumber(0), storageQuantity = new BigNumber(0), statementQuantity = new BigNumber(0);
    for (var j = 0; j < rows.length; j++) {
        var item = rows[j];
        taxAmount = taxAmount.plus(item.taxAmount);
        notTaxAmount = notTaxAmount.plus(item.notTaxAmount);
        invoicedAmount = invoicedAmount.plus(item.invoicedAmount);
        surplusAmount = surplusAmount.plus(item.surplusAmount);
        storageQuantity = storageQuantity.plus(item.receiveNum);
        statementQuantity = statementQuantity.plus(item.asQuantity);
    }

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

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


/**
 * 计算返利金额
 *
 * @param data 返利表格数据
 */
// function calculationRebateAmount(data) {
//     var rebateAmount = 0;
//     for(var j = 0; j < data.length; j++){
//         var item = data[j];
//         // 1:购方对供方返利 2:供方对购方返利
//         if(Number(item.rebateType) === 1){
//             rebateAmount = Number(rebateAmount) + Number(item.rebateAmount);
//         }else {
//             rebateAmount = Number(rebateAmount) + Number(item.rebateAmount) * -1;
//         }
//     }
//
//     $(el.rebateAmount).numberbox('setValue', rebateAmount);
//
//     // 更新页脚行的值并刷新
//     var footers = $(el.tbRebate).datagrid('getFooterRows');
//     footers[0]['rebateAmount'] = formatNumber(rebateAmount, 2, 1);
//     $(el.tbRebate).datagrid('reloadFooter');
// }


/**
 * 入库明细导出
 */
function detailExport() {
    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 findUserTableColumn() {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'fin/table/column/rest/user/setting?pageTable=2&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: 'itemNo',
//         title: '对账单行号',
//         width: 80,
//         sortable: true
//     },
//     {
//         field: 'receiveCode',
//         title: '入库凭证',
//         width: 90,
//         sortable: true
//     },
//     {
//         field: 'receiveRowNo',
//         title: '行号',
//         width: 60,
//         sortable: true
//     },
//     {
//         field: 'receiveDate',
//         title: '入库日期',
//         width: 100,
//         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: 'asQuantity',
//         title: '对账数量',
//         width: 70,
//         sortable: true,
//         formatter: function (value) {
//             if (value < 0) {
//                 return '<span style="color: red;">' + value + '</span>';
//             }else {
//                 return value;
//             }
//         }
//     },
//     {
//         field: 'notTaxPrice',
//         title: '未税单价',
//         width: 70,
//         sortable: true
//     },
//     {
//         field: 'taxPrice',
//         title: '含税单价',
//         width: 70,
//         sortable: true
//     },
//     {
//         field: 'taxCodeDesc',
//         title: '税率',
//         width: 160,
//         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);
//             }
//         }
//     },
//     {
//         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: 'diffTaxAmount',
//         title: '税额',
//         width: 100,
//         sortable: true,
//         formatter: function (value) {
//             return formatNumber(value, 2, 1);
//         }
//     },
//     // {
//     //     // 累计开票金额 = 申请开票金额 + 采购确认金额 + 财务过账金额
//     //     field: 'invoicedAmount',
//     //     title: '累计开票金额',
//     //     width: 110,
//     //     sortable: true,
//     //     formatter: function (value) {
//     //         if(!value){
//     //             return '0.00';
//     //         }
//     //         return formatNumber(value, 2, 1);
//     //     }
//     // },
//     // {
//     //     // 剩余可开票金额 = (入库数量-对账数量) * 订单含税单价
//     //     field: 'surplusAmount',
//     //     title: '剩余可开票金额',
//     //     width: 120,
//     //     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: 'paymentTermCodeName',
//         title: '付款条件',
//         width: 200,
//         sortable: true
//     },
//     {
//         field: 'contractNo',
//         title: '合同号',
//         width: 120
//     }
// ];

var tableColumns = [
    {
        field: 'deleteFlag',
        title: '删除标记',
        width: 80,
        formatter: function (value) {
            if (value ===1) {
                return '<span style="color: red;">已删除</span>';
            }else {
                return "未删除";
            }
        }
    },
    {
        field: 'zlsdh',
        title: 'SC订单号',
        width: 90,
        sortable: true
    },
    {
        field: 'poCode',
        title: 'SAP订单号',
        width: 90,
        sortable: true
    },
    {
        field: 'receiveRowNo',
        title: '行号',
        width: 60,
        sortable: true
    },
    {
        field: 'receiveDate',
        title: '入库日期',
        width: 110,
        sortable: true
    },
    {
        field: 'materialCode',
        title: '物料编码',
        width: 90,
        sortable: true
    },
    {
        field: 'materialName',
        title: '物料名称',
        width: 180,
        sortable: true
    },
    {
        field: 'specs',
        title: '规格',
        width: 120
    },

    {
        field: 'receiveNum',
        title: '入库数量',
        width: 70,
        sortable: true,
        formatter: function (value) {
            if (value < 0) {
                return '<span style="color: red;">' + value + '</span>';
            }else {
                return value;
            }
        }
    },
    {
        field: 'materialUnit',
        title: '单位',
        width: 70,
        sortable: true
    },
    {
        field: 'orderTaxPrice',
        title: '订单含税单价',
        width: 90,
        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: 'asDiffPrice',
    //     title: '对账差异单价',
    //     width: 90,
    //     sortable: true
    // },
    // {
    //     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: 'invoicedAmount',
    //     title: '累计开票金额',
    //     width: 110,
    //     sortable: true,
    //     formatter: function (value) {
    //         if (!value) {
    //             return '0.00';
    //         }
    //         return formatNumber(value, 2, 1);
    //     }
    // },
    // {
    //     // 剩余可开票金额 = (入库数量-对账数量) * 订单含税单价
    //     field: 'surplusAmount',
    //     title: '剩余可开票金额',
    //     width: 120,
    //     sortable: true,
    //     formatter: function (value) {
    //         if (!value) {
    //             return '0.00';
    //         }
    //         return formatNumber(value, 2, 1);
    //     }
    // },

    {
        field: 'poItemNo',
        title: '订单行号',
        width: 70,
        sortable: true
    },

    // {
    //     field: 'seekPgCodeName',
    //     title: '询源采购组',
    //     width: 110,
    //     sortable: true
    // },





    {
        field: 'paymentTermCodeName',
        title: '付款条件',
        width: 200,
        sortable: true
    },
    // {
    //     field: 'contractNo',
    //     title: '合同号',
    //     width: 120
    // },
    {
        field: 'inOutFlag',
        title: '出入库标识',
        width: 85,
        sortable: true
    },
    {
        field: 'receiveCode',
        title: '入库凭证',
        width: 90,
        sortable: true
    },
    {
        field: 'itemNo',
        title: '对账单行号',
        width: 80,
        sortable: true
    },
    {
        field: 'asQuantity',
        title: '本次对账数量',
        width: 100,
        sortable: true,
        formatter: function (value) {
            if (value < 0) {
                return '<span style="color: red;">' + value + '</span>';
            }else {
                return value;
            }
        }
    },
    {
        field: 'notTaxPrice',
        title: '未税单价',
        width: 70,
        sortable: true
    },
    {
        field: 'orderNotTaxPrice',
        title: '订单未税单价',
        width: 90,
        sortable: true
    },
    {
        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: 'diffTaxAmount',
        title: '对账税额',
        width: 90,
        sortable: true,
        formatter: function (value) {
            if (!value) {
                return '';
            }
            return formatNumber(value, 2, 1);
        }
    },
    {
        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);
            }
        }
    },
    {
        field: 'taxPrice',
        title: '对账含税单价',
        width: 90,
        sortable: true
    },
    {
        field: 'poTypeName',
        title: '订单类型名称',
        width: 100
    },
    {
        field: 'orderTaxCodeDesc',
        title: '订单税率',
        width: 160,
        sortable: true
    },
    {
        field: 'taxCodeDesc',
        title: '税率',
        width: 160,
        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
    // }
];
