/**
 * 开票申请，公共页签
 * Created by heqiaohui on 2021/4/30.
 */
'use strict';

/**
 * 文档就绪
 */
$(function () {
    // $(el.dataPanel).panel({
    //     collapsible: true,
    //     onCollapse: function () {
    //         $(el.tbInvoicePaymentCertificate).edatagrid('resize', {height: el.bodyHeight - 80});
    //     },
    //     onExpand: function () {
    //         var dataDiv = $(el.dataDiv).outerHeight() + 90;
    //         $(el.tbInvoicePaymentCertificate).datagrid('resize', {height: el.bodyHeight - dataDiv});
    //     }
    // });
    findTaxDictData1();
    initTbInvoicePaymentCertificate();

});
var editor2 = undefined;
var taxDict1 = [];


function findTaxDictData1() {
    $.ajax({
        type: 'POST',
        url: g.ctx + 'pc/sys/tax/rest/listAll',
        async: false,
        success: function (data) {
            for(var i = 0; i < data.length; i++){
                var obj = {};
                obj.id = data[i].id;
                obj.itemCode = data[i].taxCode;
                obj.itemName = data[i].taxName;
                obj.itemValue = data[i].taxValue;
                obj.itemRemark = data[i].taxName;
                taxDict1.push(obj);
            }
        }
    });
}

/**
 * 初始化关联发票表格
 */
