/**
 * 开票申请，公共页签
 * 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});
    //     }
    // });
    initFile();
});
var editor = undefined;
var taxDict = [];


/**
 * 初始化关联发票表格
 */
function initFile() {
    var dataDiv = $(el.dataDiv).outerHeight() + 90;
    var toolbars = [];
    var columns;
    if (fileLookFlag===0){
        toolbars = [
            {
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    addFile();
                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    delFile();
                }
            },
            '-',
            {
                text: '保存',
                iconCls: 'icon-import',
                handler: function () {
                    saveFile();
                }
            }
        ];
        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 '';
                        }

                        if (row.fileName.indexOf(".pdf") != -1) {
                            return '<a style="color: #108ee9" onclick="previewPDF(\'' + row.fileId + '\',\'' + row.fileName + '\')">'+row.fileName+'</a>';
                        }else if(row.fileName.indexOf(".jpg")!=-1||row.fileName.indexOf(".png")!=-1){
                            return '<a style="color: #108ee9" onclick="previewImg(\'' + row.fileId + '\',\'' + row.fileName + '\')">'+row.fileName+'</a>';
                        }else {
                            return '<a style="color: #108ee9" onclick="replyDownload(' + row.fileId + ')">'+row.fileName+'</a>';
                        }
                    },
                    editor: {
                        type: 'filebox', options: {
                            editable: false,
                            buttonText: '选择文件',
                            onChange(e){
                                var fileName = $(this).filebox('getValue');
                                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: '/files/newUploadFile', //单文件上传
                                    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) {
                                        $(el.tbFile).edatagrid("endEdit", editor);
                                        $(el.tbFile).edatagrid('updateRow', {
                                            index: editor,
                                            row: {
                                                fileId: result,
                                                fileName: getFileName(fileName)
                                            }
                                        });
                                        // $(el.tbInvoice).datagrid("beginEdit", editor);
                                        layer.msg('上传成功', {icon: 1, title: '温馨提示'});
                                    },
                                    error: function (xhr, status, error) {
                                        $(this).filebox('setText','');
                                        layer.alert('文件上传失败', {icon: 2, title: '温馨提示'})
                                    }
                                });
                            }
                        }
                    }
                },
                {
                    field: 'createTime', title: '创建时间', width: 300
                    , formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                },
            ]
        ];
    }else if (fileLookFlag===2){
        toolbars = [
            {
                text: '添加',
                iconCls: 'icon-add',
                handler: function () {
                    addFile();
                }
            },
            '-',
            {
                text: '删除',
                iconCls: 'icon-remove',
                handler: function () {
                    delFile();
                }
            }
        ];
        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 '';
                        }

                        if (row.fileName.indexOf(".pdf") != -1) {
                            return '<a style="color: #108ee9" onclick="previewPDF(\'' + row.fileId + '\',\'' + row.fileName + '\')">'+row.fileName+'</a>';
                        }else if(row.fileName.indexOf(".jpg")!=-1||row.fileName.indexOf(".png")!=-1){
                            return '<a style="color: #108ee9" onclick="previewImg(\'' + row.fileId + '\',\'' + row.fileName + '\')">'+row.fileName+'</a>';
                        }else {
                            return '<a style="color: #108ee9" onclick="replyDownload(' + row.fileId + ')">'+row.fileName+'</a>';
                        }
                    },
                    editor: {
                        type: 'filebox', options: {
                            editable: false,
                            buttonText: '选择文件',
                            onChange(e){
                                var fileName = $(this).filebox('getValue');
                                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: '/files/newUploadFile', //单文件上传
                                    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) {
                                        $(el.tbFile).edatagrid("endEdit", editor);
                                        $(el.tbFile).edatagrid('updateRow', {
                                            index: editor,
                                            row: {
                                                fileId: result,
                                                fileName: getFileName(fileName)
                                            }
                                        });
                                        // $(el.tbInvoice).datagrid("beginEdit", editor);
                                        layer.msg('上传成功', {icon: 1, title: '温馨提示'});
                                    },
                                    error: function (xhr, status, error) {
                                        $(this).filebox('setText','');
                                        layer.alert('文件上传失败', {icon: 2, title: '温馨提示'})
                                    }
                                });
                            }
                        }
                    }
                },
                {
                    field: 'createTime', title: '创建时间', width: 300
                    , formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                },
            ]
        ];
    }else {
        columns =  [
            [
                {
                    field: 'file',
                    title: '发票附件',
                    width: 400,
                    formatter: function (value, row, index) {
                        if (!row.fileId){
                            // return '<a style="color: grey" >点我上传</a>';
                            return '';
                        }
                        if(row.fileName.indexOf(".jpg")!=-1||row.fileName.indexOf(".png")!=-1){
                            return '<a style="color: #108ee9" onclick="previewImg(\'' + row.fileId + '\',\'' + row.fileName + '\')">'+row.fileName+'</a>';
                        }else {
                            return '<a style="color: #108ee9" onclick="replyDownload(' + row.fileId + ')">'+row.fileName+'</a>';
                        }

                    }
                },
                {
                    field: 'createTime', title: '创建时间', width: 300
                    , formatter: function (value) {
                        if (!value) {
                            return '';
                        }
                        return moment(value).format('YYYY-MM-DD HH:mm');
                    }
                },
            ]
        ]
    }


    $(el.tbFile).edatagrid({
        loadMsg: '数据加载中, 请耐心等待......',
        height: el.bodyHeight - dataDiv,
        url: g.ctx + 'fin/invoiced/file/rest/find/by/apply/id',
        singleSelect: false,
        showFooter: true,
        rownumbers: true,
        // 定义从服务器对数据进行排序
        remoteSort: false,
        // 定义是否允许多列排序
        // multiSort: true,
        pagination: false,
        queryParams: {
            iaId: $(el.id).val()
        },
        columns: columns,
        toolbar: toolbars,
        rowStyler: function (index, row) {
            if (Number(row.id) === 0) {
                return 'background-color:pink;';
            }
        },
        onClickRow: function (index) {
            if (fileLookFlag===0){
                endFileEditor();
                $(el.tbFile).edatagrid('editRow', index);
                editor = index;
                var file = $(el.tbFile).edatagrid('getEditor', {index: editor, field: 'file'});
                var row = $(el.tbFile).edatagrid('getRows')[editor];
                if (file) {
                    $(file.target).next().children(".validatebox-readonly").click(function () {
                        if (row.fileId){
                            window.location.href = '/files/replyDownload?fileId='+row.fileId;
                        }
                    });
                    $(file.target).filebox('setText',row.fileName);
                }
                // addOrDelInvoice();
            }
        }
    });
}


