var pageNo = 1;
var totalPages = 0;

var depname = 0;
var companyId = 0;

//用户列表
getListDataAjax();

//获取用户列表 ajax请求
function getListDataAjax(queryParam = {}, pageNo = 1) {

    queryParam.pageNo = pageNo;
    // queryParam.pageSize = 4;
    queryParam.roleId = 1;

    ajaxRequest(USER_LIT, "POST", queryParam, function(result) {
        let data = result.pageList;
        let items = '';
        data.forEach(function(item, key) {
            let posName = "";
            if (item.posname == 1) {
                posName = "超级管理员"
            } else if (item.posname == 2) {
                posName = "普通员工"
            }
            let locked = item.locked ? '未锁定' : '锁定';
            items += "<tr>" +
                "<td class='status' data-user='" + JSON.stringify(item) + "' data-id=" + item.id + " data-username=" + item.username + "></td>" +
                "<td>" + item.username + "</td>" +
                "<td>" + item.sex + "</td>" +
                "<td>" + posName + "</td>" +
                "<td>" + getFormatDate(item.ctime.time) + "</td>" +
                "<td>" + item.addman + "</td>" +
                "<td>" + locked + "</td>" +
                "<td>" + item.wrongtimes + "</td>" +
                "</tr>"
        })
        $('#dataList').html(items);

        totalPages = result.totalPages;
        $('#totalPage').html(totalPages); //总共多少页
        $('#dataTotal').html(result.totalCount); //总共多少条数据
        $('#currentPage').val(pageNo); //当前页面
        let pageFrom = (pageNo - 1) * result.pageSize + 1; //开始
        let pageTo = result.pageNo * result.pageSize; //结束
        pageTo = pageTo > result.totalCount ? result.totalCount : pageTo;
        $('#pageFrom').html(pageFrom);
        $('#pageTo').html(pageTo);

        // 无数据时
        if (!data.length) {
            $('.pager.has-data').hide()
            $('.pager.no-data').show()
        } else {
            $('.pager.has-data').show()
            $('.pager.no-data').hide()
        }

        if (pageNo < totalPages) {
            $('#nextPageButton,#lastPageButton').removeClass('disabled');
        } else {
            $('#nextPageButton,#lastPageButton').addClass('disabled');
        }
        if (pageNo === 1) {
            $('#firstPageButton,#prevPageButton').addClass('disabled');
        } else {
            $('#firstPageButton,#prevPageButton').removeClass('disabled');
        }
    }, function(errorMsg) {
        alert("请求数据失败!");
    })
}

//按钮搜索
$('#buttonClick').on('click', function() {
    pageNo = 1;
    getListDataAjax(getSearchParamObj());
})

//拼接搜索条件
function getSearchParamObj() {
    let queryParam = {};
    let userName = $('#userName').val();
    queryParam.userName = userName;
    if (companyId != 0) {
        queryParam.companyId = companyId;
    }
    if (depname != 0) {
        queryParam.depname = depname;
    }
    return queryParam;
}


//重置表单
$('.reset').click(resetForm)

//角色列表
getUserRole()


getCompanyTree()
    //获取公司树结构 ajax请求   
function getCompanyTree() {
    ajaxRequest(COMPANY_LIST, "POST", {}, function(result) {
        let data = result.data;
        let items = '';
        let companyItems = '';
        let companyDepartmentItems = '<option value="">请选择</option>';
        data.forEach(function(item, key) {
            items += `<li  data-id=${item.ownerId} ><span data-id=${item.ownerId}  class="treeCompany"><img  class="img" src="images/login.png" alt=""> ${item.ownerName}  (${item.userNumber})</span>`;
            if (item.child) {
                let data = item.child;
                items += `<ul class="child-three">`;
                data.forEach(function(item, key) {
                    items += `<li   data-id=${item.departmentId} ><span  data-id=${item.departmentId}  class="treeDepartment"><img class="img" src="images/login.png" alt="">${item.departmentName}</span></li>`
                });
                items += ` </ul>`;
            }
            `</li>`
            companyItems += `<option value="${item.ownerId}">${item.ownerName}</option>`
            if (key == 0) {
                let departmentObj = item.child;
                if (departmentObj) {
                    departmentObj.forEach(function(item, key) {
                        companyDepartmentItems += `<option value="${item.id}">${item.departmentName}</option>`
                    })
                    $('#departmentId').html(companyDepartmentItems);
                    $('#departmentIdUpdate').html(companyDepartmentItems);
                }
            }
        })
        $('#child-two').html(items);
        $('#companyId').html(companyItems);
        $('#companyId2').html(companyItems);
    }, function(errorMsg) {
        alert("请求数据失败!");
    })
}
//分页操作
$('#firstPageButton').on('click', function() {
    pageNo = 1;
    getListDataAjax(getSearchParamObj(), 1);
})

$('#lastPageButton').on('click', function() {
    pageNo = totalPages;
    getListDataAjax(getSearchParamObj(), pageNo);
})

$('#prevPageButton').on('click', function() {
    pageNo -= 1;
    getListDataAjax(getSearchParamObj(), pageNo);
})