function initTbInvoicePaymentCertificate() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;
    var toolbars = [];
    var columns;
    if (invoiceLookFlag===0){
        toolbars = [
            {
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    addInvoicePaymentCertificateItem();
                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    delInvoicePaymentCertificateItem();
                }
            },
            '-',
            {
                text: '导入',
                iconCls: 'icon-import',
                handler: function () {
                    importPaymentCertificateInvoice();
                }
            },
            // '-',
            // {
            //     text: '计算未税和税额',
            //     iconCls: 'icon-coins',
            //     handler: function () {
            //         addOrDelPaymentCertificateInvoice();
            //     }
            // }
        ];
        columns = [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'file',
                    title: '缴款书附件',
                    width: 400,
                    formatter: function (value, row, index) {
                        if (!row.fileId){
                            // return '<a style="color: grey" >点我上传</a>';
                            return '';
                        }
                        return '<div class="invoice-file-form custom-file-form-style" data-options=\'{"deleteEnable":false, "previewEnable":true, "uploadEnable": false, "moreFileUploadEnable": true, "fileSize": 50, "fileTypes": ".xls,.doc,.txt,.pdf"}\' data-fileIds = "'+row.fileId+'"></div>';
                        // return "<a style=\"color: #108ee9\" href='" + g.ctx + "pc/sys/file/rest/download/" + row.fileId + "'>" + row.fileName + "</a>";
                        // return '<a style="color: #108ee9" onclick="replyDownload(' + row.fileId + ')">'+row.fileName+'</a>';
                    },
                    editor: {
                        type: 'filebox', options: {
                            editable: false,
                            buttonText: '选择文件',
                            onChange(e){
                                var  tath = $(this);
                                var fileName = $(this).filebox('getValue');
                                if (!fileName){
                                    return false;
                                }
                                if(fileName.indexOf("+")>0){
                                    layer.alert( '文件名或路径不能带"+"号');
                                    $(this).filebox('setText','');
                                    return;
                                }
                                var files = $(this).next().find('input[type=file]')[0].files;
                                var formData = new FormData();
                                formData.append('file', files[0]);//默认的文件数据名为“Filedata”
                                var index_wait;
                                $.ajax({
                                    url: g.ctx + 'pc/sys/kingdeeInvoiceCloudAssistant/rest/recognitionCheck', //单文件上传
                                    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) {

                                        result.fileName = getFileName(fileName);
                                        $(el.tbInvoicePaymentCertificate).edatagrid("endEdit", editor2);
                                        delete result.currencyCode;
                                        delete result.taxRate;
                                        let row = {
                                            index: editor2,
                                            row: result
                                        };
                                        $(el.tbInvoicePaymentCertificate).edatagrid('updateRow', row);
                                        // addOrDelInvoice();
                                        initFileForm('invoice-file-form');
                                        // $(el.tbInvoicePaymentCertificate).datagrid("beginEdit", editor2);
                                        if (result.validateMessage && result.validateMessage !== "合规性校验通过") {
                                            layer.alert(result.validateMessage, {title: '温馨提示'});
                                        } else {
                                            layer.msg('上传成功', {icon: 1, title: '温馨提示'});
                                        }
                                    },
                                    error: function (error) {
                                        tath.filebox('clear');
                                        topWin.layer.alert(error.responseJSON.message, {
                                            icon: 2,
                                            content: error.responseJSON.message
                                        });
                                    }
                                });
                            }
                        }
                    }
                },
                {
                    field: 'deductionCodeType',
                    title: '可抵扣编号',
                    width: 100,
                    formatter: function (value) {
                        if (Number(value) === 1) {
                            return '可抵扣';
                        }
                        if (Number(value) === 2) {
                            return '不可抵扣';
                        }
                    },
                    editor: {
                        type: 'combobox', options: {
                            prompt: "请选择",
                            valueField: 'value',
                            editable: false,
                            panelHeight: 'auto',
                            textField: 'label',
                            data: [{
                                label: '可抵扣', value: 1
                            }, {
                                label: '不可抵扣', value: 2
                            }]
                        }
                    },
                },
                {
                    field: 'invoiceDate',
                    title: '缴款书日期',
                    width: 180,
                    formatter: function (value) {
                        if (value){
                            return moment(value).format("YYYY-MM-DD");
                        }
                        return '';
                    },
                    editor: {
                        type: 'datebox',
                        options: {
                            editable: false,
                            parser: function (value) {
                                if (value) {
                                    return new Date(value);
                                } else {
                                    return new Date();
                                }
                            }
                        }
                    }
                },
                {
                    field: 'invoiceCode',
                    title: '缴款书代码',
                    width: 150,
                    editor: {
                        type: 'textbox'
                    }
                },
                {
                    field: 'invoiceNumber',
                    title: '缴款书号码',
                    width: 150,
                    editor: {
                        type: 'textbox'
                    }
                },
                // {
                //     field: 'dutyParagraph',
                //     title: '税号',
                //     width: 150,
                //     editor: {
                //         type: 'textbox'
                //     }
                // },
                {
                    field: 'electronInvoiceNumber',
                    title: '数电缴款书号码',
                    width: 150,
                    editor: {
                        type: 'textbox'
                    }
                },
                {
                    field: 'taxRate',
                    title: '税率',
                    width: 170,
                    formatter: function (value) {
                        if (value){
                            for(var j = 0; j < taxDict1.length; j++){
                                if(taxDict1[j].itemCode === value){
                                    return taxDict1[j].itemRemark;
                                }
                            }
                        }
                        return '';
                    },
                    editor: {
                        type: 'combobox',
                        options: {
                            valueField: 'itemCode',
                            textField: 'itemRemark',
                            data: taxDict1,
                            panelHeight: 200,
                            // onChange: function (nv, ov) {
                            //     if(ov && nv !== ov){
                            //         updateRowData(nv, 'taxRate');
                            //     }
                            // }
                        }
                    }
                },
                {
                    field: 'currencyCode',
                    title: '币种',
                    width: 120,
                    editor: {
                        type: 'combobox',
                        options: {
                            url: g.ctx + 'pc/sys/dict/getDicByType?type=currency',
                            valueField: 'code',
                            textField: 'codeWithDesc',
                            limitToList: 'true',
                            prompt: '-- 请选择 --',
                            method: 'GET',
                            editable: false,
                            panelHeight: 150
                        }
                    }
                },
                {
                    field: 'taxAmount',
                    title: '含税金额',
                    width: 130,
                    formatter: function (value) {
                        return formatterCustomPrice(value,2,true,false);
                    },
                    // formatter: function (value) {
                    //     if (!value) {
                    //         return '';
                    //     }
                    //     return formatterPrice(value);
                    // },
                    editor: {
                        type: 'numberbox',
                        options: {
                            // min: 0,
                            precision: 2,
                            // onChange: function (nv, ov) {
                            //     if(ov){
                            //         updateRowData(nv, 'taxAmount');
                            //     }
                            // }
                        }
                    }
                },
                {
                    field: 'noTaxAmount',
                    title: '未税金额',
                    width: 130,
                    formatter: function (value) {
                        return formatterCustomPrice(value,2,true,false);
                    },
                    // formatter: function (value) {
                    //     if (!value) {
                    //         return '';
                    //     }
                    //     return formatterPrice(value);
                    // },
                    editor: {
                        type: 'numberbox',
                        options: {
                            // min: 0,
                            precision: 2
                        }
                    }
                },
                {
                    field: 'diffTaxMoney',
                    title: '税额',
                    width: 130,
                    formatter: function (value) {
                        return formatterCustomPrice(value,2,true,false);
                    },
                    editor: {
                        type: 'numberbox',
                        options: {
                            // min: 0,
                            precision: 2
                        }
                    }
                },

            ]
        ];
    }else if (invoiceLookFlag===2){
        toolbars=[
            {
                text: '导出',
                iconCls: 'icon-download',
                handler: function () {
                    // 刷新表体统计行金额
                    refreshInvoicePaymentCertificateFooter($(el.tbInvoicePaymentCertificate).edatagrid('getRows'));
                    invoicePaymentCertificateExport();
                }
            },

        ]
        columns = [
            [
                {
                    field: 'file',
                    title: '缴款书附件',
                    width: 400,
                    formatter: function (value, row, index) {
                        if (!row.fileId){
                            // return '<a style="color: grey" >点我上传</a>';
                            return '';
                        }
                        return '<div class="invoice-file-form custom-file-form-style" data-options=\'{"deleteEnable":false, "previewEnable":true, "uploadEnable": false, "moreFileUploadEnable": true, "fileSize": 50, "fileTypes": ".xls,.doc,.txt,.pdf"}\' data-fileIds = "'+row.fileId+'"></div>';
                        // return "<a style=\"color: #108ee9\" href='" + g.ctx + "pc/sys/file/rest/download/" + row.fileId + "'>" + row.fileName + "</a>";
                    },
                    editor: {
                        type: 'filebox', options: {
                            editable: false,
                            buttonText: '选择文件',
                            onChange(e){
                                var  tath = $(this);
                                var fileName = $(this).filebox('getValue');
                                if (!fileName){
                                    return false;
                                }
                                if(fileName.indexOf("+")>0){
                                    layer.alert( '文件名或路径不能带"+"号');
                                    $(this).filebox('setText','');
                                    return;
                                }
                                var files = $(this).next().find('input[type=file]')[0].files;
                                var formData = new FormData();
                                formData.append('file', files[0]);//默认的文件数据名为“Filedata”
                                var index_wait;
                                $.ajax({
                                    url: g.ctx + 'pc/sys/kingdeeInvoiceCloudAssistant/rest/recognitionCheck', //单文件上传
                                    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) {
                                        result.fileName = getFileName(fileName);
                                        $(el.tbInvoicePaymentCertificate).edatagrid("endEdit", editor2);
                                        delete result.taxRate;
                                        let row = {
                                            index: editor2,
                                            row: result
                                        };
                                        $(el.tbInvoicePaymentCertificate).edatagrid('updateRow', row);
                                        initFileForm('invoice-file-form');
                                        // $(el.tbInvoicePaymentCertificate).datagrid("beginEdit", editor2);
                                        if (result.validateMessage && result.validateMessage !== "合规性校验通过") {
                                            layer.alert(result.validateMessage, {title: '温馨提示'});
                                        } else {
                                            layer.msg('上传成功', {icon: 1, title: '温馨提示'});
                                        }
                                    },
                                    error: function (error) {
                                        tath.filebox('clear');
                                        topWin.layer.alert(error.responseJSON.message, {
                                            icon: 2,
                                            content: error.responseJSON.message
                                        });
                                    }
                                });
                            }
                        }
                    }
                },
                {
                    field: 'deductionCodeType',
                    title: '可抵扣编号',
                    width: 100,
                    formatter: function (value) {
                        if (Number(value) === 1) {
                            return '可抵扣';
                        }
                        if (Number(value) === 2) {
                            return '不可抵扣';
                        }
                    },
                    editor: {
                        type: 'combobox', options: {
                            prompt: "请选择",
                            valueField: 'value',
                            editable: false,
                            panelHeight: 'auto',
                            textField: 'label',
                            data: [{
                                label: '可抵扣', value: 1
                            }, {
                                label: '不可抵扣', value: 2
                            }]
                        }
                    },
                },
                {
                    field: 'invoiceDate',
                    title: '缴款书日期',
                    width: 180,
                    formatter: function (value) {
                        if (value){
                            return moment(value).format("YYYY-MM-DD");
                        }
                        return '';
                    },
                    editor: {
                        type: 'datebox',
                        options: {
                            editable: false,
                            parser: function (value) {
                                if (value) {
                                    return new Date(value);
                                } else {
                                    return new Date();
                                }
                            }
                        }
                    }
                },
                {
                    field: 'invoiceCode',
                    title: '缴款书代码',
                    width: 150,
                    editor: {
                        type: 'textbox'
                    }
                },
                {
                    field: 'invoiceNumber',
                    title: '缴款书号码',
                    width: 150,
                    editor: {
                        type: 'textbox'
                    }
                },
                // {
                //     field: 'dutyParagraph',
                //     title: '税号',
                //     width: 150,
                //     editor: {
                //         type: 'textbox'
                //     }
                // },
                {
                    field: 'electronInvoiceNumber',
                    title: '数电缴款书号码',
                    width: 150,
                    editor: {
                        type: 'textbox'
                    }
                },
                {
                    field: 'taxRate',
                    title: '税率',
                    width: 170,
                    formatter: function (value) {
                        if (value){
                            for(var j = 0; j < taxDict1.length; j++){
                                if(taxDict1[j].itemCode === value){
                                    return taxDict1[j].itemRemark;
                                }
                            }
                        }
                        return '';
                    }
                },
                {
                    field: 'currencyCode',
                    title: '币种',
                    width: 120
                },
                {
                    field: 'taxAmount',
                    title: '含税金额',
                    width: 130,
                    formatter: function (value) {
                        return formatterCustomPrice(value,2,true,false);
                    },
                },
                {
                    field: 'noTaxAmount',
                    title: '未税金额',
                    width: 130,
                    formatter: function (value) {
                        return formatterCustomPrice(value,2,true,false);
                    },
                },
                {
                    field: 'diffTaxMoney',
                    title: '税额',
                    width: 130,
                    formatter: function (value) {
                        return formatterCustomPrice(value,2,true,false);
                    },
                },

            ]
        ];
    }else {
        columns =  [
            [
                // {
                //     field: 'ck',
                //     checkbox: true
                // },
                {
                    field: 'file',
                    title: '缴款书附件',
                    width: 400,
                    formatter: function (value, row, index) {
                        if (!row.fileId){
                            // return '<a style="color: grey" >点我上传</a>';
                            return '';
                        }
                        return '<div class="invoice-file-form custom-file-form-style" data-options=\'{"deleteEnable":false, "previewEnable":true, "uploadEnable": false, "moreFileUploadEnable": true, "fileSize": 50, "fileTypes": ".xls,.doc,.txt,.pdf"}\' data-fileIds = "'+row.fileId+'"></div>';
                        // return '<a style="color: #108ee9" onclick="replyDownload(' + row.fileId + ')">'+row.fileName+'</a>';
                        // return "<a style=\"color: #108ee9\" href='" + g.ctx + "pc/sys/file/rest/download/" + row.fileId + "'>" + row.fileName + "</a>";
                    }
                },
                {
                    field: 'deductionCodeType',
                    title: '可抵扣编号',
                    width: 100,
                    formatter: function (value) {
                        if (Number(value) === 1) {
                            return '可抵扣';
                        }
                        if (Number(value) === 2) {
                            return '不可抵扣';
                        }
                    }
                },
                {
                    field: 'invoiceDate',
                    title: '缴款书日期',
                    width: 180,
                    formatter: function (value) {
                        if (value){
                            return moment(value).format("YYYY-MM-DD");
                        }
                        return '';
                    }
                },
                {
                    field: 'invoiceCode',
                    title: '缴款书代码',
                    width: 150
                },
                {
                    field: 'invoiceNumber',
                    title: '缴款书号码',
                    width: 150
                },
                // {
                //     field: 'dutyParagraph',
                //     title: '税号',
                //     width: 150
                // },
                {
                    field: 'electronInvoiceNumber',
                    title: '数电缴款书号码',
                    width: 150,
                },
                {
                    field: 'taxRate',
                    title: '税率',
                    width: 170,
                    formatter: function (value) {
                        if (value){
                            for(var j = 0; j < taxDict1.length; j++){
                                if(taxDict1[j].itemCode === value){
                                    return taxDict1[j].itemRemark;
                                }
                            }
                        }
                        return '';
                    },
                },
                {
                    field: 'currencyCode',
                    title: '币种',
                    width: 120
                },
                {
                    field: 'taxAmount',
                    title: '含税金额',
                    width: 130,
                    formatter: function (value) {
                        return formatterCustomPrice(value,2,true,false);
                    },
                },
                {
                    field: 'noTaxAmount',
                    title: '未税金额',
                    width: 130,
                    formatter: function (value) {
                        return formatterCustomPrice(value,2,true,false);
                    },
                },
                {
                    field: 'diffTaxMoney',
                    title: '税额',
                    width: 130,
                    formatter: function (value) {
                        return formatterCustomPrice(value,2,true,false);
                    },
                },

            ]
        ]
    }


    $(el.tbInvoicePaymentCertificate).edatagrid({
        name:'tbInvoicePaymentCertificateTable',
        loadMsg: '数据加载中, 请耐心等待......',
        // height: el.bodyHeight - dataDiv,
        height: 400,
        url: g.ctx + 'pc/finance/company/invoiced/payment/certificate/rest/find/by/apply/id',
        singleSelect: false,
        showFooter: true,
        rownumbers: true,
        // rowHeight: 'auto',
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // title:"<span style='color: red'>*财务确认之后，未经双方确认不允许红冲发票，请与采购沟通确认</span>",
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        queryParams: {
            iaId: $(el.id).val()
        },
        columns: columns,
        toolbar: toolbars,
        onClickRow: function (index) {
            initFileForm('invoice-file-form');
            if (invoiceLookFlag===0){
                endInvoicePaymentCertificateEditor();
                $(el.tbInvoicePaymentCertificate).edatagrid('editRow', index);
                editor2 = index;
                debugger
                var file = $(el.tbInvoicePaymentCertificate).edatagrid('getEditor', {index: editor2, field: 'file'});
                var row = $(el.tbInvoicePaymentCertificate).edatagrid('getRows')[editor2];
                if (file) {
                    $(file.target).next().children(".validatebox-readonly").click(function () {
                        console.log(row)
                        console.log(row.fileId)
                        if (row.fileId){
                            window.location.href = g.ctx+'pc/sys/file/rest/download/'+row.fileId;
                        }
                    });
                    $(file.target).filebox('setText',row.fileName);
                }
                // addOrDelInvoice();
            }
        },
        onLoadSuccess: function (data) {
            $('#tbInvoice').parent(".datagrid-view").children(".datagrid-view1")
                .children(".datagrid-body")
                .children(".datagrid-body-inner")
                .children(".datagrid-btable")
                .children("tbody")
                .children("tr")
                .children("td")
                .children(".datagrid-cell-rownumber").css('height', '60px').css('line-height', '60px')
            // if (data.rows.length>0){
                initFileForm('invoice-file-form');
            // }

        },
    });
}

