<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>企业文件</title>
    <link rel="stylesheet" href="/lib/layui-v2.6.3/css/layui.css" media="all">
    <link rel="stylesheet" href="/css/public.css" media="all">
    <link rel="stylesheet" href="/lib/font-awesome-4.7.0/css/font-awesome.min.css" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <!-- 上方搜索栏 -->
        <fieldset class="table-search-fieldset">
            <legend>搜索</legend>
            <div class="layui-form layui-form-pane">
                <div class="layui-form-item">
                    <!-- 搜索【工作流名】和【权限字符】-->
                    <div class="layui-inline">
                        <label class="layui-form-label">关键词</label>
                        <div class="layui-input-inline">
                            <input type="text" id="fileName" name="fileName" autocomplete="off" class="layui-input" placeholder="请输入关键词"/>
                        </div>
                    </div>
                    <!-- 搜索按钮 -->
                    <div class="layui-inline">
                        <button type="button" class="layui-btn layui-btn-primary layui-border-green btn-role-action" data-type="search">
                            <i class="layui-icon layui-icon-search"></i> 搜 索
                        </button>
                        <button type="button" class="layui-btn layui-btn-primary layui-border-box btn-role-action" data-type="refresh">
                            <i class="layui-icon layui-icon-refresh"></i> 清 空
                        </button>
                    </div>
                </div>
            </div>
        </fieldset>
        <!-- 表格 -->

        <table class="layui-hide" id="table-data" lay-filter="table-data"></table>
    </div>
</div>

<script type="text/html" id="toolbar-table">
    <div class="layui-btn-container">
        <button style="background-color: #154d96;" class="layui-btn layui-btn-sm layuimini-btn-primary" lay-event="btn-refresh"><i
                class="fa fa-refresh"></i></button>
        <button style="background-color: #154d96;" class="layui-btn layui-btn-normal layui-btn-sm" lay-event="btn-back"><i
                class="fa fa-mail-reply"/></i> 上一级
        </button>
        <div class="layui-btn-group" id="btn-group" style="visibility: hidden;">
            <button style="background-color: #154d96;" class="layui-btn layui-btn-normal layui-btn-sm" lay-event="uploadFile"><i
                    class="fa fa-cloud-upload"/></i></i> 上传文件
            </button>
        </div>
    </div>


</script>


