layui.use(['form','layer','table','laytpl'],function(){
    var form = layui.form,
        layer = parent.layer === undefined ? layui.layer : top.layer,
        $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;

    //用户列表
    var tableIns = table.render({
        elem: '#list',
        /*url : '../../json/userList.json',*/
        url : '/upms/sysrole/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: 'roleName', title: '角色名称', minWidth:100, align:"center"},
            {field: 'roleDesc', title: '角色详情', minWidth:100, align:"center"},
            {field: 'roleType', title: '角色类型', align:'center',templet:function(d){
                    if(d.roleType == "0"){
                        return "默认角色";
                    }else if(d.roleType == "1"){
                        return "普通管理员";
                    }else if(d.roleType == "2"){
                        return "系统管理员";
                    }else if(d.roleType == "3"){
                        return "区域管理员";
                    }else if(d.roleType == "9"){
                        return "超级管理员";
                    }else{
                        return "异常角色";
                    }
                }},
            {field: 'createTime', title: '创建时间', minWidth:100, align:"center",templet:function (d) {
                    return showTime(d.createTime);
                }},
            {field: 'updateTime', title: '更新时间', align:'center',minWidth:150,templet:function (d) {
                    return showTime(d.updateTime);
                }},
            {title: '操作', minWidth:175, templet:'#listBar',fixed:"right",align:"center"}
        ]]
    });

    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click",function(){
        if($(".searchVal").val() != ''){
            table.reload("listTable",{
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    key: $(".searchVal").val()  //搜索的关键字
                }
            })
        }else{
            layer.msg("请输入搜索的内容");
        }
    });

    //添加用户
    function add(edit){
        var index = layui.layer.open({
            title : "添加信息",
            type : 2,
            content : "/upms/sysrole/update",
            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"));
        })
    }
    $(".add_btn").click(function(){
        add();
    })

    //批量删除
    $(".delAll_btn").click(function(){
        var checkStatus = table.checkStatus('listTable'),
            data = checkStatus.data,
            ids = [];
        if(data.length > 0) {
            for (var i in data) {
                ids.push(data[i].id);
            }
            //console.log(ids)
            layer.confirm('确定删除选中的条目？', {icon: 3, title: '提示信息'}, function (index) {

                $.ajax( {
                    url : "/upms/sysrole/deleteInfoByIds/"+ids,
                    type : "POST",
                    dataType:"json",
                    async : false,
                    contentType:'application/json;charset=UTF-8',
                    success : function(res) {
                        console.log(res);
                        tableIns.reload();
                        layer.close(index);
                    },
                    error:function(e){
                        tableIns.reload();
                        layer.close(index);
                    }
                })
            })
        }else{
            layer.msg("请选择需要删除的条目!");
        }
    })

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

        if(layEvent === 'edit'){ //编辑
            addUser(data);
        }else if(layEvent === 'usable'){ //启用禁用
            var _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'){ //删除
            layer.confirm('确定删除？', {icon: 3, title: '提示信息'}, function (index) {
                $.ajax({
                    url: "/upms/sysrole/deleteInfoByIds/" + data.id,
                    type: "POST",
                    dataType: "json",
                    async: false,
                    contentType: 'application/json;charset=UTF-8',
                    success: function (res) {
                        //console.log(res);
                        tableIns.reload();
                        layer.close(index);
                    },
                    error: function (e) {
                        tableIns.reload();
                        layer.close(index);
                    }
                })
            });
        }
    });

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

    //分配权限
    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({
                type: 2,
                title: '分配权限',
                shadeClose: true,
                shade: 0.8,
                area: ['380px', '80%'],
                content: "/upms/sysrole/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("请选择需要分配权限的角色");
        }

    }

    //时间转换函数
    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;
    }
})
