let layer, orgTree, gtable, globalTree, tag, listPage, form, element;
layui.use(['layer', 'orgTree', 'gtable', 'globalTree', 'tag', 'listPage', 'form', 'element', 'dict'], function () {
    layer = layui.layer;
    orgTree = layui.orgTree;
    gtable = layui.gtable;
    globalTree = layui.globalTree;
    listPage = layui.listPage;
    form = layui.form;
    tag = layui.tag;
    element = layui.element;
    startRender && startRender();
})

/**
 * 打开目录编辑窗口
 * @param data
 */
function openDirectoryEditLayer(data, callback, view) {
    const isEdit = !!data.id;
    data.id = data.id || Util.uuid();
    let disablePermisBtn = !isEdit || isDirectoryOwner(data) ? '' : 'disabled';
    let readOnly = data.reviewStatus === 'SUBMITTED' || data.reviewStatus === 'PASS' ? 'readOnly' : '';
    if (view) {
        disablePermisBtn = 'disabled';
        readOnly = 'readOnly';
    }
    data.sort = data.sort || 9999;
    console.info(data);
    layer.open({
        type: 1,
        title: view ? '目录属性' : isEdit ? '修改目录' : '新建目录',
        btn: ['保存', '取消'],
        content: `<div class="layui-form" lay-filter="directoryEditForm" style="width: 500px; border-bottom: 1px solid #f2f2f2;">
                        <div class="layui-form-item" style="margin-bottom: 0">
                            <div class="layui-inline" style="width: calc(100% - 30px); margin:15px 15px 0 15px">
                                <input type="hidden" name="id" value="${data.id || ''}">
                                <input type="hidden" name="parentId" value="${data.parentId}" />
                                <input type="hidden" name="directoryType" value="DIRECTORY" />
                                <input type="hidden" name="basicDir" value="${data.basicDir || bus_type}" />
                                <input type="hidden" name="createTime" value="${data.createTime || ''}" />
                                <label style="color: #555;"><label style="color: red">*</label>目录名称：</label>
                                <input class="layui-input" type="text" name="directoryName" autocomplete="off" value="${data.directoryName || ''}" ${readOnly} placeholder="请输入目录名称" lay-verify="required" style="margin-top: 5px; width: 380px;">
                            </div>
                            <div class="layui-inline" style="width: calc(100% - 30px); margin:15px 15px 0 15px;display: flex;align-items: center;">
                                <label style="color: #555;"><label style="color: red">*</label>数据密级：</label>
                                <div dict-component="radio" dict-type="secret_level" dict-name="secretLevel"
                                     id="dict-secret-level"></div>
                            </div>
                            <div class="layui-inline" style="width: calc(100% - 30px); margin:15px 15px 0 15px">
                                <label style="color: #555">目录归属${data.ownerType === 'org' ? '单位' : '用户'}：</label><span style="color: #000" id="ownerNameSpan">${data.owner || user.userName}</span>
                                <button class="layui-btn layui-btn-primary layui-btn-xs ${disablePermisBtn ? 'layui-disabled' : ''}" id="ownerChooseBtn" ${disablePermisBtn} style="border:0; color: #009688">变更</button>
                                <input type="hidden" name="ownerType" value="${data.ownerType || 'user'}" />
                                <input type="hidden" name="ownerId" value="${data.ownerId || user.userId}" />
                                <input type="hidden" name="owner" value="${data.owner || user.userName}" />
                            </div>
                            <div class="layui-inline" style="width: calc(100% - 30px); margin:15px 15px 0 15px">
                                <div class="permis-setting-area">
                                    <label style="color: #555; width: 470px;">目录权限（含上传的数据）：<i class="permis-tips layui-icon layui-icon-tips" title="权限说明" style="color: orange;float: right; cursor: pointer"></i></label><br />
                                    <div class="permis-item">
                                        <label>归属者</label>
                                        <div class="line"></div>
                                        <div class="permis-ops">
                                            <input type="checkbox" name="_permisOwner" lay-skin="primary" value="read" title="查看" checked disabled>
                                            <input type="checkbox" name="_permisOwner" lay-skin="primary" value="write" title="修改" checked disabled>
                                        </div>
                                    </div>
                                    <div class="permis-item">
                                        <label>所有人</label>
                                        <div class="line"></div>
                                        <div class="permis-ops">
                                            <input type="hidden" name="permisEveryone" value="unset">
                                            <input type="checkbox" name="_permisEveryone" lay-skin="primary" value="read" title="查看" lay-filter="p-checkbox" ${disablePermisBtn}>
                                            <input type="checkbox" name="_permisEveryone" lay-skin="primary" value="write" title="修改" lay-filter="p-checkbox" ${disablePermisBtn}>
                                        </div>
                                    </div>
                                    <div class="permis-item">
                                        <label>所有上级</label>
                                        <div class="line"></div>
                                        <div class="permis-ops">
                                            <input type="hidden" name="permisAllParent" value="unset">
                                            <input type="checkbox" name="_permisAllParent" lay-skin="primary" value="read" title="查看" lay-filter="p-checkbox" ${disablePermisBtn}>
                                            <input type="checkbox" name="_permisAllParent" lay-skin="primary" value="write" title="修改" lay-filter="p-checkbox" ${disablePermisBtn}>
                                        </div>
                                    </div>
                                    <div class="permis-item">
                                        <label>直属上级</label>
                                        <div class="line"></div>
                                        <div class="permis-ops">
                                            <input type="hidden" name="permisParent" value="unset">
                                            <input type="checkbox" name="_permisParent" lay-skin="primary" value="read" title="查看" lay-filter="p-checkbox" ${disablePermisBtn}>
                                            <input type="checkbox" name="_permisParent" lay-skin="primary" value="write" title="修改" lay-filter="p-checkbox" ${disablePermisBtn}>
                                        </div>
                                    </div>
                                    <div class="permis-item">
                                        <label>所有下级</label>
                                        <div class="line"></div>
                                        <div class="permis-ops">
                                            <input type="hidden" name="permisAllChild" value="unset">
                                            <input type="checkbox" name="_permisAllChild" lay-skin="primary" value="read" title="查看" lay-filter="p-checkbox" ${disablePermisBtn}>
                                            <input type="checkbox" name="_permisAllChild" lay-skin="primary" value="write" title="修改" lay-filter="p-checkbox" ${disablePermisBtn}>
                                        </div>
                                    </div>
                                    <div class="permis-item">
                                        <label>直属下级</label>
                                        <div class="line"></div>
                                        <div class="permis-ops">
                                            <input type="hidden" name="permisChild" value="unset">
                                            <input type="checkbox" name="_permisChild" lay-skin="primary" value="read" title="查看" lay-filter="p-checkbox" ${disablePermisBtn}>
                                            <input type="checkbox" name="_permisChild" lay-skin="primary" value="write" title="修改" lay-filter="p-checkbox" ${disablePermisBtn}>
                                        </div>
                                    </div>
                                    <div class="permis-item">
                                        <input class="apply-child" type="checkbox" name="applyChild" value="true" title="对下级所有部门应用此权限设置" lay-skin="primary" lay-filter="applyCheckbox" ${disablePermisBtn}>
                                        <button class="layui-btn layui-btn-primary ${disablePermisBtn ? 'layui-disabled' : ''}" id="memberManageBtn" style="border:0; color: #009688; " ${disablePermisBtn}>管理额外的成员权限</button>
                                    </div>
                                    <div class="permis-item ${disablePermisBtn && !view ? '' : 'layui-hide'}">
                                        <label style="color: #ffa584">* 如需修改本目录权限，请联系目录归属人</label>
                                    </div>
                                </div>                              
                                <a lay-submit lay-filter="directoryEditForm" id="directoryEditFormSubmit" style=""></a>
                            </div>
                            <div class="layui-inline" style="width: calc(63% - 30px); margin:15px 15px 0 15px">
                                    <label style="color: #555">目录创建人：</label><span style="color: #000" >${data.createUserName || user.userName}</span>
                                    <input type="hidden" name="createUserName" value="${data.createUserName || user.userName}" />
                                    <input type="hidden" name="createUser" value="${data.createUser || user.userId}" />
                            </div>
                            <div class="layui-inline" style="width: calc(37% - 40px); margin:15px 15px 0 15px">
                                    <label style="color: #555">目录顺序：</label>
                                    <input class="layui-input" type="text" name="sort" value="${data.sort}" style="width: 60px"/>
                            </div>
                        </div>
                    </div>`,
        success: function () {
            form.render();
            form.val('directoryEditForm', data);
            layui.dropdown.render({
                elem: '#ownerChooseBtn',
                data: [
                    {title: '选择用户', id: 'selectUser'},
                    {title: '选择部门', id: 'selectOrg'}
                ],
                style: 'border: 1px solid #d3d3d3;',
                click: dirOwnerChangeCallback
            });
            layui.dict.render();
            if (!data || !data.secretLevel) {
                data['secretLevel'] = 0;
            }
            layui.dict.setData('dict-secret-level', data)
            $('div.dict-component').css({'margin-top': '5px', 'width': '380px', 'margin-left': '4px'})
            if (view) {
                layui.dict.setReadonly();
            }
            // 目录成员管理事件
            $('#memberManageBtn').on('click', () => {
                let formVal = form.val('directoryEditForm');
                if (!formVal.createTime) {
                    layer.confirm('是否先保存当前数据？', (index) => {
                        saveDirectory(null, (rData) => {
                            data = rData;
                            openMembersManageLayer(data)
                        })
                    });
                } else {
                    openMembersManageLayer(data)
                }
            });
            // 权限说明查看事件
            $('i.permis-tips').on('click', showPermisRemarkLayer)
            permisItemEventBind(data)
            // 同步应用到下级部门复选框事件
            applyChildCheckbox(isEdit);
        },
        yes: function (index) {
            if (view) {
                return;
            }
            saveDirectory(index, callback);
        }
    })
}