$('#nextPageButton').on('click', function() {
    pageNo += 1;
    getListDataAjax(getSearchParamObj(), pageNo);
})

//重置表单
function resetForm() {
    pageNo = 1
    $("#userName").val("");
    $('#roleId option').eq(0).prop("selected", true)
    getListDataAjax(getSearchParamObj());
}
//拼接树搜索条件

//角色查询 ajax请求
function getUserRole() {
    ajaxRequest(USER_ROLE, "POST", {}, function(result) {
        $("#loading").empty()
        let data = result.data;
        let roleItems = '';
        let roleItems2 = '';
        data.forEach(function(item, key) {
            roleItems += `<option value="${item.roleId}">${item.roleName}</option>`
            roleItems2 += `<option value="${item.roleId}">${item.roleName}</option>`
        })
        $('#roleId').append(roleItems);
        $('#roleId2').html(roleItems2);
        $('#roleId3').html(roleItems2);
    }, function(errorMsg) {
        alert("请求数据失败!");
    })
}


/*新增 修改 关闭 弹框*/
var layer = layui.layer;
var layerCreateIndex = '';
var layerUpdateIndex = ''
layui.use('layer', function() {

    //新增弹框
    $('.add').click(function() {
            layerCreateIndex = layer.open({
                type: 1,
                title: false,
                closeBtn: 0,
                shadeClose: true,
                skin: 'yourclass',
                area: ['410px', '500px'],
                content: $(".addUserOut"),
                success: function() {
                    $('.clsBtn,.cancel').click(function() {
                        layer.close(layerCreateIndex);
                    })
                }
            })
        })
        //修改弹框信息
    $('.edit').click(function() {

            if (!$('.pure-table tr').has('.checked').length) {
                layer.msg('请选择一条需要修改的信息!', { icon: 5 });
            } else {
                let dataId = $('.pure-table tr').find('.checked').data('id');
                let userInfo = $('.pure-table tr').find('.checked').data('user');

                $('.editUserOut input[name=truename').val(userInfo.truename)
                $('.editUserOut select[name=sex]').val(userInfo.sex)
                $('.editUserOut input[name=phone').val(userInfo.phone)
                $('.editUserOut select[name=posname').val(userInfo.posname)
                $('.editUserOut select[name=locked]').val(userInfo.locked)
                $('.editUserOut select[name=status]').val(userInfo.status)
                $('.editUserOut input[name=wrongtimes').val(userInfo.wrongtimes)

                // 单位赋值
                $('.editUserOut select[name=bian').val(userInfo.bian)
                    // 部门下拉展示及赋值
                if ($('#companyId2').val()) {
                    listDepname()

                    function listDepname() {
                        let companyName = $('#companyId2').find('option:selected').val();
                        ajaxRequest(COMPANY_LIST, "POST", { "ownerId": companyName }, function(result) {
                            let companyDepartmentItems = '<option value="">请选择</option>';
                            let departmentObj = result.data[0].child;
                            departmentObj.forEach(function(item, key) {
                                companyDepartmentItems += `<option value="${item.departmentId}">${item.departmentName}</option>`
                            })
                            $('#departmentIdUpdate').html(companyDepartmentItems);
                        }, function(errorMsg) {
                            alert("请求数据失败!");
                        })
                    }
                }
                // 部门赋值
                $('.editUserOut select[name=depname').val(userInfo.depname)

                $('.editUserOut input[name=username]').val(userInfo.username)

                layerUpdateIndex = layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    shadeClose: true,
                    skin: 'yourclass',
                    area: ['410px', '500px'],
                    content: $(".editUserOut"),
                    success: function() {
                        $('.clsBtn,.cancel').click(function() {
                            layer.close(layerUpdateIndex);
                        })
                    }
                });
            }
        })
        //删除信息
    $('.delete').click(function() {
        if (!$('.pure-table tr').has('.checked').length) {
            //layer.msg('请选择一条需要修改的信息');
            layer.msg('请选择一条需要删除的信息!', { icon: 5 });
        } else {

            let dataUserName = $('.pure-table tr').find('.checked').data('username');

            ajaxRequest(USER_DELETE, "POST", { "username": dataUserName }, function(result) {
                $(".pure-table tbody tr.selected").remove()
                layer.close(layer.layerCreateIndex);
                layer.msg('删除成功!', { icon: 6 });
                getListDataAjax()
            }, function(errorMsg) {
                alert("用户删除失败!");
            })
        }
    })
});


