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

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

    /**
     * 加载数据资源列表
     */
    const loadMetadataList = function (directory) {
        const {basicData} = directory;
        if (!basicData) return;
        let dirId = basicData.id, uploadPermis = true, viewPermis = true, removePermis = true,
            permis = {uploadPermis, viewPermis, removePermis};
        if (!WritePermisDirIds.includes(basicData.id) || dirId === '-') {
            permis.uploadPermis = false;
            permis.removePermis = false;
        }
        if (!ReadPermisDirIds.includes(basicData.id)) {
            permis.viewPermis = false;
        }
        metaListTable = listPage.init({
            table: {
                permis: permis,
                id: 'dirMetadataTable',
                toolbar: '#tableToolBar',
                searchFieldNames: 'formComment',
                url: `${ctx}/directory/form/page?dirId=${dirId}`,
                where: {dirId},
                height: 'full-110',
                //method: 'get',
                text: {none: 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: [[
                    {field: 'id', title: 'ID', hide: true},
                    {field: 'formName', title: '唯一标识', width: 260},
                    {field: 'formComment', title: '表单名称'},
                    {field: 'createUserName', title: '操作用户'},
                    {field: 'createTime', title: '关联时间'},

                    {
                        fixed: 'right',
                        title: '操作',
                        toolbar: `#rowToolBar`,
                        width: 160,
                        align: 'center'
                    }
                ]],
            },
        });
        metaListTable.addTableRowEvent('addLink', function (obj) {
            openAddMetadataLayer(directory.basicData, () => {
                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(`/directory/form/delete/${obj.id}`, {}, 'delete').then(res => {
                    if (res.flag) {
                        showOkMsg('删除成功')
                        metaListTable.reloadTable();
                    } else {
                        showErrorMsg(res.msg);
                    }
                }).catch(() => showErrorMsg());
            }
        })

        // 查看按钮监听
        metaListTable.addTableRowEvent('details', function (obj) {
            openMaxLayerWithURL(`${ctx}/dynamic-data/view/data/list/${obj.formId}?preview=1`)
        })
    }


    // 加载并渲染目录树
    let currentNode, currentParentNode;
    let treeChildrenUrl = `${ctx}/business/directory/tree?busType=${bus_type}`;
    const 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_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();
                })
            }
        }
    ];
    const toolbarFun = {
        // 显示右键菜单之前的回调，用于设置显示哪些菜单
        loadToolbarBefore: function (buttons, param, $div) {
            const {basicData} = param;
            // 根据数据审核状态判断是否显示相关功能按钮
            if (basicData && basicData.id !== DIR_ROOT_ID && basicData.id !== DIR_THEME_ROOT_ID && basicData.id !== DIR_BASIC_ROOT_ID) {
                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_link', 'toolbar_dir_submit', 'toolbar_dir_mark', 'toolbar_dir_copy']);
                    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(['toolbar_dir_rename', 'toolbar_dir_delete', 'toolbar_dir_link', 'toolbar_dir_submit', 'toolbar_dir_mark', 'toolbar_dir_copy']);
            }

            /**
             * 设置需要禁用的按钮
             * @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;
        }
    };
    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) {
            tempNode = node;
            currentNode = getCurrentNode();
            currentParentNode = getCurrentParentNode();
            const {basicData} = node.param;
            setLocation(basicData.directoryPath)
            loadMetadataList(node.param)
        },
        toolbarFun: !browser && toolbarFun,
        toolbarExt: !browser && toolbarExt,
    }
    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 openAddMetadataLayer(directory, callback) {
        let left = window.innerWidth / 2 - 500;
        let top = window.innerHeight / 2 - 360;
        let formTable, chooseData = [];
        layer.open({
            id: 'addMetadataLayer',
            type: 1,
            offset: [top + 'px', left + 'px'],
            btn: ['确定', '取消'],
            content: `<!-- html 模板-->
                <div class="layui-row member layui-col-space15">
                    <div class="layui-col-md12">
                    <div id="form-list-table" lay-filter="form-list-table"></div>
                    <script type="text/html" id="table-head-toolbar">
                        <div class="layui-btn-container">
                            <div class="layui-layout-left" style="top:10px; left: 20px; width: 400px">
                                <input type="text" id="searchKeyInput2" name="searchKeyInput2"
                                       autocomplete="off"
                                       placeholder="请输入表单名称" class="layui-input layui-btn-sm" style="width: 260px">
                                <button class="layui-btn layui-btn-sm" lay-event="query">查询</button>
                            </div>
                        </div>
                    </script>
                    </div>
                </div>`,
            success: function (layero) {
                formTable = layui.listPage.init({
                    table: {
                        id: 'form-list-table',
                        searchFieldNames: 'searchText',
                        searchInput: 'searchKeyInput2',
                        url: `${ctx}/dynamic-form/api/form/list`,
                        where: {},
                        method: 'get',
                        height: '562',
                        toolbar: '#table-head-toolbar',
                        cols: [[
                            {type: 'checkbox'},
                            {field: 'id', title: 'ID', width: 80},
                            {field: 'formId', title: '唯一标识', width: 260},
                            {field: 'formName', title: '表单名称'},
                        ]],
                        onChecked: function () {
                            chooseData = formTable.getCheckStatus().data;
                        }
                    }
                });
            },
            yes: function (index) {
                let ids = chooseData.map(item => item.id);
                let params = {
                    dirId: directory.id,
                    formIds: ids.join(',')
                }
                Util.post(`/directory/form/add`, params).then(res => {
                    if (res.flag) {
                        showOkMsg('保存成功');
                        layer.close(index);
                        callback && callback();
                    } else {
                        showErrorMsg(res.msg);
                    }
                })
            }
        });
    }
}