function saveDirectory(index, callback) {
    form.on('submit(directoryEditForm)', function ({elem, field}) {
        if (field.secretLevel > user.secretLevel) {
            layer.alert('禁止上传超过自身涉密等级的文件，您的涉密等级为【' + DICT.getText('secret_level', user.secretLevel) + '】', {icon: 2})
            return;
        }

        if (isNaN(parseInt(field.sort))) {
            layer.alert('目录顺序只能为数字');
            return;
        }

        // 转换数据类型
        field.basicDir = field.basicDir === '1';
        // 如果是基础数据目录，则自动为提交状态
        if (field.basicDir) {
            field.reviewStatus = ReviewStatus.SUBMITTED
        }
        Util.post(`/business/directory/save`, field, true).then(res => {
            if (res.flag) {
                ReadPermisDirIds.push(res.data.id);
                WritePermisDirIds.push(res.data.id);
                let data = Object.assign({}, generateDirectoryNode(res.data), field);
                form.val('directoryEditForm', res.data)
                index && layer.close(index);
                callback && callback(data);
            } else {
                showErrorMsg(res.msg);
            }
        });
        return false;
    });
    $('#directoryEditFormSubmit').click();
}

function permisItemEventBind(data) {
    if (data) {
        setData(data.permisEveryone, 'permisEveryone');
        setData(data.permisAllParent, 'permisAllParent');
        setData(data.permisParent, 'permisParent');
        setData(data.permisAllChild, 'permisAllChild');
        setData(data.permisChild, 'permisChild');
        form.render('checkbox')
    }

    form.on('checkbox(p-checkbox)', function ({elem, value}) {
        let elemName = $(elem).attr('name');
        let values = [], formName = elemName.substring(1);
        $(`input[name="${elemName}"]:checked`).each((index, e) => values.push($(e).val()))
        $(`input[name="${formName}"]`).val(values.join(',') || 'unset');
    });

    function setData(value, key) {
        if (value && value !== 'unset') {
            for (let permis of value.split(',')) {
                $(`input[name="_${key}"][value="${permis}"]`).attr('checked', true);
            }
        }
    }
}

