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

function startRender() {
    // 目录树
    let dirTree, metaListTable, fileUploadLayerWin, tempNode;

    let addMetadataLayerWin;
    /**
     * 打开关联数据表弹出层
     * @param directory
     * @param callback
     */
    const openAddMetadataLayer = function (directory, callback) {
        if (directory.reviewStatus === ReviewStatus.PASS || directory.reviewStatus === ReviewStatus.SUBMITTED) {
            addDataConfirm(open);
        } else {
            open();
        }

        /**
         * 弹出选择数据表窗口
         */
        function open() {
            layer.open({
                id: 'addMetadataLayer',
                type: 2,
                area: ['800px', '600px'],
                btn: ['确定', '取消'],
                content: `${ctx}/business/metadata/layer/choose?directoryId=${directory.id}`,
                success: function (layero) {
                    addMetadataLayerWin = window[layero.find('iframe')[0]['name']];
                },
                yes: function (index) {
                    addMetadataLayerWin && addMetadataLayerWin.ok().then(datas => {
                        if (datas && Array.isArray(datas) && datas.length > 0) {
                            const ids = datas.map(data => data.id).join(',');
                            $.post(`${ctx}/business/directory/save/metadata`, {
                                directoryId: directory.id,
                                metadataIds: ids
                            }, function (res) {
                                if (res.flag) {
                                    layer.msg('保存成功');
                                    refreshPermis().then(() => {
                                        layer.close(index);
                                        refreshDirectoryNode(tempNode, res.data);
                                        callback && callback();
                                    });
                                } else {
                                    layer.msg('保存失败')
                                }
                            })
                        } else {
                            layer.msg('没有选择任何数据')
                        }
                    });
                }
            });
        }
    }

    /**
     * 加载数据资源列表
     */
    const loadMetadataList = function (directory) {
        const {basicData} = directory;
        if (!basicData) return;
        let uploadPermis = true, viewPermis = true, removePermis = true, movePermis = true,
            permis = {uploadPermis, viewPermis, removePermis, movePermis};
        if (!WritePermisDirIds.includes(basicData.id) || basicData.id === '-') {
            permis.uploadPermis = false;
            permis.removePermis = false;
            permis.movePermis = false;
        }
        if (!ReadPermisDirIds.includes(basicData.id)) {
            permis.viewPermis = false;
        }
        let url = `${ctx}/business/metadata/list/directory`, where = {directoryId: basicData.id, allChild: true};
        if (!basicData.directoryType) {
            permis = false;
            url = `${ctx}/data-label/manager/api/view/data/page`;
            where = {id: basicData.id};
        }
        metaListTable = listPage.init({
            table: {
                permis: permis,
                id: 'dirMetadataTable',
                toolbar: '#tableToolBar',
                searchFieldNames: 'resourceName',
                url,
                where,
                height: 'full-110',
                method: 'get',
                text: {none: !permis || permis.viewPermis ? '没有数据' : '没有权限'},
                parseData: function (res) { //res 即为原始返回的数据
                    let data = res.data || {};
                    data.records = data.records.map(item => {
                        item.permis = permis
                        return item;
                    });
                    return {
                        "flag": res.flag, //解析接口状态
                        "msg": res.msg, //解析提示文本
                        "records": data.records || res.records || data, //解析数据长度
                        "total": data.total || data.length //解析数据列表
                    };
                },
                cols: [[
                    {type: 'checkbox', fixed: 'left'},
                    {field: 'id', title: 'ID', hide: true},
                    {
                        field: 'resourceName',
                        title: '数据名称',
                        width: 300,
                        templet: data => `<lable style="font-weight: ${data.hasMark ? 'bold' : 'italic'};">${data.resourceName}</lable>`

                    },
                    {field: 'directoryPath', title: '所属目录'},
                    {field: 'resourceComment', title: '中文注释/描述'},
                    {field: 'themeTask', title: '主题任务', hide: true},
                    {
                        field: 'dataSource',
                        title: '数据来源',
                        width: 160,
                        templet: data => DICT.getText('data_source', data.dataSource) || data.dataSource || ''
                    },
                    {field: 'taskTime', title: '任务时间', width: 180, align: 'center'},
                    {
                        fixed: 'right',
                        title: '操作',
                        toolbar: `#rowToolBar`,
                        width: 210,
                        align: 'center'
                    }
                ]],
            },
        });
        metaListTable.addTableRowEvent('addLink', function (obj) {
            openAddMetadataLayer(directory.basicData, () => {
                metaListTable.reloadTable();
            })
        })
        /**
         * 增加移动文件功能
         */
        metaListTable.addTableRowEvent('moveLink', function () {
            var table = layui.table, checkStatus = table.checkStatus('dirMetadataTable'),
                datas = checkStatus.data || [];
            if (basicData.id === 'ROOT' && !USER_ROLES.includes('ROLE_SA')) {
                showErrorMsg('没有权限');
                return false;
            }
            if (datas.length === 0) {
                showErrorMsg('请选择要移动的文件');
                return false;
            }

            const ids = datas.map(data => data.directoryId);
            const parentIdSet = new Set();
            datas.forEach(data => parentIdSet.add(data.parentId))
            openDirectorySelectLayer('move', (node)=>{
                if([...parentIdSet.values()].includes(node.id)){
                    showErrorMsg('不能选择当前目录');
                    return false;
                }
                return true;
            }).then(nodes => {
                const targetId = nodes[0].id;
                moveResource(ids.join(','), targetId).then(res => refreshPermis().then(() => metaListTable.reloadTable()));
            })
        })
        metaListTable.addTableRowEvent('removeLink', function (obj) {
            if (basicData.reviewStatus === ReviewStatus.PASS) {
                addDataConfirm(removeData)
            } else {
                layer.confirm('是否确定移除该数据？', {}, function (index) {
                    layer.close(index);
                    removeData();
                })
            }

            function removeData() {
                Util.send(`/business/directory/delete/${obj.directoryId}`, {}, 'delete').then(res => {
                    if (res.flag) {
                        showOkMsg('删除成功');
                        refreshPermis().then(() => {
                            metaListTable.reloadTable();
                            //refreshDirectoryNode(tempNode, res.data);
                        })
                    } else {
                        showErrorMsg(res.msg);
                    }
                }).catch(() => showErrorMsg());
            }
        })

        /**
         * 目录整编增加批量删除功能
         * @param ids
         * add 2024/04/11 xiongcl
         */
        metaListTable.addTableRowEvent('batchMoveLink', function (obj) {
            var table = layui.table, checkStatus = table.checkStatus('dirMetadataTable'),
                datas = checkStatus.data || [];
            if(datas.length<=0){
                showErrorMsg("请至少选择一条数据！");
                return false;
            }
            if (basicData.reviewStatus === ReviewStatus.PASS) {
                addDataConfirm(removeData)
            } else {
                layer.confirm('是否确定移除该数据？', {}, function (index) {
                    layer.close(index);
                    removeData();
                })
            }
            function removeData() {
                const ids = datas.map(data => data.directoryId);
                Util.send(`/business/directory/batch/delete/${ids.join(',')}`, {}, 'delete').then(res => {
                    if (res.flag) {
                        showOkMsg('删除成功');
                        refreshPermis().then(() => {
                            metaListTable.reloadTable();
                        })
                    } else {
                        showErrorMsg(res.msg);
                    }
                }).catch(() => showErrorMsg());
            }
        })
        metaListTable.addTableRowEvent('addFile', function () {

            upload(basicData, `${ctx}/sys/file/layer/dir?directoryId=${basicData.id}&secretLevel=${basicData.secretLevel}`, function (res) {
                if (res.success) {
                    refreshPermis().then(() => {
                        refreshDirectoryNode(tempNode, basicData);
                        metaListTable.reloadTable();
                    })

                }
            });
        });

        metaListTable.addTableRowEvent('addDirectory', function (obj) {
            upload(basicData, `${ctx}/sys/file/layer/dir?directoryId=${basicData.id}&secretLevel=${basicData.secretLevel}&dirUpload=true`, function (res) {
                if (res.success) {
                    refreshPermis().then(() => {
                        refreshDirectoryNode(tempNode, basicData);
                        metaListTable.reloadTable();
                    })
                }
            });
        })

        function upload(basicData, url, callback) {
            if (basicData.id === 'ROOT' && !USER_ROLES.includes('ROLE_SA')) {
                layer.msg('没有权限');
                return;
            }
            if (basicData.reviewStatus == ReviewStatus.PASS || basicData.reviewStatus == ReviewStatus.SUBMITTED) {
                addDataConfirm(open);
            } else {
                open();
            }

            function open() {
                let height = $(document).height();
                height = height < 1000 ? height : height * 0.8;
                layer.open({
                    id: 'fileUploadLayer',
                    title: '上传文件',
                    type: 2,
                    area: ['900px', height + 'px'],
                    maxmin: true,
                    btn: false,
                    content: url,
                    success: function (layero, index) {
                        fileUploadLayerWin = window[layero.find('iframe')[0]['name']];
                        fileUploadLayerWin.layerOkCallback = callback;
                        fileUploadLayerWin.layerCancelCallback = function () {
                            layer.close(index);
                            metaListTable.reloadTable()
                        };
                    },
                });
            }
        }

        // 查看按钮监听
        metaListTable.addTableRowEvent('details', function (obj) {
            if (obj.resourceType === 'file') {
                openMaxLayerWithURL(`${ctx}/sys/file/view?fileId=${obj.id}`)
            } else {
                openMaxLayerWithURL(`${ctx}/business/metadata/details/${obj.id}`)
            }
        })

        metaListTable.addTableRowEvent('modify', function (obj) {
            if (obj.resourceType === 'file') {
                openEditLayer(`${ctx}/sys/file/edit?id=${obj.id}`);
            } else {
                openEditLayer(`${ctx}/business/metadata/edit?id=${obj.id}`)
            }
        })

        // 下载
        metaListTable.addTableRowEvent('downFile', function (obj) {
            if (obj.resourceType === 'file') {
                layer.open({
                    title: '文件下载',
                    type: 0,
                    content: `<p>是否需要同时下载置标标签数据？</p>`,
                    btn: ['需要', '不需要'],
                    yes: function (index) {
                        layer.close(index)
                        window.open(`${ctx}/sys/file/download/${obj.id}`)
                        window.open(`${ctx}/sys/file/download/label/${obj.id}`)
                    },
                    btn2: function (index) {
                        layer.close(index);
                        window.open(`${ctx}/sys/file/download/${obj.id}`)
                    },

                });
            } else {
                showErrorMsg('数据表不支持下载');
            }
        })
    }

    let editLayerWin;

    function openEditLayer(url) {
        layer.open({
            id: 'editLayer',
            type: 2,
            title: '编辑窗口',
            offset: [50, window.innerWidth / 2 - 850 / 2],
            area: ['890px', '650px'],
            content: url,
            btn: ['保存', '取消'],
            success: function (layero, index) {
                editLayerWin = window[layero.find('iframe')[0]['name']];
                layer.iframeAuto(index)
            },
            yes: function (index) {
                editLayerWin && editLayerWin.save().then(ok => {
                    if (ok) {
                        layer.close(index);
                        metaListTable.reloadTable();
                    }
                });
            },
        })
    }


    // 加载并渲染目录树
    let currentNode, currentParentNode, tempOwner, tempOwnerType;
    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) {
            $('#directoryTree cite span').on('click', function (event) {
                event.stopPropagation();
                const target = event.target;
                const id = $(target).data('id');
                const status = $(target).data('status')
                if (status === ReviewStatus.FAIL || status === ReviewStatus.REJECTED) {
                    showLoading()
                    $.get(`${ctx}/business/review/get/entity?entityId=${id}`, {}, function (res) {
                        closeLoading()
                        if (res.flag) {
                            const reviewData = res.data;
                            const content = `
                                    <div class="tips-box">
                                        <div style="height: 32px;line-height: 32px;color: #dbdbdb;">审核人：${reviewData.reviewUser}</div>
                                        <div style="min-width: 200px;max-width: 500px;min-height: 30px;max-height: 300px; color: gray">原因：${reviewData.reviewOpinion}</div>
                                    </div>`;
                            layer.tips(content, `#${id}`, {
                                tips: [2],
                                closeBtn: 1,
                                shade: 0.3,
                                shadeClose: true,
                                time: 60000
                            });
                        } else {
                            showErrorMsg(res.msg);
                        }
                    })
                }
            })
            // 模拟鼠标点击事件展开第一层目录
            elem.find('li:first>div:first>i:first').click();
            elem.find('li:first>div:first').click();
        },
        onClick: function (node) {
            tempNode = node;
            currentNode = getCurrentNode();
            currentParentNode = getCurrentParentNode();
            const {basicData} = node.param;
            setLocation(basicData.directoryPath)
            loadMetadataList(node.param)
        },
        toolbarFun: {
            // 显示右键菜单之前的回调，用于设置显示哪些菜单
            loadToolbarBefore: function (buttons, param, $div) {
                const {basicData} = param;
                // 根据数据审核状态判断是否显示相关功能按钮
                if (basicData && basicData.id !== DIR_ROOT_ID && basicData.id !== DIR_THEME_ROOT_ID) {
                    let user = sessionStorage.getItem('login_user');
                    if (user && typeof user !== 'object') {
                        user = JSON.parse(user);
                    }
                    if (user.userId !== 'admin' && user.userId !== 'sa') {
                        switch (basicData.reviewStatus) {
                            case ReviewStatus.SUBMITTED:
                            case ReviewStatus.PASS:
                                setDisabledButtons(['toolbar_dir_submit', 'toolbar_dir_delete']);
                                if (!(user.userId === basicData.ownerId || (user.orgId === basicData.ownerId && user.orgLeader))) {
                                    setDisabledButtons(['toolbar_dir_rename'])
                                }
                                break;
                            case ReviewStatus.UN_SUBMIT:
                            case ReviewStatus.FAIL:
                                setDisabledButtons();
                                break
                            case ReviewStatus.REJECTED:
                                setDisabledButtons([]);
                        }

                        // 根据数据操作权限判断是否显示相关按钮
                        if (!WritePermisDirIds.includes(basicData.id)) {
                            setDisabledButtons(['toolbar_dir_rename', 'toolbar_dir_delete', 'toolbar_dir_move', 'toolbar_dir_link', 'toolbar_dir_submit', 'toolbar_dir_mark', 'toolbar_dir_copy', 'toolbar_dir_fenxi']);
                            if (user.orgId !== basicData.ownerId) {
                                // 如果当前用户所在部门 不是 选中目录所属部门ID，则禁用新建按钮
                                setDisabledButtons(['toolbar_dir_add'])
                            }
                        } else if (!isDirectoryOwner(basicData)) {
                            setDisabledButtons(['toolbar_dir_delete']);
                        }

                        if (basicData.directoryType.startsWith('LINK_')) {
                            setDisabledButtons(['toolbar_dir_add', 'toolbar_dir_link', 'toolbar_dir_mark', 'toolbar_dir_copy'])
                        }
                    } else {
                        setDisabledButtons([]);
                    }
                } else {
                    setDisabledButtons(['toolbar_dir_rename', 'toolbar_dir_delete', 'toolbar_dir_move', 'toolbar_dir_link', 'toolbar_dir_submit', 'toolbar_dir_mark', 'toolbar_dir_copy', 'toolbar_dir_fenxi']);
                }

                // 判断是否需要分析挖掘
                /*if (!(basicData.directoryPath.startsWith('/数据资源目录/三区演习数据/')
                    && basicData.directoryType === 'DIRECTORY'
                    && basicData.directoryName === 'Formatted Data' || basicData.directoryName.startsWith('B'))) {
                    setDisabledButtons(['toolbar_dir_fenxi'])
                }*/

                /**
                 * 设置需要禁用的按钮
                 * @param buttonIds 按钮ID数组
                 */
                function setDisabledButtons(buttonIds = []) {
                    for (let btnName of buttonIds) {
                        let $btn = $(buttons[btnName]);
                        let $a = $btn.find('a').addClass('layui-disabled');
                        $btn.html($a[0]);
                        buttons[btnName] = $btn[0];
                    }
                }

                return buttons;
            }
        },
        toolbarExt: [
            {
                toolbarId: "toolbar_dir_add",
                icon: "dtreefont dtree-icon-weibiaoti5",
                title: "新建目录",
                handler: function (node, elem) {
                    const {id, basicData} = node;
                    openDirectoryEditLayer({parentId: id}, function (data) {
                        if (id === DIR_ROOT_ID) {
                            dirTree.partialRefreshAdd(elem);
                        } else {
                            setTimeout(function () {
                                let $newDom = $(`#directoryTree div.dtree-nav-div.dtree-theme-item[data-id="${basicData.id}"]`)
                                dirTree.partialRefreshAdd($newDom);
                            }, 50)
                        }
                    });
                }
            },
            {
                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_move",
                icon: "layui-icon layui-icon-link",
                title: "移动目录",
                handler: function (node, elem) {
                    const {basicData, id, parentId, context} = node;
                    openDirectorySelectLayer('move', (node) => {
                        if (node.id === id) {
                            showErrorMsg('不能选择自己');
                            return false;
                        }
                        if (node.basicData.directoryPath.startsWith(basicData.directoryPath + '/')) {
                            showErrorMsg('不能选择子级目录');
                            return false;
                        }
                        return true;
                    }).then(nodes => {
                        const targetId = nodes[0].id;
                        moveResource(id, targetId).then(res => refreshPermis().then(() => {
                            dirTree.partialRefreshAdd($(`div[data-id="${parentId}"]`));
                            dirTree.partialRefreshAdd($(`div[data-id="${targetId}"]`));
                            metaListTable.reloadTable();
                        }));
                    });
                }
            },
            {
                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();
                    })
                }
            },
            {
                toolbarId: "toolbar_dir_link",
                icon: "layui-icon layui-icon-link",
                title: "关联数据库表",
                handler: function (node, elem) {
                    const {basicData, id, parentId, context} = node;
                    openAddMetadataLayer(basicData, function () {
                        //dirTree.partialRefreshAdd(elem);
                        metaListTable.reloadTable();
                    })
                }
            },
            {
                toolbarId: "toolbar_dir_copy",
                icon: "layui-icon layui-icon-link",
                title: "关联目录或文件",
                handler: function (node, elem) {
                    const {basicData, id, parentId, context} = node;
                    openDirectorySelectLayer('link', (node)=>{
                        if(node.id === id){
                            showErrorMsg('不能选择自己');
                            return false;
                        }
                        if(node.id === parentId){
                            showErrorMsg('已经存在于该目录')
                            return false;
                        }
                        if(node.basicData.directoryPath.startsWith(basicData.directoryPath)){
                            showErrorMsg('不能选择子级目录')
                            return false;
                        }
                        return true;
                    }).then(nodes=>{
                        const chooseNode = nodes[0];
                        linkResource(chooseNode.id, id).then(res=>{
                            refreshPermis().then(() => {
                                dirTree.partialRefreshAdd($(`div[data-id="${id}"]`));
                                metaListTable.reloadTable();
                            });
                        });
                })
                }
            },
            /*{
                toolbarId: "toolbar_dir_mark",
                icon: "layui-icon layui-icon-note",
                title: "数据置标",
                handler: function (node, elem) {
                    const {basicData} = node;
                    openDirMarkLayer(basicData);
                }
            },*/
            {
                toolbarId: "toolbar_dir_submit",
                icon: "layui-icon layui-icon-release",
                title: "提交", handler: function (node, elem) {
                    let param = {
                        id: node.id,
                        status: ReviewStatus.SUBMITTED,
                        opinion: '',
                        sendNotice: false,
                    };
                    $.post(`${ctx}/business/review/directory/change`, param, function (res) {
                        if (res.flag) {
                            layer.msg('提交成功');
                            let temp = Object.assign({}, node)
                            temp.basicData.reviewStatus = ReviewStatus.SUBMITTED;
                            temp.title = temp.context;
                            temp.title = formatterTitle(temp);
                            dirTree.partialRefreshEdit(elem, temp)
                            dirTree.getChild(elem);
                            loadMetadataList(node)
                        } else {
                            layer.msg('提交失败,' + res.msg);
                        }
                    });
                }
            },
            {
                toolbarId: 'toolbar_dir_fenxi',
                title: '分析挖掘',
                handler: function (node, elem) {
                    const {basicData} = node;
                    erbu_fenxiwajue(basicData);
                }
            },
            {
                toolbarId: 'toolbar_dir_view',
                title: '查看属性',
                handler: function (node, elem) {
                    const {basicData} = node;
                    openDirectoryEditLayer(basicData, function (data) {
                    }, true);
                }
            }
        ],
        formatter: {
            title: function (data) { // 文字过滤，返回null,"",undefined之后，都不会改变原有的内容返回。
                return formatterTitle(data);
            }
        }
    }
    dirTree = globalTree.init(treeOps);

    /**
     * 获取当前节点
     * @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();
        }
    }


    /**
     * 刷新目录节点
     */
    function refreshDirectoryNode({dom, param, parentParam, childrenParam}, data) {
        dirTree.partialRefreshEdit(dom, generateDirectoryNode(data));
        dirTree.getChild(dom);
        dom.click();
    }

    function openDirectorySelectLayer(operateType, disabledIds) {
        let chooseBeforeHandler, selectNodes = [];
        if (disabledIds instanceof Function) {
            chooseBeforeHandler = disabledIds;
            disabledIds = undefined;
        }

        return new Promise(((resolve, reject) => {
            let directorySelectTree;
            layer.open({
                type: 1,
                title: '请选择目录',
                area: ['700px'],
                btn: ['保存', '取消'],
                content: `<div style="width: 100%; height: 700px; border-bottom: 1px solid #eee;" id="moveFileTreeBox"><ul id="moveFileTree"></ul></div>`,
                success: function (layerObj, index) {
                    directorySelectTree = globalTree.init({
                        id: 'moveFileTree',
                        //url: `${treeChildrenUrl}&all=${operateType !== 'move'}`.replace('busType=0', 'busType=2'),
                        url: `${treeChildrenUrl}&all=${operateType !== 'move'}`,
                        cache: true,
                        scroll: '#moveFileTreeBox',
                        width: '100%',
                        checkbar: true,
                        checkbarType: 'only',
                        checkbarFun: {
                            chooseBefore: function ($i, node) {
                                const chooseDir = node.basicData;
                                if (node.id === DIR_ROOT_ID && (operateType === 'link')) {
                                    showErrorMsg('不能选择根节点！')
                                    return false;
                                }
                                if (chooseBeforeHandler) {
                                    return chooseBeforeHandler(node);
                                }
                                // 选中前的回调
                                return true;
                            },
                            chooseDone: function (nodes) {
                                // 选中后的回调
                                selectNodes = nodes || [];
                            }
                        },
                        done: res => {

                        }
                    });
                },
                yes: function (index) {
                    layer.close(index);
                    resolve(selectNodes);
                },
                cancel: function (index) {
                    layer.close(index);
                }
            })
        }))
    }

    function erbu_fenxiwajue(data) {
        layer.open({
            id: 'fenxiwajue',
            title: '选择演习结果',
            btn: false,
            content: `
                    <div class="layui-form" lay-filter="fenxi-result-form">
                        <div class="layui-form-item">
                            <input type="radio" name="result" value="1" title="成功">
                            <input type="radio" name="result" value="0" title="失败">
                        </div>
                        <div class="layui-form-item" style="display: flex; justify-content: center;">
                            <button type="button" class="layui-btn layui-btn-sm layui-btn-warm" id="startFenxi">确定</button>
                        </div>
                        <div>解析分析数据需消耗较长时间，请勿关闭页面</div>
                    </div>`,
            success: function () {
                form.render();
                $('#startFenxi').on('click', function () {
                    let formVal = form.val('fenxi-result-form');
                    if (!formVal.result) {
                        showErrorMsg('请选择')
                        return;
                    }
                    let url = `${ctx}/erbu/fenxi/${data.id}?result=${formVal.result}`
                    $.ajax({
                        url,
                        type: 'get',
                        dataType: 'json',
                        timeout: 0,
                        beforeSend: () => {
                            showLoading(layer)
                        },
                        success: (res) => {
                            if (res.flag) {
                                showOkMsg(res.data.includes("请稍后重试") ? "请稍后重试" : res.data, {time: 3000});
                            } else {
                                showErrorMsg(res.msg, {time: 4000});
                            }
                        },
                        error: (err) => {
                            showErrorMsg(err.message, {time: 3000});
                            console.error(err);
                        },
                        complete: () => {
                            closeLoading(layer)
                        }
                    })

                    // Util.get(`/erbu/fenxi/${data.id}?result=${formVal.result}`).then(res=>{
                    //     if(res.flag){
                    //         showOkMsg(res.data);
                    //     }else{
                    //         showErrorMsg(res.msg);
                    //     }
                    // }).catch(err=>{
                    //     showErrorMsg(err.message);
                    //     console.error(err);
                    // })
                })
            }
        })
    }

    element.on('tab(directoryTreeBody)', function (data) {
        if (data.index === 1) {
            initViewDirectoryTree();
            loadMetadataList({basicData: {id: 0}})
        }
    });

    function initViewDirectoryTree() {
        let viewDirTree = globalTree.init({
            id: 'viewDirectoryTree',
            url: `${ctx}/data-label/manager/api/view/tree/children`,
            cache: true,
            //type: 'all',
            initLevel: 1, // 默认展开一级
            scroll: '#viewDirectoryTree',
            width: 'fit-content',
            checkbar: true,
            checkbarType: 'self',
            checkbarFun: {
                // 此处勾选事件应为勾选任意节点后，在展开子节点后，子节点应为勾选状态，
                // 子节点全部勾选后父节点勾选
                // 子节点有一个不勾选，父节点取消勾选
                chooseDone: function (nodes = []) {
                    viewDirTree.chooseIds = nodes.map(node => node.basicData.id).join(',')
                    metaListTable.table.where.ids = viewDirTree.chooseIds;
                    metaListTable.reloadTable();
                }
            },
            done: function (res) {
            },
            onClick: function (node) {
                const nodeParam = node.param, {basicData} = nodeParam;

                if (metaListTable) {
                    metaListTable.table.where.id = basicData.id;
                    if (viewDirTree.chooseIds) {
                        viewDirTree.activeId = '';
                        //viewDirTree.cancelNavThis();
                        //basicData.titlePathWithSelf = '/';
                        //metaListTable.table.where.ids = '';
                    } else {
                        metaListTable.reloadTable()
                    }
                } else {
                    loadMetadataList(nodeParam)
                }
                console.info('metaListTable.table.where', metaListTable.table.where);

                setLocation(basicData.titlePathWithSelf)
                viewDirTree.activeId = basicData.id;
            }
        });
    }

    initViewDirectoryTree();
}

/**
 * 关联资源
 * @param sourceId 源资源ID
 * @param targetId 目标资源ID
 */
function linkResource(sourceId, targetId) {
    const params = {targetId, sourceId};
    return new Promise((resolve, rejects) => {
        Util.post('/business/directory/link', params).then(res => {
            if (res.flag) {
                showOkMsg('保存成功');
                resolve(res);
            } else {
                showErrorMsg();
                rejects();
            }
        }).catch(rejects);
    })
}

/**
 * 移动资源
 * @param sourceIds 源资源id集合
 * @param targetId 目标id
 */
function moveResource(sourceIds, targetId) {
    const params = {targetId, sourceIds};
    return new Promise((resolve, rejects) => {
        Util.post('/business/directory/move', params).then(res => {
            if (res.flag) {
                showOkMsg('保存成功');
                resolve(res);
            } else {
                showErrorMsg();
                rejects();
            }
        }).catch(rejects);
    })
}