function invoicePaymentCertificateExport() {
    var rows = $(el.tbInvoicePaymentCertificate).datagrid('getRows');

    for(var i = 0; i < rows.length; i++){
        var row =rows[i];
        row['invoiceDate']=timestampToTime(row['invoiceDate']);
    }

    $(el.tbInvoicePaymentCertificate).datagrid('toExcel', {
        filename: '开票申请数据-关联缴款书.xls',
        rows: rows,
        worksheet: '开票申请明细-关联缴款书'
    });
}

/**
 * 添加发票
 */
function addInvoicePaymentCertificateItem() {
    // endInvoiceEditor();
    var index = $(el.tbInvoicePaymentCertificate).edatagrid('appendRow', {
        id: 0,
        dutyParagraph: el.supplierBusinessRegisterNo,
        taxRate: el.supplierTaxRate,
        currencyCode: el.supplierCurrencyCode,
    }).edatagrid("getRows").length - 1;
    // $(el.tbInvoicePaymentCertificate).edatagrid('beginEdit', index);
    $(el.tbInvoicePaymentCertificate).edatagrid('editRow', index);
    editor2 = index;
    // addOrDelInvoice();
}

//结束行编辑
function endInvoicePaymentCertificateEditor() {
    $(el.tbInvoicePaymentCertificate).edatagrid('saveRow')
    editor2 = undefined;
    //重新计算表头的某些字段值
    var rows = $(el.tbInvoicePaymentCertificate).edatagrid('getRows');
    countPageHeadInvoicePaymentCertificate(rows);
}

