<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8">
    <title>角色管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" th:href="@{/lib/layui/css/layui.css}" media="all">
    <link rel="stylesheet" th:href="@{/css/public.css}" media="all">
</head>
<body>
<div class="layuimini-container">
    <div class="layuimini-main">
        <fieldset class="table-search-fieldset">
            <legend>搜索信息(<b>收起-展开</b>)</legend>
            <div id="search-div" style="margin: 5px 10px -10px -50px">
                <form class="layui-form" action="" lay-filter="search-form">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">名称</label>
                            <div class="layui-input-inline">
                                <input type="text" id="name" name="name" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">标识</label>
                            <div class="layui-input-inline">
                                <input type="text" name="sign" id="sign" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">状态</label>
                            <div class="layui-input-inline">
                                <select name="status" id="status" lay-filter="status">
                                    <option value="">所有</option>
                                    <option th:each="item:${baseDictList}" th:text="${item.name}"
                                            th:value="${item.code}"></option>
                                </select>
                            </div>
                        </div>

                        <div class="layui-inline">
                            <button type="submit" class="layui-btn" lay-submit lay-filter="data-search-btn"><i
                                    class="layui-icon"></i> 搜 索
                            </button>
                            <button type="submit" class="layui-btn layui-btn-primary" lay-submit
                                    lay-filter="data-reset-btn"><i class="layui-icon layui-icon-refresh"></i> 重 置
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <button class="layui-btn layui-btn-sm data-add-btn" lay-event="add">
                    <i class="layui-icon layui-icon-addition" style="font-size: 10px;"></i>新增
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="edit">
                    <i class="layui-icon layui-icon-edit" style="font-size: 10px;"></i>编辑
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-normal" lay-event="view">
                    <i class="layui-icon layui-icon-file" style="font-size: 10px;"></i>查看
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-danger" lay-event="delete">
                    <i class="layui-icon layui-icon-delete" style="font-size: 10px;"></i>删除
                </button>
            </div>
        </script>

        <table class="layui-hide" id="currentTableId" lay-filter="currentTableFilter"></table>

        <script type="text/html" id="currentTableBar">
            <!--            <a class="layui-btn layui-btn-xs data-count-edit" lay-event="edit">-->
            <!--                <i class="layui-icon layui-icon-edit" style="font-size: 10px;"></i>编辑-->
            <!--            </a>-->
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-authorize" lay-event="authorize">
                <i class="layui-icon layui-icon-set" style="font-size: 10px;"></i>授权
            </a>
            {{#  if(d.status == '0'){ }}
            <a class="layui-btn layui-btn-normal layui-btn-xs data-count-forbid" lay-event="forbid">
                <i class="layui-icon layui-icon-close" style="font-size: 10px;"></i>禁用
            </a>
            {{#  } else { }}
            <a class="layui-btn layui-btn-warm layui-btn-xs data-count-enable" lay-event="enable">
                <i class="layui-icon layui-icon-play" style="font-size: 10px;"></i>启用
            </a>
            {{#  } }}
            <!--            <a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="delete">-->
            <!--                <i class="layui-icon layui-icon-delete" style="font-size: 10px;"></i>删除-->
            <!--            </a>-->
        </script>

        <script type="text/html" id="statusTpl">
            {{#
            var str = '';
            if (d.status == '0') {
            str = '<span class="layui-badge layui-bg-blue">正常</span>';
            } else {
            str = '<span class="layui-badge layui-bg-orange">禁用</span>'
            }
            return str;
            }}
        </script>

    </div>
</div>
<script th:src="@{/lib/jquery-3.4.1/jquery-3.4.1.min.js}" charset="utf-8"></script>
<script th:src="@{/lib/layui/layui.js}" charset="utf-8"></script>
<script th:src="@{/lib/coco-message/coco-message.js}" charset="utf-8"></script>
<script th:src="@{/js/lay-config.js}" charset="utf-8"></script>
<script th:inline="javascript" type="text/javascript">
    AjaxUtil.ctx = /*[[@{/}]]*/'';
    var updateflag = 0;
    layui.use(['form', 'table'], function () {
        var form = layui.form,
            table = layui.table;

        var currTable = table.render({
            elem: '#currentTableId',
            url: AjaxUtil.ctx + 'roleinfo/list',
            method: 'post', //如果无需自定义HTTP类型，可不加该参数
            where: {sortName: 'role_id', sortOrder: 'asc'}, // 初始化时带的参数
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter', 'exports', 'print'],
            cols: [
                [
                    {type: "checkbox", fixed: 'left'},
                    {type: 'numbers', fixed: 'left',title: '序号'},
                    {field: 'name', width: '10%', title: '名称'},
                    {field: 'sign', width: '10%', title: '标志'},
                    {field: 'descript', width: '20%', title: '描述', minWidth: 80},
                    {field: 'status', width: '10%', title: '状态', templet: '#statusTpl', sort: true, align: 'center'},
                    {field: 'cjrxm', width: '10%', title: '创建人'},
                    {field: 'createTime', width: '15%', title: '创建时间', sort: true, align: 'center'},
                    {title: '操作', width: '15%', toolbar: '#currentTableBar', align: "center"}
                ]
            ],
            autoSort: false, //禁用前端自动排序。注意：该参数为 layui 2.4.4 新增
            limits: [10, 15, 20, 25, 50, 100],
            limit: 10,
            page: true,
            skin: 'grid', // 行边框风格
            parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.message, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.rows //解析数据列表
                };
            }
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            currTable.reload({
                page: {
                    curr: 1 // 页码从1开始
                },
                where: {
                    sign: data.field.sign,
                    name: data.field.name,
                    status: data.field.status
                }
            });

            return false;
        });

        // 监听重置操作
        form.on('submit(data-reset-btn)', function (data) {
            form.val("search-form", {
                "name": '',
                "sign": '',
                "status": ''
            });
            // 执行搜索重载
            currTable.reload({
                page: {
                    curr: 1
                },
                where: form.val("search-form")
            });
            return false;
        });

        // 监听排序事件
        table.on('sort(currentTableFilter)', function (obj) { //注：sort 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            console.log(obj.field); //当前排序的字段名
            console.log(obj.type); //当前排序类型：desc（降序）、asc（升序）、null（空对象，默认排序）
            console.log(this); //当前排序的 th 对象

            //尽管我们的 table 自带排序功能，但并没有请求服务端。
            //有些时候，你可能需要根据当前排序的字段，重新向服务端发送请求，从而实现服务端排序，如：
            currTable.reload({
                initSort: obj, //记录初始排序，如果不设的话，将无法标记表头的排序状态。
                where: { //请求参数（注意：这里面的参数可任意定义，并非下面固定的格式）
                    sortName: toLine(obj.field), //排序字段
                    sortOrder: toLine(obj.type) //排序方式
                }
            });
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                var index = layer.open({
                    title: '添加角色',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: [layerwidth + 'px', layerheight + 'px'],
                    content: AjaxUtil.ctx + 'roleinfo/forAdd',
                    end: function () {
                        // 重载表格
                        if (updateflag == 1)
                            currTable.reload();
                        updateflag = 0;
                        layer.close(index);
                    }
                });
            } else if (obj.event == 'edit') {
                var dataRole = table.cache["currentTableId"];
                if (dataRole.length == 0)
                    return;

                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data == null || data.length === 0)
                    Message.warning("请选择要编辑的角色信息！", 1500);
                else if (data.length > 1)
                    Message.warning("请选择一条记录进行编辑！", 1500);
                else {
                    var index = layer.open({
                        title: '编辑角色',
                        type: 2,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: true,
                        area: [layerwidth + 'px', layerheight + 'px'],
                        content: AjaxUtil.ctx + 'roleinfo/forUpdate/' + data[0].roleId,
                        end: function () {
                            // 重载表格
                            if (updateflag == 1)
                                currTable.reload();
                            updateflag = 0;
                            layer.close(index);
                        }
                    });
                }
            } else if (obj.event == 'view') {
                var dataRole = table.cache["currentTableId"];
                if (dataRole.length == 0)
                    return;

                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data == null || data.length === 0)
                    Message.warning("请选择要查看的角色信息！", 1500);
                else if (data.length > 1)
                    Message.warning("请选择一条记录进行查看！", 1500);
                else {
                    var index = layer.open({
                        title: '查看角色',
                        type: 2,
                        shade: 0.2,
                        maxmin: true,
                        shadeClose: true,
                        area: [layerwidth + 'px', layerheight + 'px'],
                        content: AjaxUtil.ctx + 'roleinfo/forView/' + data[0].roleId,
                        end: function () {
                            layer.close(index);
                        }
                    });
                }
            } else if (obj.event === 'delete') {
                var dataRole = table.cache["currentTableId"];
                if (dataRole.length == 0)
                    return;

                var checkStatus = table.checkStatus('currentTableId')
                    , data = checkStatus.data;
                if (data == null || data.length === 0) {
                    Message.warning("请选择要删除的角色！", 1000);
                    return;
                }
                var roleIds = [];
                for (var i = 0, len = data.length; i < len; i++) {
                    roleIds.push(data[i].roleId);
                }
                layer.confirm('确定批量删除所选择角色信息吗？', function (index) {
                    layer.close(index);
                    AjaxUtil.post({
                        url: AjaxUtil.ctx + "roleinfo/batchDelete",
                        contentType: "application/json",
                        data: JSON.stringify(roleIds),
                        success: function (res) {
                            if (res.code === 0) {
                                Message.success(1500, res.message, function () {
                                    currTable.reload();
                                });
                            } else {
                                Message.error(res.message, 1000);
                            }
                        },
                        error: function (error) {
                        }
                    });
                });
            }
        });

        // 监听行工具事件
        table.on('tool(currentTableFilter)', function (obj) {
            var data = obj.data;
            console.log(data);
            if (obj.event === 'authorize') {

                var index = layer.open({
                    title: '角色授权',
                    type: 2,
                    shade: 0.2,
                    maxmin: true,
                    shadeClose: true,
                    area: [layerwidth + 'px', layerheight + 'px'],
                    content: AjaxUtil.ctx + 'roleinfo/authorize/' + data.roleId,
                    end: function () {
                        // 重载表格
                        if (updateflag == 1)
                            currTable.reload();
                        updateflag = 0;
                        layer.close(index);
                    }
                });
                return false;
            } else if (obj.event === 'forbid') {
                layer.confirm('确定禁用该角色吗？', function (index) {
                    layer.close(index);
                    AjaxUtil.get({
                        url: AjaxUtil.ctx + "roleinfo/forbid/" + data.roleId,
                        success: function (res) {
                            if (res.code === 0) {
                                Message.success(1000, res.message, function () {
                                    // 重载表格
                                    currTable.reload();
                                });
                            } else {
                                Message.error(res.message, 1000);
                            }
                        },
                        error: function (error) {
                        }
                    });
                });
                return false;
            } else if (obj.event === 'enable') {
                layer.confirm('确定启用该角色吗？', function (index) {
                    layer.close(index);
                    AjaxUtil.get({
                        url: AjaxUtil.ctx + "roleinfo/enable/" + data.roleId,
                        success: function (res) {
                            if (res.code === 0) {
                                Message.success(1000, res.message, function () {
                                    // 重载表格
                                    currTable.reload();
                                });
                            } else {
                                Message.error(res.message, 1000);
                            }
                        },
                        error: function (error) {
                        }
                    });
                });
                return false;
            }
        });

        //双击
        table.on('rowDouble(currentTableFilter)', function (obj) {
            data = obj.data;
            var index = layer.open({
                title: '查看角色',
                type: 2,
                shade: 0.2,
                maxmin: true,
                shadeClose: true,
                area: [layerwidth + 'px', layerheight + 'px'],
                content: AjaxUtil.ctx + 'roleinfo/forView/' + data.roleId,
                end: function () {
                    layer.close(index);
                }
            });
        });
    });

    function setUpdateFlag() {
        updateflag = 1;
    }
</script>
</body>
</html>