/**
 * 目录归属者变更下拉菜单事件回调
 * @param obj
 */
function dirOwnerChangeCallback(obj) {
    if (obj.id == 'selectUser') {
        openUserSelectLayer(true).then(user => {
            setOwner({
                ownerType: 'user',
                ownerId: user[0].userId,
                ownerName: user[0].userName
            });
            $('#ownerNameSpan').text(user[0].userName);
        })
    } else if (obj.id == 'selectOrg') {
        openOrgSelectLayer('only').then(orgs => {
            setOwner({
                ownerType: 'org',
                ownerId: orgs[0].id,
                ownerName: orgs[0].context
            });
            $('#ownerNameSpan').text(orgs[0].context);
        })
    }

    function setOwner(owner) {
        $('[name=ownerType]').val(owner.ownerType);
        $('[name=ownerId]').val(owner.ownerId);
        $('[name=owner]').val(owner.ownerName);
        form.render();
    }
}

/**
 * 应用到下级目录复选框功能实现
 */
function applyChildCheckbox(isEdit) {
    if (!isEdit) return;
    $('input[class="apply-child"]').next().css('margin-top', '0');
    form.on('checkbox(applyCheckbox)', function (data) {
        if (data.elem.checked) {
            layer.alert('请注意！该操作将覆盖所有下级目录关于该项的设置', {title: '警告', icon: 0});
        }
    });
}

