/**
 * 打开成员管理窗口
 */
let memberManageTable;

function openMembersManageLayer(data) {
    let left = window.innerWidth / 2 - 500;
    let top = window.innerHeight / 2 - 424;
    let global_members = [];
    layer.open({
        type: 1,
        title: '成员管理',
        /*area: ['780px', '630px'],*/
        offset: [top + 'px', left + 'px'],
        btn: ['关闭'],
        content: `<!-- html 模板-->
                <div class="layui-row member layui-col-space15">
                    <div class="layui-col-md12">
                        <div id="memberManage" lay-filter="memberManage" style="display: none;"></div>
                        <script id="memberManageToolBar" type="text/html">
                            <div class="layui-btn-container">
                                <button class="layui-btn layui-btn-sm" lay-event="add-user">添加用户成员</button>
                                <button class="layui-btn layui-btn-sm" lay-event="add-org">添加部门成员</button>
                                <button class="layui-btn layui-btn-sm" lay-event="permis">权限</button>
                                <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete">删除</button>
                            </div>
                        </script>
                    </div>
                </div>`,
        success: function (layerObj, index) {
            init();
        },
        yes: function (index, layerObj) {
            layer.close(index);
        }
    });

    function init() {
        layui.use(['form'], function () {
            layui.form.render();
            renderMemberTable();

            function renderMemberTable() {
                memberManageTable = layui.gtable.init({
                    id: 'memberManage',
                    url: ctx + '/business/directory/members/page',
                    method: 'get',
                    toolbar: '#memberManageToolBar',
                    where: {directoryId: data.id},
                    height: '562',
                    page: true,
                    limit: 30,
                    cols: [[
                        {field: 'id', title: 'ID', hide: true},
                        {field: 'id', type: 'checkbox', title: 'ID', width: 60, align: 'center'},
                        {field: 'memberName', title: '成员名称'},
                        {field: 'memberTypeDesc', title: '成员类型', width: 90, align: 'center'},
                        {
                            field: 'permisType', title: '权限类型', width: 90, align: 'left',
                            templet: permisTypeTemplet
                        },
                        {field: 'modifyTime', title: '修改时间', width: 180, align: 'center'},
                    ]],
                    onToolBarTable: memberManageTableTooBarCallBack,
                    done: () => loadMembers()
                });

                /**
                 * 工具条按钮点击事件回调函数
                 * @param obj
                 */
                function memberManageTableTooBarCallBack(obj) {
                    let checkedMembers = memberManageTable.getCheckStatus().data;
                    switch (obj.event) {
                        case 'add-user':
                            addUserMembers();
                            break;
                        case 'add-org':
                            addOrgMembers();
                            break;
                        case 'permis':
                            setChooseMemberPermis(checkedMembers)
                            break;
                        case 'delete':
                            deleteMembers(checkedMembers);
                            break;
                    }
                }

                /**
                 * 权限类型数据转换
                 * @param d
                 * @returns {*}
                 */
                function permisTypeTemplet(d) {
                    return d.permisType.replace('read', '查看').replace('write', '修改')
                }
            }
        })
    }

    /**
     * 添加用户成员
     */
    function addUserMembers() {
        let ids = global_members.filter(item => item.memberType === 'USER').map(item => item.memberId);
        openUserSelectLayer(false, ids).then(users => {
            choosePermitsOps('USER').then(p => {
                saveMembers(convertMembers(users, 'USER', p));
            })
        })
    }

    /**
     * 添加部门成员
     */
    function addOrgMembers() {
        let ids = global_members.filter(item => item.memberType === 'ORG').map(item => item.memberId);
        openOrgSelectLayer('p-casc').then(orgs => {
            choosePermitsOps('ORG').then(p => {
                saveMembers(convertMembers(orgs, 'ORG', p));
            })
        })
    }

    /**
     * 设置成员权限
     * @param members
     */
    function setChooseMemberPermis(members) {
        if (!members || members.length === 0) {
            showErrorMsg('请至少选择一条数据');
            return;
        }
        const hasOrg = members.some(member => member.memberType === 'ORG');
        choosePermitsOps(hasOrg ? 'ORG' : 'USER').then(p => {
            let params = members.map(m => {
                return {id: m.id, permisType: p.permitsType, applyChildren: p.applyChildren}
            });
            saveMembers(params);
        })
    }

    /**
     * 保存成员
     * @param members
     */
    function saveMembers(members) {
        Util.post(`/business/directory/members/save`, {members}).then(res => {
            if (res.flag) {
                memberManageTable.reload();
            } else {
                showErrorMsg(res.msg);
            }
        }).catch(err => showErrorMsg())
    }

    /**
     * 批量删除成员
     * @param members 成员数组
     */
    function deleteMembers(members, callback) {
        if (!members || members.length === 0) {
            showErrorMsg('请至少选择一条数据');
            return;
        }
        layer.confirm('是否删除这些成员？', {title: '删除确认'}, function (index) {
            let ids = members.map(m => m.id);
            Util.post(`/business/directory/members/delete`, {ids}).then(res => {
                if (res.flag) {
                    layer.close(index);
                    memberManageTable.reload();
                } else {
                    showErrorMsg(res.msg);
                }
            }).catch(err => showErrorMsg())
        });
    }

    /**
     * 选择权限弹框
     * @returns {Promise<unknown>}
     */
    function choosePermitsOps(memberType) {
        const isOrg = memberType === 'ORG';
        const applyChild = isOrg ? 'checked' : ''
        return new Promise(resolve => {
            layer.open({
                type: 1,
                title: '选择权限',
                btn: ['确定'],
                content: `<div class="layui-form permis-choose" lay-filter="permits-choose-form" style="padding-left: 20px; padding-top: 20px;">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <input type="radio" name="permitsType" lay-skin="primary" value="read" title="仅查看权限" checked>
                            <input type="radio" name="permitsType" lay-skin="primary" value="read,write" title="查看和修改权限">
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <input type="checkbox" name="applyChildren" lay-skin="primary" ${isOrg ? '' : 'disabled'} value="1" ${applyChild} title="将此权限设置应用到下级所有部门">
                        </div>
                    </div>
                </div>`,
                success: function () {
                    form.render();
                },
                yes: function (index) {
                    let value = form.val('permits-choose-form');
                    value.applyChildren = !!value.applyChildren
                    resolve && resolve(value);
                    layer.close(index)
                }
            });
        })
    }

    /**
     * 加载目录所有成员数据
     */
    function loadMembers() {
        Util.get(`/business/directory/members/list/${data.id}`,).then(res => {
            global_members = res.data;
        });
    }

    /**
     * 转换成员对象
     * @param items
     * @param memberType
     * @param permits
     * @returns {*}
     */
    function convertMembers(items, memberType, permits) {
        return items.map(item => {
            return {
                directoryId: data.id,
                memberId: memberType === 'USER' ? item.userId : item.id,
                memberName: memberType === 'USER' ? item.userName : item.context,
                memberType: memberType,
                permisType: permits.permitsType,
                applyChildren: permits.applyChildren
            }
        })
    }
}