layui.use(['table', 'form', 'layer'], function(){
    var table = layui.table;
    var form = layui.form;
    var layer = layui.layer;
    var $ = layui.$;
    
    // 初始化表格
    table.render({
        elem: '#user-table',
        url: '/api/users',
        headers: {
            'Authorization': 'Bearer ' + localStorage.getItem('token')
        },
        toolbar: '#tableToolbar',
        defaultToolbar: ['filter', 'exports', 'print'],
        cols: [[
            {type: 'checkbox'},
            {field: 'username', title: '用户名', width: 150},
            {field: 'email', title: '邮箱', width: 200},
            {field: 'role', title: '角色', width: 100, templet: '#roleTpl'},
            {field: 'lastLogin', title: '最后登录', width: 160},
            {field: 'createdAt', title: '创建时间', width: 160},
            {fixed: 'right', title: '操作', toolbar: '#tableRowBar', width: 150}
        ]],
        page: true,
        parseData: function(res) {
            if (res.code === 401) {
                window.location.href = '/login';
                return;
            }
            return res;
        }
    });
    
    // 表格工具栏事件
    table.on('toolbar(user-table)', function(obj){
        switch(obj.event){
            case 'refresh':
                table.reload('user-table');
                break;
        }
    });
    
    // 行工具栏事件
    table.on('tool(user-table)', function(obj){
        var data = obj.data;
        
        switch(obj.event){
            case 'edit':
                layer.open({
                    type: 1,
                    title: '编辑用户',
                    area: ['500px', '400px'],
                    content: $('#userFormTpl').html(),
                    success: function(){
                        // 填充表单数据
                        form.val('userForm', {
                            'id': data.id,
                            'username': data.username,
                            'email': data.email,
                            'role': data.role
                        });
                        // 编辑时密码可选
                        $('input[name=password]').removeAttr('required').removeAttr('lay-verify');
                        form.render();
                    }
                });
                break;
            case 'del':
                layer.confirm('确定删除该用户吗？', function(index){
                    fetch('/api/users/' + data.id, {
                        method: 'DELETE',
                        credentials: 'include'
                    })
                    .then(response => response.json())
                    .then(result => {
                        if (result.error) {
                            layer.msg(result.error);
                            return;
                        }
                        layer.msg('删除成功');
                        obj.del();
                    })
                    .catch(error => {
                        layer.msg('删除失败：' + error.message);
                    });
                    layer.close(index);
                });
                break;
        }
    });
    
    // 搜索表单提交
    form.on('submit(search)', function(data){
        table.reload('user-table', {
            where: data.field
        });
        return false;
    });
    
    // 添加用户按钮点击事件
    $('#add-user').on('click', function(){
        layer.open({
            type: 1,
            title: '添加用户',
            area: ['500px', '400px'],
            content: $('#userFormTpl').html(),
            success: function(){
                form.render();
            }
        });
    });
    
    // 用户表单提交
    form.on('submit(userSubmit)', function(data){
        var url = data.field.id ? '/api/users/' + data.field.id : '/api/users';
        var method = data.field.id ? 'PUT' : 'POST';
        
        // 如果是编辑且没有输入密码，则删除密码字段
        if (data.field.id && !data.field.password) {
            delete data.field.password;
        }
        
        fetch(url, {
            method: method,
            headers: {
                'Content-Type': 'application/json'
            },
            credentials: 'include',
            body: JSON.stringify(data.field)
        })
        .then(response => response.json())
        .then(result => {
            if (result.error) {
                layer.msg(result.error);
                return;
            }
            layer.closeAll('page');
            layer.msg(data.field.id ? '更新成功' : '添加成功');
            table.reload('user-table');
        })
        .catch(error => {
            layer.msg((data.field.id ? '更新' : '添加') + '失败：' + error.message);
        });
        
        return false;
    });
});
