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

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

});
var editor = undefined;
var taxDict = [];
let assistantUploadWindow;
let assistantViewWindow;


function findTaxDictData() {
    $.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;
                taxDict.push(obj);
            }
        }
    });
}

/**
 * 初始化关联发票表格
 */
function initTbInvoice() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;
    var toolbars = [];
    var columns;
    if (invoiceLookFlag===0){
        toolbars = [
            {
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    addInvoiceItem();
                }
            },
            // '-',
            // {
            //     text: "从发票云添加", iconCls: 'icon-remove', handler: loadKingdeeAssistant
            // },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    delInvoiceItem();
                }
            },
            '-',
            {
                text: '导入',
                iconCls: 'icon-import',
                handler: function () {
                    importInvoice();
                }
            },
            // '-',
            // {
            //     text: '计算未税和税额',
            //     iconCls: 'icon-coins',
            //     handler: function () {
            //         addOrDelInvoice();
            //     }
            // }
        ];
        columns = [
            [
                {
                    field: 'ck',
                    checkbox: true
                },
                {
                    field: 'file',
                    title: '发票附件',
                    width: 300,
                    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”
                                formData.append('billId', $(el.accountStatementNo).textbox('getValue'));
                                formData.append('orgNumber', $(el.companyCode).combobox('getValue'));
                                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) {
                                        if (result.validateMessage) {
                                            layer.alert("发票云识别报错："+result.validateMessage, {title: '温馨提示'});
                                            tath.filebox('clear');
                                            return false
                                        }
                                        result.fileName = getFileName(fileName);
                                        $(el.tbInvoice).edatagrid("endEdit", editor);
                                        delete result.currencyCode;
                                        // delete result.taxRate;
                                        let row = {
                                            index: editor,
                                            row: result
                                        };
                                        $(el.tbInvoice).edatagrid('updateRow', row);
                                        initFileForm('invoice-file-form');
                                        // $(el.tbInvoice).datagrid("beginEdit", editor);
                                        if (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: 'type',
                    title: '发票类型',
                    width: 100,
                    sortable: true,
                    exportEnum:[
                        {code:0,codeWithDesc:'蓝票'},
                        {code:1,codeWithDesc:'红票'},
                    ],
                    formatter: function (value) {
                        switch (Number(value)) {
                            case 0:
                                return '<span style="color: blue;">蓝票</span>';
                            case 1:
                                return '<span style="color: red;">红票</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'deductionStatus',
                    title: '发票状态',
                    width: 100,
                    sortable: true,
                    exportEnum:[
                        {code:3,codeWithDesc:'红冲'},
                    ],
                    formatter: function (value) {
                        switch (Number(value)) {
                            case 3:
                                return '<span style="color: red;">红冲</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    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: 100,
                    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 < taxDict.length; j++){
                                if(taxDict[j].itemCode === value){
                                    return taxDict[j].itemRemark;
                                }
                            }
                        }
                        return '';
                    },
                    // editor: {
                    //     type: 'combobox',
                    //     options: {
                    //         valueField: 'itemCode',
                    //         textField: 'itemRemark',
                    //         data: taxDict,
                    //         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 () {
                    // 刷新表体统计行金额
                    refreshInvoiceFooter($(el.tbInvoice).edatagrid('getRows'));
                    invoiceExport();
                }
            },

        ]
        columns = [
            [
                {
                    field: 'file',
                    title: '发票附件',
                    width: 300,
                    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 fileName = $(this).filebox('getValue');
                                var  tath = $(this);
                                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”
                                formData.append('billId', $(el.accountStatementNo).textbox('getValue'));
                                formData.append('orgNumber', $(el.companyCode).combobox('getValue'));
                                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) {
                                        if (result.validateMessage) {
                                            layer.alert("发票云识别报错："+result.validateMessage, {title: '温馨提示'});
                                            tath.filebox('clear');
                                            return false
                                        }
                                        result.fileName = getFileName(fileName);
                                        $(el.tbInvoice).edatagrid("endEdit", editor);
                                        // delete result.taxRate;
                                        let row = {
                                            index: editor,
                                            row: result
                                        };
                                        $(el.tbInvoice).edatagrid('updateRow', row);
                                        initFileForm('invoice-file-form');
                                        // $(el.tbInvoice).datagrid("beginEdit", editor);
                                        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: 'type',
                    title: '发票类型',
                    width: 100,
                    sortable: true,
                    exportEnum:[
                        {code:0,codeWithDesc:'蓝票'},
                        {code:1,codeWithDesc:'红票'},
                    ],
                    formatter: function (value) {
                        switch (Number(value)) {
                            case 0:
                                return '<span style="color: blue;">蓝票</span>';
                            case 1:
                                return '<span style="color: red;">红票</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'deductionStatus',
                    title: '发票状态',
                    width: 100,
                    sortable: true,
                    exportEnum:[
                        {code:3,codeWithDesc:'红冲'},
                    ],
                    formatter: function (value) {
                        switch (Number(value)) {
                            case 3:
                                return '<span style="color: red;">红冲</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    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: 100,
                    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 < taxDict.length; j++){
                                if(taxDict[j].itemCode === value){
                                    return taxDict[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: 300,
                    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: 'type',
                    title: '发票类型',
                    width: 100,
                    sortable: true,
                    exportEnum:[
                        {code:0,codeWithDesc:'蓝票'},
                        {code:1,codeWithDesc:'红票'},
                    ],
                    formatter: function (value) {
                        switch (Number(value)) {
                            case 0:
                                return '<span style="color: blue;">蓝票</span>';
                            case 1:
                                return '<span style="color: red;">红票</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'deductionStatus',
                    title: '发票状态',
                    width: 100,
                    sortable: true,
                    exportEnum:[
                        {code:3,codeWithDesc:'红冲'},
                    ],
                    formatter: function (value) {
                        switch (Number(value)) {
                            case 3:
                                return '<span style="color: red;">红冲</span>';
                            default:
                                return '';
                        }
                    }
                },
                {
                    field: 'deductionCodeType',
                    title: '可抵扣编号',
                    width: 100,
                    formatter: function (value) {
                        if (Number(value) === 1) {
                            return '可抵扣';
                        }
                        if (Number(value) === 2) {
                            return '不可抵扣';
                        }
                    }
                },
                {
                    field: 'invoiceDate',
                    title: '发票日期',
                    width: 100,
                    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 < taxDict.length; j++){
                                if(taxDict[j].itemCode === value){
                                    return taxDict[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.tbInvoice).edatagrid({
        name:'tbInvoiceTable',
        loadMsg: '数据加载中, 请耐心等待......',
        // height: el.bodyHeight - dataDiv,
        height: 400,
        url: g.ctx + 'pc/finance/invoiced/receipt/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,
        rowStyler: function (index, row) {
            //如果是补票且不允许删除
            if (optType===8&&Number(row.notDeleteFlag) === 1) {
                return 'background-color:#FAC80026;';
            }
        },
        onBeforeEdit: function (index, row) {
            if (optType===8&&Number(row.notDeleteFlag) === 1) {
                return false;
            }
        },
        onClickRow: function (index, rowData) {
            initFileForm('invoice-file-form');
            if (invoiceLookFlag===0){
                //如果不是补票且允许删除
                if (optType!==8&&Number(rowData.notDeleteFlag) !== 1) {
                    endInvoiceEditor();
                    $(el.tbInvoice).edatagrid('editRow', index);
                    editor = index;
                    debugger
                    var file = $(el.tbInvoice).edatagrid('getEditor', {index: editor, field: 'file'});
                    var row = $(el.tbInvoice).edatagrid('getRows')[editor];
                    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')
            // $(this).edatagrid('fixRowHeight'); // 修正行高
            // if (data.rows.length>0){
                initFileForm('invoice-file-form');
            // }

        },
    });
}


/**
 * 添加发票
 */
function addInvoiceItem() {
    var accountStatementNo = $(el.accountStatementNo).textbox('getValue');
    if (!accountStatementNo){
        topWin.layer.alert('请先选择对账单',{icon: 2, shadeClose: true, title: '温馨提示'});
        return false;
    }
    var rows = $(el.tbInvoice).edatagrid('getRows');
    // endInvoiceEditor();
    var index = $(el.tbInvoice).edatagrid('appendRow', {
        id: 0,
        notDeleteFlag: 0,
        dutyParagraph: el.supplierBusinessRegisterNo,
        taxRate: rows.length>0?rows[0].taxRate:el.supplierTaxRate?el.supplierTaxRate:$(el.taxCode).combobox('getValue'),
        currencyCode: rows.length>0?rows[0].currencyCode:el.supplierCurrencyCode?el.supplierCurrencyCode:$(el.currencyCode).textbox('getValue'),
    }).edatagrid("getRows").length - 1;
    // $(el.tbInvoice).edatagrid('beginEdit', index);
    $(el.tbInvoice).edatagrid('editRow', index);
    editor = index;
    // addOrDelInvoice();
}

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

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




/**
 * 删除关联发票明细数据
 */
function delInvoiceItem() {
    endInvoiceEditor();

    // 获取选中行 + 对应索引（关键！）
    var allRows = $(el.tbInvoice).edatagrid('getRows');
    var selections = $(el.tbInvoice).edatagrid('getSelections');

    if (selections.length <= 0) {
        layer.msg("请选择您要删除的发票信息");
        return;
    }

    // 如果是补票且不可删除
    if (optType === 8) {
        for (var ii = 0; ii < selections.length; ii++) {
            if (selections[ii].notDeleteFlag === 1) {
                layer.msg("选中发票不可删除");
                return false;
            }
        }
    }

    // 提取 serialNos
    var serialNos = [];
    for (var j = 0; j < selections.length; j++) {
        if (selections[j].serialNo) {
            serialNos.push(selections[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 () {
                // ✅ 安全删除：提前计算索引（基于当前 allRows 和 selections 的匹配）
                var indicesToDelete = [];
                for (var i = 0; i < allRows.length; i++) {
                    // 判断 allRows[i] 是否在 selections 中（通过 serialNo 或其他唯一字段）
                    for (var s = 0; s < selections.length; s++) {
                        if (allRows[i].serialNo === selections[s].serialNo) {
                            indicesToDelete.push(i);
                            break;
                        }
                    }
                }

                // 逆序删除，防止索引偏移
                indicesToDelete.sort((a, b) => b - a);
                var grid = $(el.tbInvoice);
                indicesToDelete.forEach(idx => {
                    grid.edatagrid("deleteRow", idx);
                });
                grid.edatagrid("acceptChanges");
                countPageHeadInvoice(grid.edatagrid('getRows'));
            },
            complete: function() {
                top.layer.close(loading);
            },
            error: function (data) {
                parent.layer.alert(JSON.parse(data.responseText).message, {icon: 2, shadeClose: true, title: '温馨提示'});
            }
        });
    } else {
        // 无 serialNo：直接前端删除（同样用索引方式）
        var indicesToDelete = [];
        var currentRows = $(el.tbInvoice).edatagrid('getRows');
        for (var i = 0; i < currentRows.length; i++) {
            for (var s = 0; s < selections.length; s++) {
                if (currentRows[i].serialNo === selections[s].serialNo) {
                    indicesToDelete.push(i);
                    break;
                }
            }
        }
        indicesToDelete.sort((a, b) => b - a);
        var grid = $(el.tbInvoice);
        indicesToDelete.forEach(idx => {
            grid.edatagrid("deleteRow", idx);
        });
        grid.edatagrid("acceptChanges");
        countPageHeadInvoice(grid.edatagrid('getRows'));
    }
}
/**
 * 导入关联发票明细数据
 */
function importInvoice() {
    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/invoiced/receipt/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.tbInvoice).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.tbInvoice).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 addOrDelInvoice() {
    $(el.tbInvoice).edatagrid('saveRow')


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

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

}

function countPageHeadInvoice(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.invoiceTotalAmount).textbox('setValue', noTaxAmount.decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
    // 关联含税总金额
    $(el.invoiceTaxTotalAmount).textbox('setValue', taxAmount.decimalPlaces(2, priceHandle.cutType === 0 ? BigNumber.ROUND_HALF_UP : BigNumber.ROUND_DOWN));
    // 发票税额
    $(el.diffAmount1).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 countPageHeadOtherInvoice(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 refreshInvoiceFooter(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 < taxDict.length; j++){
                if(taxDict[j].itemCode === item.taxRate){
                    taxData = taxDict[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.tbInvoice).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.tbInvoice).edatagrid('updateRow', {
            index: i,
            row: {
                noTaxAmount: Number(item.noTaxAmount),
                diffTaxMoney: Number(item.diffTaxMoney)
            }
        });

    }


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

    if(0 !== rows.length){
        // 更新页脚行的值并刷新
        var footers = $(el.tbInvoice).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.tbInvoice).edatagrid('reloadFooter');
    }else {
        // 更新页脚行并载入新数据
        $(el.tbInvoice).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.tbInvoice).edatagrid('getRows');
    for (let i = 0; i < supJson.length; i++) {
        let supplier = supJson[i];
        console.log(JSON.stringify(supplier))
        // mark 为0代表新增的供应商
        $(el.tbInvoice).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,
        });
    }
}



/**
 * 查看发票云附件
 */
function viewKingdeeAssistant() {
    if (!$(el.accountStatementId).val()) {
        topWin.layer.alert('请先选择对账单');
    }
    const data = {
        // "billId": billId,
        "resource ": "SRM",
        // "billType": "开票申请单",
        billId: 2313974925850848256,
        billType: "er_tripreimbursebill",
    };
    $.ajax({
        type: 'post',
        url: g.ctx + 'pc/sys/kingdeeInvoiceCloudAssistant/rest/getAssistantInfo',
        data: JSON.stringify(data),
        contentType: 'application/json',
        success: function (data) {
            const httpUrl = "https://gxdev.jwipc.com:8022/ierp/";
            const wssUrl = "wss://gxdev.jwipc.com:8022/ierp/";
            const accessToken = data.accessToken;
            const eventCode = data.eventCode;

            let socket = new WebSocket(wssUrl + "msgwatch/?identifytype=" + billNo + "&token=" + accessToken);
            //打开事件
            socket.onopen = function () {
                setInterval(function () {
                    socket.send("{\"handshake\":false}");
                }, 20000);
            };
            //获得消息事件
            socket.onmessage = function (msg) {};
            //关闭事件
            socket.onclose = function () {
                if (assistantViewWindow) {
                    assistantViewWindow.close();
                }
            };
            //发生了错误事件
            socket.onerror = function () {
                console.log("连接失败");
                if (assistantViewWindow) {
                    assistantViewWindow.close();
                }
            };
            const url = httpUrl + 'index.html?userId=Guest&formId=rim_view_invoice&&eventCode=' + eventCode;
            assistantViewWindow = window.open(url, '_blank');
            // IFrame的方式会被浏览器的安全机制，控制住Cookie导致无法访问，废弃
            // const reqUrl = encodeURIComponent(httpUrl + 'index.html?formId=rim_view_invoice&&eventCode=' + eventCode);
            // const url = httpUrl + "accessTokenLogin.do?encode=true&access_token=" + accessToken + '&redirect=' + reqUrl;
            // let kingdeeAssistantDialog = openDialog("kingdeeAssistantDialog", url, {
            //     title: '发票上传',
            //     width: '1230px',
            //     height: '740px',
            //     cache: false,
            //     modal: true,
            //     border: false,
            //     draggable: true,
            //     shadow: false,
            //     onClose: function () {
            //         kingdeeAssistantDialog.dialog('destroy');
            //     },
            //     buttons: [{
            //         text: '关闭', iconCls: 'icon-cancel', handler: function () {
            //             kingdeeAssistantDialog.dialog('close');
            //         }
            //     }]
            // });
        },
        error: function (error) {
            topWin.layer.alert(error.responseJSON.message, {
                icon: 2,
                content: error.responseJSON.message
            });
        }
    });
}
