let userTable;
let tree;
layui.use(['element', 'form', 'dropdown', 'table', 'layer', 'laydate', 'tree', 'gtable', 'orgTree'], function () {
    let table = layui.table;
    let form = layui.form;//select、单选、复选等依赖form
    let element = layui.element; //导航的hover效果、二级菜单等功能，需要依赖element模块
    tree = layui.tree;
    let orgTree = layui.orgTree;
    let layer = layui.layer;
    let gtable = layui.gtable;

    /**
     * 加载用户数据列表
     */
    let opstions = {
        id: 'userTable',
        url: ctx + '/sys/sysUser/page',
        toolbar: '#tableToolBar',
        title: '用户列表',
        cols: [[
            {field: 'userId', title: 'ID', hide: true}
            , {field: 'loginName', title: '用户名', width: 150}
            , {field: 'userName', title: '姓名', width: 150}
            , {field: 'orgName', title: '所属部门', templet: data => data.org ? data.org.orgName : ''}
            , {field: 'valid', title: '是否允许登录系统', hide: true}
            , {field: 'limitMultiLogin', title: '是否允许多人在线', hide: true}
            , {field: 'limitedIp', title: '限制允许登录的IP集合', hide: true}
            , {field: 'expiredTime', title: '账号失效时间', hide: true}
            , {field: 'lastChangePwdTime', title: '最近修改密码时间', hide: true}
            , {field: 'createTime', title: '创建时间', hide: true}
            , {field: 'modifyTime', title: '更新时间', width: 180, align: 'center'}
            , {fixed: 'right', align: 'center', title: '操作', toolbar: '#userTableBarDemo', width: 160}
        ]],
        done: function (res) {
            layui.dropdown.render({
                elem: 'button.operate-btn',
                align: 'right',
                data: [
                    {id: 'role', title: '配置角色'},
                    {id: 'client', title: '配置客户端'},
                    {id: 'pwd', title: '密码重置'},
                    {id: 'del', title: '删除用户'},
                    {id: 'sync', title: '用户同步'}
                ],
                ready: function(panelElem, elem){
                    let userId = $(elem).data('userId')
                    if(userId === user.userId){
                        panelElem.find('ul > li').each((index, item)=>{
                            if("配置角色|配置客户端|删除用户|用户同步".includes($(item).text())){
                                $(item).off('click').css('color', '#cacaca');
                            }
                        })
                    }
                },
                click(data, othis) {
                    let userId = $(this.elem).data('userId')
                    switch (data.id) {
                        case 'role':
                            openRoleLayer(userId);
                            break;
                        case 'client':
                            openClientLayer(userId);
                            break;
                        case 'pwd':
                            resetPassword(userId)
                            break;
                        case 'del':
                            if(userId === 'admin' || userId === 'sa'){
                                showLockMsg('系统内置用户，无法删除')
                                return false;
                            }
                            layer.confirm('删除后，该用户的目录数据将被转移至其部门下。<br>确定要删除吗？', {title: '删除用户', icon: 3}, function (index) {
                                $.delete(ctx + "/sys/sysUser/delete/" + userId, {}, function (data) {
                                    userTable.reload();
                                    layer.close(index);
                                })
                            });
                            break;
                        case 'sync':
                            Util.get(`/sys/sysUser/sync?userId=${userId}`, {}).then(res=>{
                                if(res.flag){
                                    showOkMsg('操作成功');
                                }else{
                                    showErrorMsg('同步失败,请联系管理员');
                                    console.error(res.msg);
                                }
                            })
                    }
                }
            });
        },
        onToolBarTable: function (obj) {
            switch (obj.event) {
                case 'addData':
                    let param = orgTree.getNowParam();
                    if (param && param.id) {
                        openEditLayer(param.id, param.context, "", "add");
                    } else {
                        layer.msg("请先选择所属部门！");
                    }
                    break;
                case 'query':
                    let queryByLoginName = $("#queryByLoginName").val();
                    let query = {
                        page: {
                            current: 1 //重新从第 1 页开始
                        }
                    };
                    if (!queryByLoginName) {
                        queryByLoginName = "";
                    }
                    //设定异步数据接口的额外参数
                    query.where = {loginName: queryByLoginName};
                    userTable.reload(query);
                    $("#queryByLoginName").val(queryByLoginName);
                    break;
                case 'reload':

                    break;
            }
        },
        onToolBarRow: function (obj) {
            if (obj.event == 'edit') {
                openEditLayer("", "", obj.data.userId, "edit");
            }
        }
    };
    userTable = gtable.init(opstions);

    /**
     * 选择角色弹框
     * @param userId
     */
    function openRoleLayer(userId) {
        let roleLayer;
        layer.open({
            id: 'roleLayer',
            type: 2,
            title: '选择角色',
            area: ['300px', '400px'],
            content: ctx + `/sys/role/layer?userId=${userId}`,
            btn: ['关闭'],
            success: function (layero, index) {
                roleLayer = window[layero.find('iframe')[0]['name']]
            },
            yes: function (index) {
                //roleLayer && roleLayer.save();
                layer.close(index)
            },
            end: function () {
                //userTable.reload();
            }
        });
    }


    /**
     * 选择角色弹框
     * @param userId
     */
    function openClientLayer(userId) {
        let clientLayer;
        layer.open({
            id: 'clientLayer',
            type: 2,
            title: '选择客户端',
            area: ['300px', '400px'],
            content: ctx + `/sys/userClient/layer?userId=${userId}`,
            btn: ['关闭'],
            success: function (layero, index) {
                clientLayer = window[layero.find('iframe')[0]['name']]
            },
            yes: function (index) {
                layer.close(index)
            },
            end: function () {

            }
        });
    }


    function openEditLayer(orgId, orgName, userId, type) {
        if (!userId) {
            userId = ''
        }
        if(userId === 'admin' || userId === 'sa'){
            showLockMsg('系统内置用户，无法编辑')
            return false;
        }
        let titleType;
        if ("add" == type) {
            titleType = "新增用户";
        } else if ("edit" == type) {
            titleType = "编辑用户";
        }
        let editLayerWin;
        layer.open({
            id: 'userEdit',
            type: 2,
            title: titleType,
            area: ['500px', '380px'],
            content: ctx + `/sys/sysUser/edit?orgId=${orgId}&orgName=${orgName}&userId=${userId}`,
            btn: ['确定', '取消'],
            success: function (layero, index) {
                editLayerWin = window[layero.find('iframe')[0]['name']]
            },
            yes: function () {
                editLayerWin && editLayerWin.save();
            },
            end: function () {
                gtable.reload();
            }
        });
    }

    /**
     * 加载部门树
     */
    function loadOrgTree() {
        orgTree.init({
            id: `orgTree`,
            done: function (nodes, elem) {
            },
            onClick: function (obj) {
                let query = {
                    page: {
                        curr: 1 //重新从第 1 页开始
                    }
                };
                //设定异步数据接口的额外参数
                query.where = {orgId: obj.param.id};
                gtable.reload(query);
            }
        })
    }

    loadOrgTree();
});


/**
 * 重置密码
 */
function resetPassword(userId) {
    layer.confirm('确认重置该用户的密码吗？', function (index) {
        layer.close(index);
        layer.prompt({
            title: '请输入新密码'
        }, (value, index2) => {
            $.post(ctx + "/sys/sysUser/resetPassword", {userId, password: value}, (data) => {
                if (data.flag) {
                    showOkMsg("密码重置成功")
                    layer.close(index2)
                } else {
                    showErrorMsg(data.msg)
                }
            });
        })
    });
}

