var options = {}
var el = {
    bodyHeight: document.documentElement.clientHeight
}
$(function () {
    var optionStr = localStorage.getItem($("#optionKey").val())
    options = JSON.parse(optionStr)
    loadGrid()
});

function fileUpload(v1, v2) {
    var filebox = $("#fileInput").filebox("files");
    if (filebox.length >= 1) {
        var formData = new FormData();
        for (let filebox1 of filebox) {
            formData.append("files", filebox1);
        }
        var index = topWin.layer.msg('0%', {icon: 16, time: 0, shade: [0.8, '#393D49']});
        $.ajax({
            url: g.ctx + 'pc/sys/file/rest/upload/files',
            data: formData,
            type: 'post',
            contentType: false,
            processData: false,
            xhr: function () {
                var xhr = new XMLHttpRequest();
                xhr.upload.addEventListener('progress', function (e) {
                    var progressRate = ((e.loaded / e.total) * 100).toFixed(0) + '%';
                    topWin.layer.close(index);
                    index = topWin.layer.msg(progressRate, {
                        icon: 16, time: 0, shade: [0.8, '#393D49']
                    });
                });
                return xhr;
            },
            success: function (d) {
                topWin.layer.close(index);
                //需要把结构拼接到table中
                if (options['mapping'] !== undefined) {
                    var mp = options['mapping']
                    $.each(d, function (idx, itm) {
                        $.each(mp, function (kkk, vvv) {
                            if (itm[kkk] !== undefined) {
                                itm[vvv] = itm[kkk]
                                delete itm[kkk]
                            }
                        })
                        $("#tb").datagrid("appendRow", itm);
                    })
                } else {
                    $.each(d, function (idx, itm) {
                        $("#tb").datagrid("appendRow", itm);
                    })
                }
            },
            error: function (d) {
                topWin.layer.close(index);
                topWin.layer.msg("上传文件错误!");
                $("#fileInput").filebox("clear");
            }
        })
    }
}

function save(call) {
    var rows = $("#tb").datagrid("getRows");
    call(rows)
}

/**
 * 加载页面表格
 */
function loadGrid() {
    var columns = [{
        field: 'ck', checkbox: true
    }, {
        field: 'fileName', title: "文件名", width: 200,
        formatter: function (value,row) {
            return '<a style="color: blue" href="'+g.ctx + 'pc/sys/file/rest/download/'+row.id+'">'+value+'<a>'
        }
    }]
    //如果存在自定义字段就直接显示文件名
    if (options['extendedColumns'] != undefined) {
        const deserializeColumns = options['extendedColumns'].map(column => {
            if (column.formatter !== undefined) {
                return {
                    ...column, formatter: function (val) {
                        // 使用 Function 构造函数创建函数
                        const firstBraceIndex = column.formatter.indexOf("{");
                        const lastBraceIndex = column.formatter.lastIndexOf("}");
                        const customFunction = new Function('data', column.formatter.substring(firstBraceIndex + 1, lastBraceIndex));
                        return customFunction(val);
                    }
                }
            } else {
                return column
            }

        });
        $.each(deserializeColumns, function (idx, itm) {
            columns.push(itm)
        })

    } else {
        columns.push({
            field: 'fileType', title: "文件类型", width: 80
        }, {
            field: 'fileSize', title: "文件大小", width: 70
        }, {
            field: 'dateline', title: "上传时间", width: 135
        })
    }
    columns.push({
        field: 'opt', title: "操作", width: 65, formatter: function (value, row) {
            // if (previewFlag(row.fileType)) {
                return '<a href="#" onclick="previewFileForm(undefined,\'' + row.fileName + '\',\'' + row.id + '\')">预览</a>'
            // }
            // return ''
        }
    });
    var pager = initGridPagerNew(el.bodyHeight, 37, 40);
    //如果listUrl和fileIds
    let url = ''
    if (options['listUrl'] == undefined) {
        url = g.ctx + 'pc/sys/file/rest/getFileListByFileIds?fileIds=' + options['fileIds']
    } else {
        url = options['listUrl']
    }
    var toolbar = [{
        text: XTJCGL.GYSYHGL_XZ, iconCls: 'icon-add', handler: function () {
            $("#fileUpload .filebox-label").click();
        }
    }, {
        text: XTJCGL.GYSYHGL_SC, iconCls: 'icon-remove', handler: function () {
            var rows = $("#tb").datagrid("getChecked");
            if (rows.length < 0) {
                topWin.layer.alert("请选至少一条数据", {icon: 3})
                return
            }
            topWin.layer.confirm('确定要删除选中文件吗?', {icon: 3}, function (index) {
                var rowIds = [];
                var rowIndex = [];
                $.each(rows, function (inx, itm) {
                    rowIds.push(itm.id);
                    rowIndex.push($("#tb").datagrid("getRowIndex",itm));
                });
                if (options['removeUrl'] != undefined) {
                    var removeUrl = options['removeUrl'];
                    if (options['removeUrl'].includes("?")) {
                        removeUrl = removeUrl + "&ids=" + rowIds.join(",")
                    } else {
                        removeUrl = removeUrl + "?ids=" + rowIds.join(",")
                    }
                    $.ajax({
                        url: removeUrl, type: 'POST', complete: function () {
                            topWin.layer.close(index);
                        }, success: function (d) {
                            $("#tb").datagrid("reload");
                        }, error: function (data) {
                            topWin.layer.alert(data.responseJSON.message, {icon: 2});
                        }
                    });
                } else {
                    $.each(rowIndex, function (idx, itm) {
                        $("#tb").datagrid("deleteRow", itm);
                    })
                    topWin.layer.close(index);
                }
            });
        }
    }]
    if (options.lookFlag == 1) {
        toolbar = []
    }
    $("#tb").datagrid({
        height: el.bodyHeight - 20,
        url: url,
        method: "GET",
        singleSelect: true,
        pagination: false,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        rownumbers: true,
        columns: [columns],
        toolbar: toolbar
    });
}