/**
 * 用户列表 start
 */

//获取公司树
getCompanyTree()

//角色列表
getUserRole()

var pageNo = 1;
var totalPages = 0;

var depname = 0;
var companyId = 0;

//用户列表
getListDataAjax();

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

//公司树点击事件
$(".treeCompany").on('click', function() {

        // if($(this).hasClass('selected')){
        //     return;
        // }
        //判断有没有样式
        $('.treeCompany').removeClass('selected').find('.img').attr('src', '../images/login.png');
        $('.treeDepartment').removeClass('selected').find('.img').attr('src', '../images/login.png');


        $(this).addClass('selected').find('.img').attr('src', '../images/loginSelected.png');

        companyId = $(this).data('id');
        depname = 0;
        $("#userName").val("");
        $('#roleId option').eq(0).prop("selected", true)
        getListDataAjax({ "companyId": $(this).data('id') });

    })
    //部门树点击事件
$(".treeDepartment").on('click', function() {

    // if($(this).hasClass('selected')){
    //     return;
    // }

    $('.treeDepartment').removeClass('selected').find('.img').attr('src', '../images/login.png')
    $('.treeCompany').removeClass('selected').find('.img').attr('src', '../images/login.png')

    $(this).addClass('selected').parent().parent().siblings().addClass('selected').find('.img').attr('src', '../images/loginSelected.png');
    $(this).find('.img').attr('src', '../images/loginSelected.png');

    companyId = 0;
    depname = $(this).data('id');
    $("#userName").val("");
    $('#roleId option').eq(0).prop("selected", true)
    getListDataAjax({ "depname": $(this).data('id') });


})

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


//分页操作
$('#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());
}

//拼接搜索条件
function getSearchParamObj() {

    let queryParam = {};

    let userName = $('#userName').val();
    let roleId = $('#roleId option:selected').val();
    queryParam.userName = userName;
    queryParam.roleId = roleId;

    if (companyId != 0) {
        queryParam.companyId = companyId;
    }

    if (depname != 0) {
        queryParam.depname = depname;
    }

    return queryParam;
}

//拼接树搜索条件



//角色查询 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("请求数据失败!");
    })

}

//获取公司树结构 ajax请求
function getCompanyTree() {

    ajaxRequest(COMPANY_LIST, "POST", {}, function(result) {
        // $(".loadingdata").html(""); 
        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);
        // treeClickSearch();

    }, function(errorMsg) {
        alert("请求数据失败!");
    })

}


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

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

    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-id=" + item.id + " data-user='" + JSON.stringify(item) + "'></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("请求数据失败!");
    })
}


/*新增 修改 关闭 弹框*/
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() {
                        //alert(1)
                        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() {
                            //alert(1)
                            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()

                let data = result.data;
                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;
            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;
        }
    }

    //验证通过 请求ajax

    ajaxRequest(USER_ADD, "POST", userAddParam, function(result) {
        if (result.flag) {
            let data = result.data;
            layer.close(layerCreateIndex);
            layer.msg(result.msg, { icon: 6 });
            getListDataAjax();
        } else {
            //服务端返回报错
            alert(result.msg);
        }

    }, function(errorMsg) {
        alert("用户添加失败!");

    })
})

/* 修改用户发送请求 */
$('#editUser').click(function() {
    //获取表单的值 并转换成对象
    let allParam = serializeArrayToObj($("#editUserForm").serializeArray());

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

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

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

        } else if (userEditObj[key].name == 'sex') {
            if (!userEditObj[key].value) {
                alert('请选择性别');
                return;
            }
            userEditParam['sex'] = md5(userEditObj[key].value);

        } else if (userEditObj[key].name == 'posname') { //aa验证年龄
            if (!userEditObj[key].value) {
                alert('请选择角色');
                return;
            }
            userEditParam['posname'] = 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 if (userEditObj[key].name == 'status') { //aa验证年龄
            if (!userEditObj[key].value) {
                alert('请选择删除状态');
                return;
            }
            userEditParam['status'] = userEditObj[key].value;

        } else if (userEditObj[key].name == 'locked') { //aa验证年龄
            if (!userEditObj[key].value) {
                alert('请选择锁定状态');
                return;
            }
            userEditParam['locked'] = userEditObj[key].value;

        } else if (userEditObj[key].name == 'wrongtimes') { //aa验证年龄
            if (!userEditObj[key].value) {
                alert('请输入错误次数');
                return;
            }
            userEditParam['wrongtimes'] = userEditObj[key].value;

        } else {
            //其它字段  ....
            userEditParam[userEditObj[key].name] = userEditObj[key].value;
        }
    }
    //验证通过 请求ajax
    ajaxRequest(USER_UPDATE, "POST", allParam, 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("请求数据失败!");
        })
    })
}

// 导出 start
$('.export').click(getDataExport)

function getDataExport() {
    // 输出base64编码
    const base64 = s => window.btoa(unescape(encodeURIComponent(s)));
    ajaxRequest(USER_EXPORT, "POST", {}, function(result) {
        let data = result.data;
        let newData = [];
        data.forEach(function(item, index) {
            let posName = "";
            if (item.posname == 1) {
                posName = "超级管理员"
            } else if (item.posname == 2) {
                posName = "普通员工"
            }
            let locked = item.locked ? '未锁定' : '锁定';
            let time = getFormatDate(item.ctime.time)
            newData.push({ truename: item.truename, sex: item.sex, posname: posName, time: time, addman: item.addman, locked: locked, wrongtimes: item.wrongtimes })
        });
        let str = '<tr style="text-align:center"><th>姓名</th><th>性别</th><th>用户身份</th><th>创建时间</th><th>创建人</th><th>锁定状态</th><th>错误次数</th></tr>';
        // 循环遍历，每行加入tr标签，每个单元格加td标签
        for (let i = 0; i < newData.length; i++) {
            str += '<tr style="text-align:center">';
            for (const key in newData[i]) {
                // 增加\t为了不让表格显示科学计数法或者其他格式
                str += `<td x:str>${ newData[i][key] + '\t'}</td>`;
            }
            str += '</tr>';
        }
        // Worksheet名
        const worksheet = 'Sheet1'
        const uri = 'data:application/vnd.ms-excel;base64,';

        // 下载的表格模板数据
        let template = `<html xmlns:o="urn:schemas-microsoft-com:office:office"
          xmlns:x="urn:schemas-microsoft-com:office:excel"
          xmlns="http://www.w3.org/TR/REC-html40">
          <head><meta charset='UTF-8'><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet>
            <x:Name>${worksheet}</x:Name>
            <x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet>
            </x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]-->
            </head><body><table>${str}</table></body></html>`;

        // 通过创建a标签实现
        const link = document.createElement("a");
        link.href = uri + base64(template);
        // 对下载的文件命名
        link.download = "用户管理数据表.xls";
        link.click();

    }, function(errorMsg) {
        alert("请求数据失败!");
    })
}
// 导出  end