<!-- 【行内按钮】表格每行末尾的操作按钮-->
<script type="text/html" id="table-tool">


    {{# if(d.fileFolder == 1) { }}
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="btn-preview">预览</a>
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="btn-collection">收藏</a>
    {{# if(d.roleUpload == 1) { }}
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="btn-change">替换文件</a>
    {{# } }}


    {{# if(d.roleDown == 1) { }}
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="btn-down">下载</a>
    {{# } }}
    {{# } }}
    {{# if(d.fileFolder == 0) { }}
    <a class="layui-btn layui-btn-xs layui-btn-normal" lay-event="btn-open">打开</a>
    {{# } }}

    {{# if(d.roleDelete == 1) { }}
    <a class="layui-btn layui-btn-xs layui-btn-danger" lay-event="btn-delete">删除</a>
    {{# } }}
</script>
<!--引入JS文件-->
<script src="/lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script src="/js/lay-config.js?v=1.0.4" charset="utf-8"></script>
<script src="/js/jquery-1.10.2.min.js" charset="utf-8"></script>
<style>
    .layui-table-cell {
        height: 60px;
        line-height: 60px;
    }
</style>
<script>
    let fileParentId = 0;
    layui.use(['table', 'dropdown', 'util', 'layer',], function () {
        let form = layui.form,
            dropdown = layui.dropdown,
            $ = layui.jquery,
            table = layui.table;

        let currPage = 1

        let arr = ["jpeg", "jpg", "png"];

        const searchInput = document.getElementById("fileName");

        let table_data = table.render({
            even: true,
            elem: '#table-data',
            url: '/cloud/share/list',
            where: {fileParentId: fileParentId},
            response: {statusCode: 200},
            toolbar: '#toolbar-table',
            defaultToolbar: ['filter', 'exports'],
            title: '企业文件',
            height: 'full-200',
            cols: [
                [
                    {type: "checkbox", width: 50},
                    {
                        field: 'fileImage', title: '', width: 80, align: 'center',
                        templet: function (d) {
                            if (d.fileOss) {
                                let extension = d.fileOss.split('.').pop(); //
                                if ($.inArray(extension, arr) > -1) {
                                    return '<img src="' + d.fileOss + '" style="width: 50px; height: 50px;" />';
                                }
                            }
                            return '<img src="' + d.fileImage + '" style="width: 25px; height: 25px;" />';
                        }
                    },
                    {field: 'fileName', title: '文件名称'},
                    {field: 'fileFormat', title: '文件格式', width: 150},
                    {
                        field: 'fileSize', title: '文件大小', width: 150, templet: function (d) {
                            let html = "";
                            if (d.fileSize === null) {
                                html = ""
                            } else {
                                html = d.fileSize + ` KB`
                            }
                            return html
                        }
                    },

                    {field: 'creatorName', title: '创建人', width: 150},
                    {
                        field: 'fileTop', title: '是否置顶', align: 'center', width: 95, templet: function (d) {
                            if (d.fileTop === null) {
                                return "";
                            } else {
                                if (d.roleUpload === 1) {
                                    let checkStr = "";
                                    if (d.fileTop === 1) {
                                        checkStr += " checked "
                                    }
                                    return '<input type="checkbox" lay-filter="check-fileTop" value="' + d.id + '" lay-skin="switch" lay-text="正常|禁用" ' + checkStr + '/>'
                                } else {
                                    return "";
                                }

                            }

                        }
                    },
                    {fixed: 'right', title: '操作', align: 'center', toolbar: '#table-tool', width: 300}
                ]
            ],
            page: {
                layout: ['limit', 'count', 'prev', 'page', 'next', 'skip', 'refresh'], // 自定义分页布局
                curr: 1, // 初始当前页
                limits: [30, 50, 100, 500, 1000], // 自定义每页显示条数选择项
                limit: 30 // 默认每页显示条数
            },
            done: function (res, curr, count) {

                getRole()
                if (res.data.length === 0 && curr > 1) {
                    table_data.reload({page: {curr: curr - 1}})
                }
                currPage = curr
            }
        });

        let active = {
            search: function () {
                table_data.reload({
                    page: {curr: 1},
                    where: {
                        fileName: $('#fileName').val(),
                        fileParentId: fileParentId
                    }
                });
            },
            refresh: function () {
                table_data.reload({
                    page: {curr: 1},
                    where: {fileName: ""}
                });
                $('#fileName').val('')
            }
        };
        $('.btn-role-action').on('click', function () {
            let type = $(this).data('type');
            active[type] ? active[type].call(this) : '';
        });

        searchInput.addEventListener('keydown', function (event) {
            if (event.key === 'Enter' || event.keyCode === 13) {
                event.preventDefault(); // 阻止默认行为（如表单提交）
                active['search'].call(this);
            }
        })

        table.on('toolbar(table-data)', function (obj) {
            let that = this;
            switch (obj.event) {
                case "btn-refresh":
                    table_data.reload()
                    break;
                case "btn-back":
                    $.ajax({
                        type: "get",
                        data: {"id": fileParentId},
                        dataType: "json",
                        url: "/cloud/space/getData",
                        success: function (data) {
                            if (data.code === 200) {
                                fileParentId = data.data.fileParentId;
                                table.reload('table-data', {
                                    page: {curr: 1},            // 页码
                                    where: {                    // 检索数据
                                        fileParentId: data.data.fileParentId
                                    }
                                });
                            } else {
                                layer.msg(data.msg, {icon: 2});
                            }
                        }
                    })
                    break;
                case "addFolder":
                    layer.open({
                        title: '新建目录',
                        type: 2,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: false,
                        area: ['800px', '700px'],
                        btn: ["确定", "取消"],
                        content: '/cloud/space/add',
                        yes: function (index, layero) {
                            let body = layer.getChildFrame('body', index);

                            let fileName = body.find("input[name='fileName']").val();
                            if (fileName.length <= 0) {
                                layer.msg('请输入目录名称！');
                                return;
                            }

                            let dataSet = {
                                "fileParentId": fileParentId,
                                "fileName": fileName
                            }

                            $.post("/cloud/space/addSave", dataSet, function (data) {
                                if (data.code === 200) {
                                    layer.open({
                                        type: 0,
                                        title: data.msg,
                                        closeBtn: 0,
                                        btn: ["继续添加", "关闭"],
                                        content: '是否继续添加？',
                                        btn1: function (index) {
                                            layer.close(index)
                                        },
                                        btn2: function (index2) {
                                            layer.close(index2);
                                            layer.close(index);
                                            table_data.reload();
                                        }
                                    });
                                } else {
                                    layer.msg(data.msg, {icon: 2});
                                }
                            });
                        }
                        , btn2: function (index, layero) {

                        },
                    });
                    break;
                case "uploadFile":
                    layer.open({
                        title: '上传文件',
                        type: 2,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: false,
                        area: ['900px', '700px'],
                        btn: ["取消"],
                        content: '/cloud/upload/index/' + fileParentId,

                        btn1: function (index, layero) {
                            table_data.reload();
                            layer.close(index);
                        }
                    });
                    break;
            }
        });

        table.on('rowDouble(table-data)', function (obj) {
            let data1 = obj.data;
            $.ajax({
                type: "get",
                data: {"fileId": data1.id},
                dataType: "json",
                url: "/cloud/fileRole/getData",
                success: function (data) {
                    if (data1.fileFolder == 0) {
                        if (data.code === 200) {
                            fileParentId = data1.id;
                            table.reload('table-data', {
                                page: {curr: 1},            // 页码
                                where: {                    // 检索数据
                                    fileParentId: data1.id
                                }
                            });

                        } else {
                            layer.msg(data.msg, {icon: 2});
                        }
                    } else {
                        copyImg(obj)
                        layer.msg("复制成功", {icon: 1});
                        //lately(data1.id, data1.fileOss);
                    }
                }
            })
        });

        /*复制图片*/
        function copyImg(dom) {
            /* 警告：dom不能是img标签，建议用DIV标签包裹img标签，否者会报错！不支持复制背景图！ */
            dom = dom.tr[0].querySelector('td[data-field="fileImage"]').querySelector('div')
            dom.style.userSelect = 'auto';
            let selection = getSelection(), range = document.createRange();
            selection.removeAllRanges(), range.selectNodeContents(dom), selection.addRange
            (range), document.execCommand('copy'), selection.removeAllRanges();
        }

        table.on('tool(table-data)', function (obj) {
            let that = this;
            let data = obj.data;
            let layEvent = obj.event;
            switch (layEvent) {
                case "btn-open":
                    data1 = data;

                    $.ajax({
                        type: "get",
                        data: {"fileId": data1.id},
                        dataType: "json",
                        url: "/cloud/fileRole/getData",
                        success: function (data) {
                            if (data.code === 200) {
                                fileParentId = data1.id;
                                table.reload('table-data', {
                                    page: {curr: 1},            // 页码
                                    where: {                    // 检索数据
                                        fileParentId: data1.id
                                    }
                                });
                            } else {
                                layer.msg(data.msg, {icon: 2});
                            }
                        }
                    })


                    break;
                case "btn-collection":

                    let dataSet = {
                        "fileId": data.id
                    }

                    $.post("/cloud/collect/collection", dataSet, function (data2) {
                        if (data2.code === 200) {
                            table_data.reload()
                            layer.msg(data2.msg, {time: 3000, icon: 1});
                        } else {
                            layer.msg(data2.msg, {time: 3000, icon: 2});
                        }
                    });
                    break;

                case "btn-preview":
                    lately(data.id, data.fileOss);
                    break;
                case "btn-down":
                    let a = document.createElement('a');  // 创建下载链接
                    a.href = data.fileOss;
                    a.target = '_blank';  // 新开页下载
                    a.download = data.fileName + data.fileFormat; // 下载文件名
                    document.body.appendChild(a);  // 添加dom元素
                    a.click();  //  点击下载
                    document.body.removeChild(a); // 下载后移除元素
                    window.URL.revokeObjectURL(data.fileOss);
                    a.remove();
                    break;
                case "btn-delete":
                    layer.confirm("<a style='color: red'>真的要删除该文件 " + data.fileName + " 吗？删除后可在回收站恢复！</a>", {
                        icon: 3, title: '删除文件确认【1/1】',
                        btn: ['确定', '取消'],
                        closeBtn: 0,
                        btn1: function (index) {
                            // 加载层
                            let index_loading = layer.load(1, {
                                shade: [0.2, '#fff'] //0.1透明度的白色背景
                            });
                            $.post("/cloud/space/delete", {id: data.id}, function (data2) {
                                // 关闭加载层
                                layer.close(index_loading)
                                if (data2.code === 200) {
                                    layer.msg(data2.msg, {time: 3000, icon: 1});
                                    table_data.reload();
                                } else {
                                    layer.msg(data2.msg, {time: 3000, icon: 2});
                                }
                            });
                        }

                    });
                    break;
                case "btn-edit":

                    layer.open({
                        title: '编辑信息',
                        type: 2,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: false,
                        area: ['800px', '700px'],
                        content: '/cloud/space/edit/' + data.id,
                        btn: ["确定", "取消"],
                        yes: function (index, layero) {
                            let body = layer.getChildFrame('body', index);

                            let fileName = body.find("input[name='fileName']").val();
                            if (fileName.length <= 0) {
                                layer.msg('请输入目录名称！');
                                return;
                            }

                            let dataSet = {
                                "id": data.id,
                                "fileName": fileName
                            }

                            $.post("/cloud/space/editSave", dataSet, function (data) {
                                if (data.code === 200) {
                                    layer.msg(data.msg, {time: 3000, icon: 1});
                                    table_data.reload();
                                    layer.close(index);

                                } else {
                                    layer.msg(data.msg, {icon: 2});
                                }
                            });
                        }
                        , btn2: function (index, layero) {

                        }
                    });

                    break;
                case "btn-change":
                    layer.open({
                        title: '上传文件',
                        type: 2,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: false,
                        area: ['900px', '700px'],
                        btn: ["取消"],
                        content: '/cloud/upload/changeIndex/' + data.id,

                        btn1: function (index, layero) {
                            table_data.reload();
                            layer.close(index);
                        }
                    });
                    break;
            }
        });

        form.on('switch(check-fileTop)', function (data) {
            // 注意：isChecked是操作之后的值
            let isChecked = data.elem.checked;
            let actionText = isChecked ? "开启" : "禁用"
            let newStatus = isChecked ? "1" : "0"
            let ids = data.value;
            layer.confirm('确认要置顶 ' + actionText + '？', {
                title: false,
                btn: ['确定', '取消'],
                closeBtn: 0,        // 不显示右上角的关闭（X）按钮
                // 按钮【确定】的回调
                btn1: function (index) {
                    $.post("/cloud/space/changeDeleteStatus/" + newStatus, {ids: ids}, function (d) {
                        if (d.code === 200) {
                            layer.msg(d.msg, {time: 3000, icon: 1});
                            data.elem.checked = isChecked;
                            form.render();
                        } else {
                            layer.msg(d.msg, {time: 3000, icon: 2});
                            data.elem.checked = !isChecked;
                            form.render();
                        }
                    });
                },
                // 按钮【取消】的回调
                btn2: function (index) {
                    data.elem.checked = !isChecked;
                    form.render();
                    layer.close(index);
                }
            });
        });


    });

    function parentOpenChange(fileName, fileOss, id, fileSize) {
        let dataSet = {
            "fileName": fileName,
            "fileOss": fileOss,
            "fileSize": fileSize,
            "id": id
        }

        $.post("/cloud/upload/editSave", dataSet, function (data) {
            if (data.code === 200) {

            } else {
                layer.msg(data.msg, {icon: 2});
            }
        });
    }

    function parentOpen(fileName, fileOss, fileParentId, fileSize) {
        let dataSet = {
            "fileName": fileName,
            "fileOss": fileOss,
            "fileParentId": fileParentId,
            "fileSize": fileSize,
        }

        $.post("/cloud/upload/addSave", dataSet, function (data) {
            if (data.code === 200) {

            } else {
                layer.msg(data.msg, {icon: 2});
            }
        });
    }


    function getRole() {
        $.ajax({
            type: "get",
            data: {},
            dataType: "json",
            url: "/cloud/roleUser/getRole",
            success: function (data) {
                if (data.code === 200) {

                    if (data.data.roleUpload == 1) {
                        $("#btn-group").css('visibility', "visible");
                    }
                }
            }
        })
    }

    function lately(id, url) {
        let dataSet = {
            "fileId": id
        }
        $.post("/cloud/lately/addSave", dataSet, function (data) {
            if (data.code === 200) {
                window.open('http://onlinefile.lingtao8.com/onlinePreview?url=' + encodeURIComponent(base64Encode(url)));
            } else {
                window.open('http://onlinefile.lingtao8.com/onlinePreview?url=' + encodeURIComponent(base64Encode(url)));
            }
        });
    }

    function base64Encode(str) {
        // 将字符串转换为UTF-8编码的字节序列，然后进行Base64编码
        return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function (match, p1) {
            return String.fromCharCode('0x' + p1);
        }));
    }
</script>
</body>
</html>