$('#directoryTreeSearchBox').on('keyup', function () {
    setTimeout(() => {
        dirTree.fuzzySearch(this.value);
    }, 500)
})

/**
 * 设置当前位置
 * @param path
 */
function setLocation(path) {
    if (path) {
        try {
            $('#currentPosition').text(path.replaceAll('/', ' / '));
        } catch (e) {
            console.error(e);
        }
    }
}

/**
 * 打开用户选择窗口
 * @returns {Promise<unknown>}
 */
function openUserSelectLayer(radio = false, ids = []) {
    return new Promise((resolve) => {
        layer.open({
            type: 2,
            title: '选择用户',
            area: ['1000px', '750px'],
            btn: ['确定', '取消'],
            content: `${ctx}/sys/sysUser/select/layer?all=true&radio=${radio}&initData=${ids.join(',')}`,
            yes: function (index, layerObj) {
                let iframeWin = window[layerObj.find('iframe')[0]['name']];
                let users = iframeWin.getSelectedUser();
                if (users && users.length > 0) {
                    resolve && resolve(users);
                    layer.close(index);
                } else {
                    showErrorMsg('请选择用户');
                }
            },
        });
    })
}

/**
 * 打开部门选择窗口
 * @returns {Promise<unknown>}
 */
function openOrgSelectLayer(checkType = 'p-casc') {
    return new Promise(((resolve, reject) => {
        layer.open({
            type: 1,
            title: '选择部门',
            area: ['450px', '550px'],
            btn: ['确定', '取消'],
            content: `<div id="orgTreeSelector" style="width: 100%; height: 100%; overflow: auto"></div>`,
            success: function (layerObj) {
                orgTree.init({
                    id: 'orgTreeSelector',
                    all: true,
                    checkbar: true,
                    checkbarType: checkType,
                    checkbarFun: {chooseDone: obj => layerObj.org = obj}
                });
            },
            yes: function (index, layerObj) {
                if (layerObj.org) {
                    let orgs = layerObj.org;
                    resolve && resolve(orgs);
                    layer.close(index);
                } else {
                    showErrorMsg('请选择部门');
                }
            },
        });
    }))
}

function deleteDirectory(id) {
    return new Promise((resolve, reject) => {
        layer.confirm('是否确定删除该目录？', function (index) {
            Util.send(`/business/directory/delete/${id}`, {}, 'delete').then(res => {
                if (res.flag) {
                    showOkMsg('删除成功')
                    resolve && resolve(res);
                    layer.close(index);
                } else {
                    showErrorMsg(res.msg);
                    reject && reject()
                }
            }).catch(() => showErrorMsg());
        });
    });
}

function refreshPermis() {
    return new Promise(resolve => {
        setTimeout(function () {
            Util.get('/business/directory/permis', {}).then(res => {
                if (res.flag) {
                    let permis = res.data;
                    ReadPermisDirIds && ReadPermisDirIds.push(...permis.readIds);
                    WritePermisDirIds && WritePermisDirIds.push(...permis.writeIds);
                    resolve && resolve(res.data);
                } else {
                    console.error(res.msg);
                }
            }).catch(err => showErrorMsg('刷新目录权限请求异常'))
        }, 500);
    })
}

/**
 * 权限说明展示框
 */