function endInvoiceOtherEditor() {
    $(el.tbInvoicePaymentCertificate).edatagrid('saveRow')
    editor2 = undefined;
    //重新计算表头的某些字段值
    var rows = $(el.tbInvoicePaymentCertificate).edatagrid('getRows');
    countPageHeadOtherInvoicePaymentCertificate(rows);
}




/**
 * 删除关联发票明细数据
 */
function delInvoicePaymentCertificateItem() {
    endInvoiceEditor();
    var rows = $(el.tbInvoicePaymentCertificate).edatagrid('getSelections');
    if (rows.length<=0) {
        layer.msg("请选择您要删除的发票信息");
        return;
    }


    var serialNos = [];
    for (var j = 0; j < rows.length; j++) {
        if (rows[j].serialNo){
            serialNos.push(rows[j].serialNo);
        }
    }
    if (serialNos.length>0){
        var loading = top.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/sys/kingdeeInvoiceCloudAssistant/rest/deleteInvoice',
            method: "post",
            data: {serialNos: serialNos.join(",")},
            success: function () {
                for (var i = 0; i < rows.length; i++) {
                    var index = $(el.tbInvoicePaymentCertificate).edatagrid("getRowIndex", rows[i]);
                    $(el.tbInvoicePaymentCertificate).edatagrid("deleteRow", index);
                }
            },
            complete: function(data) {
                top.layer.close(loading);
            },
            error: function (data) {
                parent.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    }else {
        for (var i = 0; i < rows.length; i++) {
            var index = $(el.tbInvoicePaymentCertificate).edatagrid("getRowIndex", rows[i]);
            $(el.tbInvoicePaymentCertificate).edatagrid("deleteRow", index);
        }
    }
    //重新计算表头的某些字段值
    var rows = $(el.tbInvoicePaymentCertificate).edatagrid('getRows');
    countPageHeadInvoicePaymentCertificate(rows);
}
/**
 * 导入关联发票明细数据
 */
function importPaymentCertificateInvoice() {
    var importDialog = openImportExcelDialog('static/excel/缴款书导入模板.xls','缴款书导入',function(file){
        let formData = new FormData();
        formData.append("file", file);
        var loading = topWin.layer.msg('处理中', {icon: 16, shade: [0.1, '#000'], time: false});
        $.ajax({
            url: g.ctx + 'pc/finance/company/invoiced/payment/certificate/rest/importData',
            method: "POST",
            data: formData,
            contentType: false,
            processData: false,
            success: function (data) {
                topWin.layer.alert("导入成功", {icon: 1}, function (idx) {
                    topWin.layer.close(idx);
                    let ps = $(el.tbInvoicePaymentCertificate).datagrid('getRows');
                    // console.log(data)
                    // console.log(ps)
                    for (let i = 0; i < data.length; i++) {
                        let invoice = data[i];
                        // let sameFlag = false;
                        // for (let j = 0; j < ps.length; j++) {
                        //     if (invoice.invoiceNumber === ps[j].invoiceNumber) {
                        //         sameFlag = true;
                        //         break;
                        //     }
                        // }
                        // if (sameFlag){
                        //     continue;
                        // }
                        $(el.tbInvoicePaymentCertificate).datagrid('appendRow', {
                            deductionCodeType: invoice.deductionCodeType,
                            invoiceCode: invoice.invoiceCode,
                            invoiceNumber: invoice.invoiceNumber,
                            electronInvoiceNumber: invoice.electronInvoiceNumber,
                            dutyParagraph: invoice.dutyParagraph,
                            invoiceDate: invoice.invoiceDate,
                            taxRate: invoice.taxRate,
                            currencyCode: invoice.currencyCode,
                            noTaxAmount: invoice.noTaxAmount,
                            taxAmount: invoice.taxAmount,
                            diffTaxMoney: invoice.diffTaxMoney
                        });
                    }
                    importDialog.dialog('close');
                });
            },
            complete: function(data) {
                topWin.layer.close(loading);
            },
            error: function (data) {
                topWin.layer.alert(JSON.parse(data.responseText).message,{icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    });
    // openLayerWin("导入", "/fin/invoiced/apply/importUI", "900px", "70%");
}



/**
 * 新增或删除数据时重新计算关联发票表头、表体
 */
function addOrDelPaymentCertificateInvoice() {
    $(el.tbInvoicePaymentCertificate).edatagrid('saveRow')


    //全部结束行编辑
    // for (let i = 0;i<rows.length;i++){
    //     $(el.tbInvoicePaymentCertificate).edatagrid('endEdit', i);
    //
    // }
    var rows = $(el.tbInvoicePaymentCertificate).edatagrid('getRows');
    // 刷新表体统计行金额
    refreshInvoicePaymentCertificateFooter(rows);

    //重新计算表头的某些字段值
    countPageHeadInvoicePaymentCertificate(rows);

}

function countPageHeadInvoicePaymentCertificate(rows) {
    //发票张数
    // $(el.invoiceNum).numberbox('setValue', rows.length);

    var noTaxAmount = new BigNumber(0), taxAmount = new BigNumber(0), invoiceDiffAmount = new BigNumber(0);
    var taxNo = "";
    for (var i = 0; i < rows.length; i++) {
        var item = rows[i];
        if (item.taxAmount){
            noTaxAmount = noTaxAmount.plus(item.noTaxAmount);
            taxAmount = taxAmount.plus(item.taxAmount);
        }
        if (item.invoiceNumber) {
            taxNo = taxNo + item.invoiceNumber + ",";
        }
        if (item.electronInvoiceNumber) {
            taxNo = taxNo + item.electronInvoiceNumber + ",";
        }
        if (item.diffTaxMoney) {
            invoiceDiffAmount = invoiceDiffAmount.plus(item.diffTaxMoney);
        }

    }
    // 发票号
    // $(el.invoiceNo).textbox('setValue', taxNo.substring(0,taxNo.length -1));
    // 关联净价总金额
    $(el.paymentCertificateTotalExclTax).textbox('setValue', noTaxAmount.decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
    // 关联含税总金额
    $(el.paymentCertificateTotalInclTax).textbox('setValue', taxAmount.decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
    // 发票税额
    $(el.paymentCertificateTaxAmount).textbox('setValue', invoiceDiffAmount.decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
//     var invoiceTaxAmount = $(el.invoiceTaxAmount).textbox('getValue');
//     invoiceTaxAmount = new BigNumber(invoiceTaxAmount.replace(/,/g,''));
//
//     var diffAmount = $(el.diffAmount).textbox('getValue');
//     diffAmount = new BigNumber(diffAmount.replace(/,/g,''));
// //金额差
//     $(el.diffAmountSap).textbox('setValue', taxAmount.minus(invoiceTaxAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
// //税额差
//     $(el.diffTaxAmountSap).textbox('setValue', invoiceDiffAmount.minus(diffAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
}

function countPageHeadOtherInvoicePaymentCertificate(rows) {
    //发票张数
    $(el.invoiceNum).numberbox('setValue', rows.length);
    var taxNo = "";
    for (var i = 0; i < rows.length; i++) {
        var item = rows[i];
        if (item.invoiceNumber) {
            taxNo = taxNo + item.invoiceNumber + ",";
        }
    }
    // 发票号
    $(el.invoiceNo).textbox('setValue', taxNo.substring(0,taxNo.length -1));
}

/**
 * 刷新关联发票明细表格页脚
 */
function refreshInvoicePaymentCertificateFooter(rows) {
    debugger
    var noTaxAmount = new BigNumber(0), taxAmount = new BigNumber(0),diffTaxMoney = new BigNumber(0);

    for (var i = 0; i < rows.length; i++) {
        var item = rows[i];
        if (item.taxAmount && item.taxRate) {
            var taxData = {};
            for(var j = 0; j < taxDict1.length; j++){
                if(taxDict1[j].itemCode === item.taxRate){
                    taxData = taxDict1[j];
                    break;
                }
            }
            // 税率转换 = 1 + 税率值
            var tax = new BigNumber(taxData.itemName.match(/\d+/g)[0]);
            var taxConvert = new BigNumber(1).plus(tax / 100);
            // 到票未税单价 = 到票含税单价 / (1 + 税率)
            item.noTaxAmount = new BigNumber(item.taxAmount).div(taxConvert).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN);
        }
        // var rowIndex = $(el.tbInvoicePaymentCertificate).datagrid('getRowIndex', item1);
        if (item.taxAmount && item.noTaxAmount) {
            item.diffTaxMoney = new BigNumber(item.taxAmount-item.noTaxAmount).decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN);

        }
        if(item.noTaxAmount){
            noTaxAmount = noTaxAmount.plus(item.noTaxAmount);
        }
        if(item.taxAmount){
            taxAmount = taxAmount.plus(item.taxAmount);
        }
        if(item.diffTaxMoney){
            diffTaxMoney = diffTaxMoney.plus(item.diffTaxMoney);
        }
        $(el.tbInvoicePaymentCertificate).edatagrid('updateRow', {
            index: i,
            row: {
                noTaxAmount: Number(item.noTaxAmount),
                diffTaxMoney: Number(item.diffTaxMoney)
            }
        });

    }


    // //全部结束行编辑
    // for (let ii = 0;ii<rows.length;i++){
    //     $(el.tbInvoicePaymentCertificate).datagrid('endEdit', ii);
    //
    // }

    if(0 !== rows.length){
        // 更新页脚行的值并刷新
        var footers = $(el.tbInvoicePaymentCertificate).edatagrid('getFooterRows');
        footers[0]['noTaxAmount'] = noTaxAmount.decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN);
        footers[0]['taxAmount'] = taxAmount.decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN);
        footers[0]['diffTaxMoney'] = diffTaxMoney.decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN);
        $(el.tbInvoicePaymentCertificate).edatagrid('reloadFooter');
    }else {
        // 更新页脚行并载入新数据
        $(el.tbInvoicePaymentCertificate).edatagrid('reloadFooter', [
            {
                noTaxAmount: 0,
                taxAmount: 0,
                diffTaxMoney: 0
            }
        ]);
    }
}

function getFileName(o){
    var pos=o.lastIndexOf("\\");
    return o.substring(pos+1);
}
function replyDownload(fileId){
    console.log(fileId)
    window.location.href = g.ctx+'pc/sys/file/rest/download/'+fileId;
}

function updatePageShowValue(girdTr, oriRowData, columns, columnsData) {
    // for(var i = 0; i < columns.length; i++){
    //     var value = columnsData[i], item = columns[i];
    //     if(Number(value) < 0){
    //         value = '<span style="color: red;">' + formatNumber(value, item.cent, 1) + '</span>'
    //     }else {
    //         value = formatNumber(value, item.cent, 1);
    //     }
    //     girdTr.siblings('td[field="' + item.column + '"]').find('div').html(value);
    //     oriRowData[item.column] = columnsData[i];
    // }

    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 productJson
 */
function importInvoiceRow(supJson) {
    let old_supplier = $(el.tbInvoicePaymentCertificate).edatagrid('getRows');
    for (let i = 0; i < supJson.length; i++) {
        let supplier = supJson[i];
        console.log(JSON.stringify(supplier))
        // mark 为0代表新增的供应商
        $(el.tbInvoicePaymentCertificate).edatagrid('appendRow', {
            deductionCodeType: Number(supplier.deductionCodeType),
            invoiceDate: moment(supplier.invoiceDate).format("YYYY-MM-DD"),
            invoiceCode: supplier.invoiceCode,
            invoiceNumber: supplier.invoiceNumber,
            dutyParagraph: supplier.dutyParagraph,
            taxRate: supplier.taxRate,
            currencyCode: supplier.currencyCode,
            taxAmount: supplier.taxAmount,
            noTaxAmount: supplier.noTaxAmount,
            diffTaxMoney: supplier.diffTaxMoney,
        });
    }
}
