<!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">
    <style>
        body {
            background-color: #ffffff;
        }
    </style>
</head>
<body>
<div class="layui-form layuimini-form" style="margin-left: -20px; margin-right: 20px">
    <div class="layui-form-item">
        <label class="layui-form-label required">账号</label>
        <div class="layui-input-block">
            <input type="text" name="account" lay-verify="required|acc" lay-reqtext="用户名不能为空" autocomplete="off"
                   class="layui-input">
            <tip>此为用于登陆的账号</tip>
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">姓名</label>
        <div class="layui-input-block">
            <input type="text" name="name" lay-verify="required" lay-reqtext="姓名不能为空" autocomplete="off"
                   class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">所属部门</label>
        <div class="layui-input-block">
            <input type="text" id="deptName" name="deptName" lay-verify="required" lay-reqtext="所属部门不能为空">
            <input type="hidden" id="deptId" name="deptId">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label required">性别</label>
        <div class="layui-input-block">
            <input type="radio" name="sex" value="1" title="男" checked>
            <input type="radio" name="sex" value="2" title="女">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">电话</label>
        <div class="layui-input-block">
            <input type="text" name="phone" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">邮箱</label>
        <div class="layui-input-block">
            <input type="text" name="email" autocomplete="off" class="layui-input">
        </div>
    </div>

    <div class="layui-form-item">
        <label class="layui-form-label">岗位</label>
        <div class="layui-input-block">
            <div id="postSelect" name="postSelect" class="xm-select-demo"></div>
        </div>
    </div>

    <!--    <div class="layui-form-item">-->
    <!--        <label class="layui-form-label">用户头像</label>-->
    <!--        <div class="layui-input-block">-->
    <!--            <input type="hidden" name="avatar" value="">-->
    <!--            <div style="height: 100px;width: 100px;position: relative;">-->
    <!--                <input type="file" accept="image/*" id="pic-input"-->
    <!--                       style="position: absolute;left: 0;top: 0;opacity: 0;filter: alpha(opacity=0);height: 100%;width: 100%;z-index: 99">-->
    <!--                <img th:src="@{/images/photo_icon.png}" alt="" id="pic-img"-->
    <!--                     style="height: 100%;width: 100%;position: absolute;left: 0;top: 0;border: 1px solid #1E9FFF;">-->
    <!--            </div>-->
    <!--        </div>-->
    <!--    </div>-->

    <!--    <div class="layui-form-item layui-form-text">-->
    <!--        <label class="layui-form-label">备注信息</label>-->
    <!--        <div class="layui-input-block">-->
    <!--            <textarea name="remark" class="layui-textarea" autocomplete="off"></textarea>-->
    <!--        </div>-->
    <!--    </div>-->

    <!-- 右侧悬浮按钮 -->
    <div class="right-bottom-btn">
        <button class="layui-btn" lay-filter="cancleBtn">
            <i class="layui-icon layui-icon-close"></i>取消
        </button>
        <button class="layui-btn" lay-submit lay-filter="saveBtn">
            <i class="layui-icon layui-icon-ok"></i>确认
        </button>

    </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/md5/md5.min.js}" charset="utf-8"></script>