function showPermisRemarkLayer() {
    layer.open({
        type: 1,
        shade: false,
        title: false,
        content: `<h2 style="padding: 5px">目录权限说明</h2><ul class="layer_notice">
                        <li>一、归属者和所有上级可见</li>
                            <li style="padding-left: 20px">归属者为部门：当前部门所有用户和所有上级部门所有用户可见</li>
                            <li style="padding-left: 20px">归属者为个人：</li>
                             <li style="padding-left: 40px">1、归属者为普通用户：自己和部门管理员以及所有上级部门内的所有用户可见</li>
                             <li style="padding-left: 40px">2、归属者为部门管理员：所有该部门管理员（如有2个或2个以上个部门管理员，虽然为同级，但依旧可见）以及所有上级部门内的所有用户可见</li>
                        <li>二、归属者和直属上级可见</li>
                            <li style="padding-left: 20px">归属者为部门：当前部门所有人和直属上级部门所有人可见</li>
                            <li style="padding-left: 20px">归属者为个人：</li>
                             <li style="padding-left: 40px">1、归属者为普通用户：自己和部门管理员可见</li>
                             <li style="padding-left: 40px">2、归属者为部门管理员：所有该部门管理员（如有2个或2个以上个部门管理员，虽然为同级，但依旧可见）和直属上级部门所有人可见</li>
                        <li>三、仅归属者可见</li>
                            <li style="padding-left: 20px">归属者为部门：仅当前部门所有人可见</li>
                            <li style="padding-left: 20px">归属者为个人：</li>
                             <li style="padding-left: 40px">1、归属者为普通用户：自己可见</li>
                             <li style="padding-left: 40px">2、归属者为部门管理员：自己可见</li>
                        <li>四、归属者和所有下级可见</li>
                            <li style="padding-left: 20px">归属者为部门：当前部门所有用户和所有下级部门的所有用户可见</li>
                            <li style="padding-left: 20px">归属者为个人：</li>
                             <li style="padding-left: 40px">1、归属者为普通用户：自己可见</li>
                             <li style="padding-left: 40px">2、归属者为部门管理员：自己部门所有用户（如有2个或2个以上个部门管理员，虽然为同级，但依旧可见）和所有下级部门的所有用户可见</li>
                        <li>五、归属者和直属下级可见</li>
                            <li style="padding-left: 20px">归属者为部门：当前部门所有人和直属下级部门的所有用户可见</li>
                            <li style="padding-left: 20px">归属者为个人：</li>
                             <li style="padding-left: 40px">1、归属者为普通用户：自己可见</li>
                             <li style="padding-left: 40px">2、归属者为部门管理员：自己部门所有用户（如有2个或2个以上个部门管理员，虽然为同级，但依旧可见）可见</li>
                        <li>六、所有人可见</li>
                            <li style="padding-left: 20px">系统内的所有用户可见</li>
                        </ul>`
    });
}


function formatterTitle(data) {
    let {title, basicData} = data;
    title = basicData.directoryName + '<div class="badge">';
    if (basicData.directoryType.startsWith('LINK_')) {
        title += `<label title="软链接"><i class="layui-icon layui-icon-link"></i></label>`;
    }
    if (basicData && basicData.id !== DIR_ROOT_ID && basicData.id !== DIR_THEME_ROOT_ID) {
        let reviewStatus = data.basicData.reviewStatus;
        title += ReviewStatusIcon[reviewStatus].replaceAll('##id##', basicData.id);
    }
    title += '</div>'
    return title;
}


function generateDirectoryNode(data) {
    if (data) {
        let temp = Object.assign({}, data);
        temp.basicData = data;
        temp.title = data.title || data.directoryName

        return {
            id: temp.id,
            basicData: temp,
            title: formatterTitle(temp)
        }
    }
    return {};
}

function addDataConfirm(callback) {
    layer.confirm('当前目录已经提交，该操作完成后，需要重新提交。<br>是否继续？', {
        area: ['400px', '220px'],
        icon: 0
    }, function (index) {
        layer.close(index);
        callback && callback()
    })
}

/**
 * 判断当前用户是否为目录的归属者
 * @param directory
 * @returns {boolean|false|Document.orgLeader|*}
 */
function isDirectoryOwner(directory) {
    let user = sessionStorage.getItem('login_user');
    if (user && typeof user !== 'object') {
        user = JSON.parse(user);
    }
    if (user.userId === 'admin' || user.userId === 'sa') {
        return true
    }
    if (!directory) return false;
    if (directory.ownerType === 'org') {
        return directory.ownerId === user.orgId && user.orgLeader;
    }
    return directory.ownerId === user.userId
}
