/**
 * <p>
 *  repair
 * </p>
 *
 * @author Administrator
 * @since 2021/6/1
 */
// 目录树数据缓存
const dirCache = new Map();

function startRender() {
    layui.use(['uploader'], function () {
        const uploader = layui.uploader;
        // 目录树
        let dirTree, fileTable, activeNode;
        let currentNode, currentParentNode;
        let treeChildrenUrl = `${ctx}/business/directory/tree?busType=` + bus_type

        // 加载并渲染目录树
        let treeOps = {
            id: 'directoryTree',
            url: treeChildrenUrl,
            cache: false,
            // type: 'all',
            initLevel: 1, // 默认展开一级
            scroll: '#tree-toobar-div',
            width: 'fit-content',
            toolbar: true,
            toolbarShow: [], //置空默认菜单项
            sendSuccess: function (res) {
                if (res.flag) {
                    res.data.forEach(item => {
                        dirCache.set(item.id, item);
                    })

                    setTimeout(() => {
                        $('.dtree-nav-div.dtree-theme-item').each((index, elem) => {
                            let data = $(elem).data('basic');
                            if (data) {
                                if (typeof data === 'string') {
                                    data = JSON.parse(data);
                                }
                                let title = data.metadataComment || data.directoryName || data.fileName + data.fileSuffix;
                                $(elem).attr('title', title)
                            }
                        });
                    }, 200)
                }
            },
            done: function (nodes, elem) {
                // 模拟鼠标点击事件展开第一层目录
                elem.find('li:first>div:first>i:first').click();
                elem.find('li:first>div:first').click();
            },
            onClick: function (node) {
                activeNode = node;
                currentNode = getCurrentNode();
                currentParentNode = getCurrentParentNode();
                const {basicData} = node.param;
                setLocation(basicData.directoryPath)
                loadFileList(activeNode.param)
            },
            toolbarFun: {
                // 显示右键菜单之前的回调，用于设置显示哪些菜单
                loadToolbarBefore: function (buttons, param, $div) {
                    return buttons;
                }
            },
            toolbarExt: [
                {
                    toolbarId: "toolbar_dir_rename",
                    icon: "dtreefont dtree-icon-bianji",
                    title: "修改目录",
                    handler: function (node, elem) {
                        const {basicData} = node;
                        openDirectoryEditLayer(basicData, function (data) {
                            dirTree.partialRefreshEdit(elem, data);
                            dirTree.getChild(elem);
                            elem[0].click();
                        });
                    }
                },
                {
                    toolbarId: "toolbar_dir_delete",
                    icon: "dtreefont dtree-icon-delete1",
                    title: "删除目录",
                    handler: function (node, elem) {
                        const {id, parentId} = node;
                        deleteDirectory(id).then(() => {
                            //dirTree.partialRefreshDel(elem)
                            reZhanKai(currentParentNode);
                            // 点击父节点
                            $(`div[data-id="${parentId}"]`).click();
                        })
                    }
                }
            ],
            formatter: {
                title: function (data) { // 文字过滤，返回null,"",undefined之后，都不会改变原有的内容返回。
                    return formatterTitle(data);
                }
            }
        }
        dirTree = globalTree.init(treeOps);

        /**
         * 加载数据资源列表
         */
        function loadFileList(directory) {
            const {basicData} = directory, dirId = basicData.id;
            if (!basicData) return;
            Util.get(`/sys/file/repair/list?dirId=${dirId}`).then(({flag, data, msg}) => {
                if (!flag) {
                    showErrorMsg(msg);
                    return;
                }
                data && renderFileTable(data);
            });
        }

        function renderFileTable(data) {
            fileTable = listPage.init({
                table: {
                    id: 'dirMetadataTable',
                    searchFieldNames: 'metadataName',
                    height: 'full-110',
                    data: data,
                    cols: [[
                        {field: 'id', title: 'ID', hide: true},
                        {field: 'fileName', title: '文件名称', width: 300},
                        {field: 'directoryPath', title: '所属目录'},
                        {field: 'fileType', title: '文件类型', width: 160, align: 'center'},
                        {
                            field: 'fileSize',
                            title: '文件大小',
                            width: 160,
                            align: 'center',
                            templet: (data) => Util.fileSizeFormat(data.fileSize, "M")
                        },
                        {field: 'createTime', title: '最后修改时间', width: 160, align: 'center'},
                        {field: 'createUser', title: '最后修改用户', width: 160, align: 'center'},
                        {
                            fixed: 'right',
                            title: '操作',
                            toolbar: `#rowToolBar`,
                            width: 160,
                            align: 'center'
                        }
                    ]],
                },
            });
            // 查看按钮监听
            fileTable.addTableRowEvent('reupload', reupload)
            fileTable.addTableRowEvent('clean', cleanData)
        }

        function reupload(obj) {
            const fileId = obj.id;
            const layerId = 'reupload-layer';
            let uploadObject;
            let layerIndex = layer.open({
                title: '重新上传文件',
                content: `<div id="${layerId}" style="width: 800px; height: 160px;"></div>`,
                btn: ['上传', '取消'],
                success: function (layObj, index) {
                    uploadObject = renderUploader();
                },
                yes: function () {
                    uploadObject.uploadToServer();
                },
            });

            function renderUploader() {
                return uploader.render({
                    url: `${ctx}/sys/file/repair/upload/chunk`,//上传文件服务器地址，必填
                    fileCheckUrl: `${ctx}/sys/file/repair/upload/check`,//文件校验地址
                    fileMergeUrl: `/sys/file/repair/upload/chunk/complete`,
                    fileBoxEle: `#${layerId}`,//上传容器
                    height: '130px',
                    multiple: false,
                    getFormData: () => ({repairId: fileId}),
                    uploadFinished: function (ok) {
                        loadFileList(activeNode.param);
                        layer.close(layerIndex);
                    }
                });
            }
        }

        /**
         * 移除数据
         * @param obj
         */
        function cleanData(obj) {
            layer.confirm('该清理操作将删除该文件记录以及对该文件引用的资源数据，是否确定清理？', {}, function (index) {
                layer.close(index);
                Util.get(`/sys/file/repair/clean/${obj.id}`, {},).then(res => {
                    if (res.flag) {
                        showOkMsg('清理成功')
                        loadFileList(activeNode.param)
                    } else {
                        showErrorMsg(res.msg);
                    }
                }).catch(() => showErrorMsg());
            })

        }


        /**
         * 获取当前节点
         * @returns {*|jQuery|HTMLElement}
         */
        function getCurrentNode() {
            return $('li.dtree-nav-item div.dtree-theme-item-this');
        }

        /**
         * 获取当前节点的父级节点
         * @returns {*|jQuery}
         */
        function getCurrentParentNode() {
            return getCurrentNode().parent().parent().prev();
        }

        function reZhanKai(node) {
            let iconNode = node.find('i:first');
            if (iconNode.data('spread') === 'open') {
                iconNode.click();
                iconNode.click();
            } else {
                iconNode.click();
            }
        }
    });
}