<script th:src="@{/lib/xm-select-v1.2.2/xm-select.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 type="text/javascript" th:inline="javascript">
    AjaxUtil.ctx = /*[[@{/}]]*/'';
    layui.use(['form', 'layCascader'], function () {
        var form = layui.form,
            layer = layui.layer,
            layCascader = layui.layCascader;

        // 初始化xmSelect人员岗位选择
        var postSelect;
        var index1 = layer.load(0, {shade: 0.1}); //0代表加载的风格，支持0-2
        AjaxUtil.get({
            url: AjaxUtil.ctx + 'userinfo/listPostByUserId',
            success: function (res) {
                layer.close(index1);
                postSelect = xmSelect.render({
                    el: '#postSelect',
                    data: res.data,
                    theme: {
                        color: '#1E9FFF'
                    }
                })
            },
            error: function (error) {
                layer.close(index1);
                Message.error('获取岗位信息失败！', 1000);
            }
        });


        // 初始化cascader所属部门选择
        var index2 = layer.load(0, {shade: 0.1});
        AjaxUtil.get({
            url: AjaxUtil.ctx + 'userinfo/listDeptForSelect',
            success: function (res) {
                layer.close(index2);

                var datalist = [];
                for (let item of res.data) {
                    item.value = item.deptId;
                    item.label = item.deptName;
                    datalist.push(item);
                }
                // 扁平数据转树
                var options = arrayToTree(datalist, "0");

                // 初始化cascader实例
                var cascader = layCascader({
                    elem: '#deptName',
                    clearable: true,
                    showAllLevels: false, // 配置仅显示最后一级
                    props: {
                        checkStrictly: true, // 配置选择任意一级选项
                    },
                    options: options
                });

                // 监听cascader变化
                cascader.changeEvent(function (value, node) {
                    // 主动关闭面板
                    cascader.close();
                    $("#deptId").val(value);
                    console.log(node);
                });
            },
            error: function (error) {
                layer.close(index2);
                Message.error('获取部门信息失败！', 1000);
            }
        });


        //监听提交
        form.on('submit(saveBtn)', function (data) {
            var selectArr = postSelect.getValue('valueStr');
            console.log("selectArr = " + selectArr);

            var index = layer.alert('确认提交吗？', function () {
                layer.close(index);
                data.field.password = md5.MD5(data.field.password);

                data.field.postStr = selectArr;
                var loading = layer.load(0, {shade: 0.1}); //0代表加载的风格，支持0-2
                AjaxUtil.post({
                    url: AjaxUtil.ctx + "userinfo/doAdd",
                    data: data.field,
                    success: function (res) {
                        if (res.code === 0) {
                            layer.close(loading);
                            Message.success(1500, res.message, function () {
                                parent.setUpdateFlag();
                                // 重载表格
                                var iframeIndex = parent.layer.getFrameIndex(window.name);
                                parent.layer.close(iframeIndex);
                            });
                        } else {
                            layer.close(loading);
                            Message.error(res.message, 1000);
                        }
                    },
                    error: function (error) {
                    }
                });
            });

            return false;
        });

        form.verify({
            acc: function (value, item) { //value：表单的值、item：表单的DOM对象
                if (!new RegExp("^[a-zA-Z0-9_\u4e00-\u9fa5\\s·]+$").test(value)) {
                    return '用户名不能有特殊字符';
                }
                if (/(^\_)|(\__)|(\_+$)/.test(value)) {
                    return '用户名首尾不能出现下划线\'_\'';
                }
                if (/^\d+\d+\d$/.test(value)) {
                    return '用户名不能全为数字';
                }
            },

            //既支持上述函数式的方式，也支持下述数组的形式
            //数组的两个值分别代表：[正则匹配、匹配不符时的提示文字]
            pass: [
                /(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9]).{8,30}/
                , '密码复杂度过低（密码中必须包含字母、数字、特殊字符）'
            ]
        });


        $('#pic-input').change(function () {
            var formData = new FormData();
            formData.append("files", $("#pic-input")[0].files[0]);
            formData.append("fileName", $("#pic-input")[0].files[0].name); // 文件名字
            var index = layer.load(0, {shade: 0.1}); //0代表加载的风格，支持0-2

            AjaxUtil.upload({
                url: AjaxUtil.ctx + 'fileupload/put',
                data: formData,
                success: function (res) {
                    layer.close(index);
                    if (0 === res.code) {
                        $("input[name='avatar']").val(res.data.fileId);
                        $('#pic-img').attr('src', res.data.previewUrl);
                        Message.success(res.message, 1000);
                    } else {
                        Message.error(res.message, 1000);
                    }
                },
                error: function (error) {
                    layer.close(index);
                    Message.error("服务器异常！", 1000);
                }
            });
        });


        // 监听取消按钮
        $("button[lay-filter='cancleBtn']").click(function () {
            var iframeIndex = parent.layer.getFrameIndex(window.name);
            parent.layer.close(iframeIndex);
        });
    });


    /**
     *  扁平数据转树结构
     * @returns {[]}
     * @param data
     * @param firstPid
     */
    function arrayToTree(data, firstPid) {
        const result = [];
        getChildren(data, result, firstPid)
        return result;
    }

    function getChildren(data, result, parentId) {
        for (const item of data) {
            if (item.parentId === parentId) {
                const newItem = {...item, children: []};
                result.push(newItem);
                getChildren(data, newItem.children, item.deptId);
            }
        }
    }
</script>
</body>
</html>