/**
 * 添加发票
 */
function addFile() {
    var index = $(el.tbFile).edatagrid('appendRow', {
        id: 0
    }).edatagrid("getRows").length - 1;
    $(el.tbFile).edatagrid('editRow', index);
    editor = index;
}

//结束行编辑
function endFileEditor() {
    $(el.tbFile).edatagrid('saveRow')
    editor = undefined;
}
function saveFile() {
    endFileEditor();
    var fileJson = $(el.tbFile).datagrid('getRows')
    var loading = topWin.layer.msg('数据提交中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
    $.ajax({
        url: '/fin/invoiced/file/rest/saveFile',
        type: 'POST',
        data: {fileJson: JSON.stringify(fileJson),iaId: $(el.id).val()},
        success: function () {
            topWin.layer.close(loading);
            topWin.layer.msg('数据保存成功', {icon: 1});
            $(el.tbFile).datagrid('load');
        },
        error: function (data) {
            topWin.layer.close(loading);
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    });
}



/**
 * 删除关联发票明细数据
 */
function delFile() {
    endFileEditor();
    var rows = $(el.tbFile).edatagrid('getSelections');
    if (rows.length<=0) {
        layer.msg("请选择您要删除的附件信息");
        return;
    }
    var ids = [];
    for (var i = 0; i < rows.length; i++) {
        var index = $(el.tbFile).edatagrid("getRowIndex", rows[i]);
        $(el.tbFile).edatagrid("deleteRow", index);
        if (rows[i].id!==0){
            ids.push(rows[i].id)
        }
    }
    $.ajax({
        type: "POST", //请求方式
        data: {ids: JSON.stringify(ids)},
        url: "/fin/invoiced/file/rest/deleteFile", //请求路径
        success: function (data) {
            layer.alert("删除成功", function (index) {
                layer.close(index);
                $(el.tbFile).datagrid('reload');
            })
        },
        error: function (data) {
            layer.alert(data.responseJSON.message);
            $(el.tbFile).datagrid('reload');
        }
    });

}

function previewPDF(fileId,fileName) {
    localStorage.pdf_url = '/files/newDownload?fileId=' + fileId;
    openMainLayerWin("PDF文件预览", '/static/pdfjs1/web/viewer.html', "1000px;", "100%");
}
/**
 * 预览图片
 */
function previewImg(fileId,fileName){
    layer.photos({
        photos: {
            "title": "图片预览",
            "start": 0,
            "data": [
                {
                    "alt": fileName,
                    "pid": 5,
                    "src": '/files/newDownload?fileId='+fileId
                }
            ]
        }
    });
}

function getFileName(o){
    var pos=o.lastIndexOf("\\");
    return o.substring(pos+1);
}
function replyDownload(fileId){
    window.location.href = '/files/newDownload?fileId='+fileId;
}