/* 新增用户发送请求 */
$('#addUser').click(function() {
    //获取表单的值
    let userAddObj = $("#addUserForm").serializeArray();

    //发送给服务端的数据格式
    let userAddParam = {};
    for (let key in userAddObj) { //循环验证······

        //验证用户名
        if (userAddObj[key].name == 'username') {
            if (!userAddObj[key].value) {
                alert('请输入用户名');
                return;
            }
            userAddParam['username'] = userAddObj[key].value; // aa  
            userAddParam['agentid'] = userAddObj[key].value;

        } else if (userAddObj[key].name == 'password') {
            if (!userAddObj[key].value) {
                alert('请输入密码');
                return;
            }
            userAddParam['password'] = md5(userAddObj[key].value);

        } else if (userAddObj[key].name == 'age') { //aa验证年龄
            if (!userAddObj[key].value) {
                alert('请填写年龄');
                return;
            } else {
                let pattern = /^(([0-9]|[1-9][1-9]|1[0-7][0-9])(\\.[0-9]+)?|180)$/;
                if (!pattern.test(userAddObj[key].value)) {
                    alert('请输正确的年龄');
                    return false;
                }
            }
            userAddParam['age'] = userAddObj[key].value;

        } else if (userAddObj[key].name == 'truename') { //aa验证真实姓名
            if (!userAddObj[key].value) {
                alert('请填写真实姓名');
                return;
            }
            userAddParam['truename'] = userAddObj[key].value;

        } else if (userAddObj[key].name == 'phone') { //aa验证手机号
            if (!userAddObj[key].value) {
                alert('请填写手机号码');
                return;
            } else {
                let telre = /^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$/;
                if (!telre.test(userAddObj[key].value)) {
                    alert('请输入有效的手机号码');
                    return false;
                }
            }
            userAddParam['phone'] = userAddObj[key].value;

        } else {
            //其它字段  ....
            userAddParam[userAddObj[key].name] = userAddObj[key].value; // aa  inputKey[]???
        }
    }


    //验证通过 请求ajax
    ajaxRequest(USER_ADD, "POST", userAddParam, function(result) {
        let data = result.data;
        layer.close(layerCreateIndex);
        layer.msg('添加成功!', { icon: 6 });
        getListDataAjax();
    }, function(errorMsg) {
        alert("用户添加失败!");
    })
})


/* 修改用户发送请求 */
$('#editUser').click(function() {

    //获取表单的值
    let userEditObj = $("#editUserForm").serializeArray();

    //发送给服务端的数据格式
    let userEditParam = {};

    for (let key in userEditObj) { //循环验证······
        //验证用户名
        if (userEditObj[key].name == 'username') {
            if (!userEditObj[key].value) {
                alert('请输入用户名');
                return;
            }
            userEditParam['username'] = userEditObj[key].value; // aa  
            userEditParam['agentid'] = userEditObj[key].value;

        } else if (userEditObj[key].name == 'password') {
            if (!userEditObj[key].value) {
                alert('请输入密码');
                return;
            }
            userEditParam['password'] = md5(userEditObj[key].value);

        } else if (userEditObj[key].name == 'age') { //aa验证年龄
            if (!userEditObj[key].value) {
                alert('请填写年龄');
                return;
            } else {
                let pattern = /^(([0-9]|[1-9][1-9]|1[0-7][0-9])(\\.[0-9]+)?|180)$/;
                if (!pattern.test(userEditObj[key].value)) {
                    alert('请输正确的年龄');
                    return false;
                }
            }
            userEditParam['age'] = userEditObj[key].value;

        } else if (userEditObj[key].name == 'truename') { //aa验证真实姓名
            if (!userEditObj[key].value) {
                alert('请填写真实姓名');
                return;
            }
            userEditParam['truename'] = userEditObj[key].value;

        } else if (userEditObj[key].name == 'phone') { //aa验证手机号
            if (!userEditObj[key].value) {
                alert('请填写手机号码');
                return;
            } else {
                let telre = /^(13[0-9]|14[0-9]|15[0-9]|17[0-9]|18[0-9])\d{8}$/;
                if (!telre.test(userEditObj[key].value)) {
                    alert('请输入有效的手机号码');
                    return false;
                }
            }
            userEditParam['phone'] = userEditObj[key].value;

        } else {
            //其它字段  ....
            userEditParam[userEditObj[key].name] = userEditObj[key].value; // aa  inputKey[]???
        }
    }

    //验证通过 请求ajax
    ajaxRequest(USER_UPDATE, "POST", userEditParam, function(result) {
        let data = result.data;
        layer.close(layerUpdateIndex);
        layer.msg('修改成功!', { icon: 6 });
        getListDataAjax();
    }, function(errorMsg) {
        alert("用户修改失败!");
    })
})


// 公司与部门联动 (修改和新增)
linkDep('#companyId')
linkDep('#companyId2')

function linkDep(element) {
    $(element).on('change', function() {

        //获取公司id
        let companyName = $(this).find('option:selected').val();
        ajaxRequest(COMPANY_LIST, "POST", { "ownerId": companyName }, function(result) {
            let companyDepartmentItems = '<option value="">请选择</option>';
            let departmentObj = result.data[0].child;
            departmentObj.forEach(function(item, key) {
                companyDepartmentItems += `<option value="${item.departmentId}">${item.departmentName}</option>`
            })
            $('#departmentId').html(companyDepartmentItems);
            $('#departmentIdUpdate').html(companyDepartmentItems);
        }, function(errorMsg) {
            alert("请求数据失败!");
        })
    })
}