layui.config({
    base: '/admin/assets/lib/jplus/treeTable/'
}).use(['form', 'layer', 'table', 'laytpl', 'treeTable'], function () {
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table,
        treeTable = layui.treeTable;

    //用户列表
    var tableIns = table.render({
        elem: '#list',
        url: '/upms/sysuser/queryPage',
        method: 'POST',
        dataType: 'json',
        contentType: 'application/json;charset=utf-8',
        headers: {token: ''},
        cellMinWidth: 95,
        page: true,
        height: "full-125",
        limits: [10, 15, 20, 25],
        limit: 15,
        id: "listTable",
        request: {
            pageName: "pageNo",//重新定义当前页码参数名称
            limitName: "pageRows"//重新定义每页大小参数名称
        },
        response: {
            statusName: 'code', //数据状态的字段名称，默认：code
            statusCode: 200, //成功的状态码，默认：0
            msgName: 'msg',  //状态信息的字段名称，默认：msg
            countName: 'totalRows',  //数据总数的字段名称，默认：count
            dataName: 'data' //数据列表的字段名称，默认：data
        },
        where: {
            //请求的参数写在where
        },
        parseData: function (res) {
            return {
                "code": res.code,
                "msg": res.msg, //解析提示文本
                "totalRows": res.data.totalRows, //解析数据长度
                "data": res.data.dataList, //解析数据列表
            };
        },
        cols: [[
            {type: "checkbox", fixed: "left", width: 50},
            {field: 'userName', title: '用户名', minWidth: 100, align: "center"},
            {field: 'loginName', title: '登录名', minWidth: 100, align: "center"},
            {
                field: 'userGender', title: '性别', align: 'center', templet: function (d) {
                    if (d.userGender == "0") {
                        return "男";
                    } else if (d.userGender == "1") {
                        return "女";
                    } else if (d.userGender == "2") {
                        return "保密";
                    } else {
                        return "保密";
                    }
                }
            },
            {field: 'userAddress', title: '用户地址', minWidth: 100, align: "center"},
            {field: 'userDesc', title: '用户详情', minWidth: 100, align: "center"},
            {
                field: 'userEmail', title: '用户邮箱', minWidth: 200, align: 'center', templet: function (d) {
                    if (d.userEmail) {
                        return '<a class="layui-blue" href="mailto:' + d.userEmail + '">' + d.userEmail + '</a>';
                    }
                    return "";
                }
            },
            {field: 'userMobilePhone', title: '手机号码', align: 'center'},
            {
                field: 'userType', title: '用户类型', align: 'center', templet: function (d) {
                    if (d.userType == "0") {
                        return "默认用户";
                    } else if (d.userType == "1") {
                        return "普通管理员";
                    } else if (d.userType == "2") {
                        return "系统管理员";
                    } else if (d.userType == "3") {
                        return "区域管理员";
                    } else if (d.userType == "9") {
                        return "超级管理员";
                    } else {
                        return "未授权用户";
                    }
                }
            },
            {
                field: 'userStatus', title: '用户状态', align: 'center', templet: function (d) {
                    /*return d.userStatus == "0" ? "正常使用" : "限制使用";*/
                    if (d.userStatus == "0") {
                        return "默认";
                    } else if (d.userStatus == "1") {
                        return "无效";
                    } else if (d.userStatus == "2") {
                        return "被删除";
                    } else if (d.userStatus == "3") {
                        return "暂停使用";
                    } else {
                        return "异常用户";
                    }
                }
            },
            {field: 'userIdCard', title: '身份证号', minWidth: 100, align: "center"},
            /*{field: 'userAvatar', title: '用户头像', minWidth:100, align:"center",templet:function(d){
                    return "<img src='"+d.userAvatar+"' style='width: 30px;height: 30px'>";
            }},*/
            {field: 'orgTreeName', title: '所属组织', minWidth: 100, align: "center"},
            {field: 'employeeId', title: '工号', minWidth: 100, align: "center"},
            {field: 'loginerrorTimes', title: '登录错误次数', minWidth: 100, align: "center"},
            {
                field: 'createTime', title: '创建时间', minWidth: 100, align: "center", templet: function (d) {
                    return showTime(d.createTime);
                }
            },
            {
                field: 'updateTime', title: '修改时间', minWidth: 100, align: "center", templet: function (d) {
                    return showTime(d.updateTime);
                }
            },
            {
                field: 'lastLoginTime', title: '最后登录时间', align: 'center', minWidth: 100, templet: function (d) {
                    return showTime(d.lastLoginTime);
                }
            },
            {title: '操作', minWidth: 200, templet: '#listBar', fixed: "right", align: "center", toolBar: '#listBar'}
        ]]
    });

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click", function () {
        table.reload("listTable", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                userName: $("#userName").val(),  //搜索的关键字
                loginName: $("#loginName").val(),
                userMobilePhone: $("#userMobilePhone").val(),
                userNickName: $("#userNickName").val()
            }
        })
    });

    $(".add_btn").click(function () {
        edit();
    })

    //添加用户
    function edit(edit) {
        let title = "添加用户";
        if (edit != null) {
            title = "修改用户";
        }
        const index = layui.layer.open({
            title: title,
            type: 2,
            content: "/upms/sysuser/edit.html",
            success: function (layero, index) {
                var body = layui.layer.getChildFrame('body', index);
                if (edit) {
                    body.find(".userName").val(edit.userName);  //登录名
                    body.find(".userEmail").val(edit.userEmail);  //邮箱
                    body.find(".userSex input[value=" + edit.userSex + "]").prop("checked", "checked");  //性别
                    body.find(".userGrade").val(edit.userGrade);  //会员等级
                    body.find(".userStatus").val(edit.userStatus);    //用户状态
                    body.find(".userDesc").text(edit.userDesc);    //用户简介
                    form.render();
                }
                setTimeout(function () {
                    layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                        tips: 3
                    });
                }, 500)
            }
        });
        layui.layer.full(index);
        window.sessionStorage.setItem("index", index);
        //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
        $(window).on("resize", function () {
            layui.layer.full(window.sessionStorage.getItem("index"));
        })
    }

    //批量删除
    $(".delAll_btn").click(function () {
        let checkStatus = table.checkStatus('listTable'),
            data = checkStatus.data,
            idsArr = [];
        if (data.length > 0) {
            for (const i in data) {
                idsArr.push(data[i].id);
            }
            layer.confirm('确定删除选中的用户？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    url: "/upms/sysuser/deleteByIds",
                    type: "POST",
                    dataType: "json",
                    async: false,
                    contentType: 'application/json;charset=UTF-8',
                    data: JSON.stringify({idsArr: idsArr}),
                    success: function (res) {
                        //console.log(res);
                        tableIns.reload();
                        layer.close(index);
                    },
                    error: function (e) {
                        tableIns.reload();
                        layer.close(index);
                    }
                })
                return false;
            })
        } else {
            layer.msg("请选择需要删除的用户");
        }
    })

    //列表操作
    table.on('tool(list)', function (obj) {
        const layEvent = obj.event,
            data = obj.data;

        if (layEvent === 'edit') { //编辑
            edit(data);
        } else if (layEvent === 'usable') { //启用禁用
            let _this = $(this),
                usableText = "是否确定禁用此用户？",
                btnText = "已禁用";
            if (_this.text() == "已禁用") {
                usableText = "是否确定启用此用户？",
                    btnText = "已启用";
            }
            layer.confirm(usableText, {
                icon: 3,
                title: '系统提示',
                cancel: function (index) {
                    layer.close(index);
                }
            }, function (index) {
                _this.text(btnText);
                layer.close(index);
            }, function (index) {
                layer.close(index);
            });
        } else if (layEvent === 'del') { //删除
            let id = data.id
            layer.confirm('确定删除此用户？', {icon: 3, title: '提示信息'}, function (index) {
                $.get("/upms/sysuser/delete", {
                    id: id  //将需要删除的newsId作为参数传入
                }, function (data) {
                    tableIns.reload();
                    layer.close(index);
                })
            });
        }
    });


    //分配角色
    function allot() {
        var checkStatus = table.checkStatus('listTable'),
            data = checkStatus.data,
            ids = [];
        if (data.length > 0) {
            for (var i in data) {
                ids.push(data[i].id);
            }
            var index = layui.layer.open({
                title: "分配角色",
                type: 2,
                content: "/upms/sysuser/allot?ids=" + ids,
                success: function (layero, index) {
                    var body = layui.layer.getChildFrame('body', index);

                    setTimeout(function () {
                        layui.layer.tips('点击此处返回用户列表', '.layui-layer-setwin .layui-layer-close', {
                            tips: 3
                        });
                    }, 500)
                }
            })
            layui.layer.full(index);
            window.sessionStorage.setItem("index", index);
            //改变窗口大小时，重置弹窗的宽高，防止超出可视区域（如F12调出debug的操作）
            $(window).on("resize", function () {
                layui.layer.full(window.sessionStorage.getItem("index"));
            })
        } else {
            layer.msg("请选择需要分配权限的角色");
        }

    }

    $(".allot_btn").click(function () {
        allot();
    })

    //时间转换函数
    function showTime(tempDate) {
        var d = new Date(tempDate);
        var year = d.getFullYear();
        var month = d.getMonth();
        month++;
        var day = d.getDate();
        var hours = d.getHours();

        var minutes = d.getMinutes();
        var seconds = d.getSeconds();
        month = month < 10 ? "0" + month : month;
        day = day < 10 ? "0" + day : day;
        hours = hours < 10 ? "0" + hours : hours;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;


        var time = year + "-" + month + "-" + day + " " + hours + ":" + minutes + ":" + seconds;
        return time;
    }

    $(".refresh").click(function () {
        location.reload();
    })
})
