/**
 * 用户管理
 */
var name = $("#sel").val();
var dataTable = null;
var i;
var userState = "", careUser = "";
var ii;
var resultData = null;
var resultNums = parent.resultNum;

function loadWarning() {
    var type = 0;
    $.ajax({
        type: "POST",
        url: "/pqs9900/log/getWarnInfoCounts",
        data: {
            type: type
        },
        success: function (data) {
            if (data.code === 500) {

            } else {
                if (data.body > 0) {
                    layer.close(ii);
                    ii = layer.open({
                        type: 2,
                        title: false,
                        anim: 2,
                        area: ['800px', '200px'],
                        offset: 'rb',
                        content: 'warnwin',
                        shadeClose: true,
                        yes: function () {
                            layer.closeAll();
                        },
                        success: function (layero, index) {
//	                            var t=setTimeout(function(){
//	                            	layer.close(index);
//	                            },10000);
                        }
                    });
                }
            }
        }
    });
}

function load(userState, careUser) {
    $.ajax({
        type: "POST",
        url: "/pqs9900/user/selectAllUser",
        data: {
            userState: userState,
            careUser: careUser,
            resultNum: resultNums
        },
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (data) {
            initTable(data);
            resultData = data;
            startQuery();
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    });
}

function initTable(data) {
    var height = $(window).height() - 155;
    var length = Math.floor(height / 28);
    if (length < 1) {
        length = 1;
    }
    // var heightTemp = screen.height;
    // var length;
    // if (heightTemp === 768) {
    //     length = 10;
    // } else if (heightTemp === 1024) {
    //     length = 20;
    // } else if (heightTemp === 960) {
    //     length = 15;
    // } else if (heightTemp === 1050) {
    //     length = 18;
    // } else {
    //     length = 15;
    // }
    dataTable = $("#usertId").DataTable();
    dataTable.clear().draw();
    dataTable = $('#usertId').DataTable({
        order: [],
        columnDefs: [
            {
                orderable: false,
                targets: [9]
            }
        ],
        data: data.body,
        destroy: true,
        searching: true,
        dom: 'rtip',
        pageLength: length,
        columns: [
            {width: "7%", data: 'name'},
            {width: "7%", data: 'loginName'},
            {width: "10%", data: 'roleGPIndex'},
            {width: "8%", data: 'deptsName'},
            {width: "9%", data: 'phone'},
            {width: "10%", data: 'registTime'},
            {width: "10%", data: 'lastLoginTime'},
            {width: "10%", data: 'referralCode'},
            {
                width: "6%", data: 'casualUser', render: function (data, type, full, meta) {
                    if (data === 1) {
                        return "临时账户";
                    } else {
                        return "长期账户";
                    }
                }
            },
            {
                width: "5%", data: 'state', render: function (data, type, full, meta) {
                    switch (data) {
                        case 0:
                            return "注销";
                        case 1:
                            return "正常";
                        case 2:
                            return "锁定";
                        case 3:
                            return "待审核";
                        case 4:
                            return "休眠";
                        case 5:
                            return "密码过期";
                    }
                }
            },
            {
                width: "20%", data: 'roleGPIndex', render: function (data, type, full, meta) {
                    var extarButton = "";
                    switch (full.state) {
                        case 0:
                            break;
                        case 1:
                            break;
                        case 2:
                            extarButton = "<button type='button' class='btn  btn-primary  mr10' onclick='unLock(\"" + full.userIndex + "\")' ><i class='fa fa-unlock'></i>解锁</button>";
                            break;
                        case 3:
                            break;
                        case 4:
                            extarButton = "<button type='button' class='btn  btn-primary  mr10' onclick='active(\"" + full.userIndex + "\")' ><i class='fa fa-unlock'></i>激活</button>";
                            break;
                        case 5:
                            break;
                    }
                    var modifyPWDButton = "<button type='button' class='btn  btn-primary  mr10' onclick='updateUserPassWordByIndex(\"" + full.userIndex + "\")' ><i class='fa fa-vcard-o'></i>修改密码</button>"
                    var modifyButton = "";
                    var deleteButton = "";
                    var buttons = "";
                    if (full.item !== "system") {
                        modifyButton = "<button type='button' class='btn  btn-primary  mr10' onclick='updateUserByIndex(\"" + full.userIndex + "\")' ><i class='fa fa-edit'></i>修改</button>";
                        deleteButton = "<button type='button' class='btn  btn-danger  mr10' onclick='deleteUserByIndex(\"" + full.userIndex + "\")' ><i class='fa fa-trash'></i>注销</button>";
                    }
                    if (full.state == 0) {
                        buttons = "";
                    } else {
                        buttons = extarButton + modifyPWDButton + modifyButton + deleteButton;
                    }
                    return buttons;
                }
            }
        ],
        language: {
            url: '/pqs9900/json/chine.json',
            "sEmptyTable": "没有内容"
        },
        'fnDrawCallback': function (oTable) {
            $("#usertId_paginate").append("<div style='float:right;padding-top:4px;padding-left:10px'>到第 <input type='text' id='changePage' class='input-text' style='width:50px;height:28px;'> 页  <button class='btn btn-primary' id='dataTable-btn'>确定</button></div>");
            var table = $("#usertId").dataTable();
            $('#dataTable-btn').click(function (e) {
                if ($("#changePage").val() && $("#changePage").val() > 0) {
                    var redirectpage = $("#changePage").val() - 1;
                } else {
                    var redirectpage = 0;
                }
                table.fnPageChange(redirectpage);
            });
        }
    });
    new $.fn.dataTable.Buttons(dataTable, {
        buttons: [
            {
                extend: 'csv',//导出格式
                title: '用户管理列表',//导出csv名称
                exportOptions: {
                    columns: [0, 1, 2, 3, 4, 5, 6, 7, 8],//导出需要的列
                    format: {
                        body: function (data) {//对导出内容的筛选 data 表格内容 rid 行索引 cid 列索引
                            return data;
                        }
                    }
                }
            }
        ]
    });
    modifyCss(dataTable);
}

//解锁用户
function unLock(index) {
    //先进行密码确认
    var username = $("#username").val();
    confirmIndentity(username, function () {
        var token = $("#token").val();
        $.ajax({
            type: "POST",
            url: "/pqs9900/user/unlockUser",
            dataType: "json",
            data: {
                userIndex: index,
                token: token
            },
            success: function (data) {
                if (data.code === 200) {
                    layer.msg(data.message, {
                        icon: 6,
                        time: 1000
                    }, function () {
                        load(userState, careUser);
                    });
                } else {
                    layer.msg(data.message, {
                        icon: 5,
                        time: 1000
                    }, function () {
                        load(userState, careUser);
                    });
                }
            }
        });
    });
}

$("#userState").change(function () {
    //要触发的事件
    userState = $(this).children('option:selected').val();
});

$("#careUser").change(function () {
    careUser = $(this).children('option:selected').val();
})

//激活用户
function active(index) {
    //先进行密码确认
    var username = $("#username").val();
    confirmIndentity(username, function () {
        var token = $("#token").val();
        $.ajax({
            type: "POST",
            url: "/pqs9900/user/activeUser",
            dataType: "json",
            data: {
                userIndex: index,
                token: token
            },
            success: function (data) {
                if (data.code === 200) {
                    layer.msg(data.message, {
                        icon: 6,
                        time: 1000
                    }, function () {
                        load(userState, careUser);
                    });
                } else if (data.code === 400) {
                    layer.msg(data.message, {
                        icon: 5,
                        time: 1000
                    }, function () {
                        load(userState, careUser);
                    });
                } else {
                    layer.msg(data.message, {
                        icon: 5,
                            time: 1000
                    }, function () {
                        load(userState, careUser);
                    });
                }
            }
        });
    })
}

//修改密码
function updateUserPassWordByIndex(index) {
    //先进行密码确认
    var username = $("#username").val();
    $("#resultNum").val(resultNums);
    confirmIndentity(username, function () {
        $("#userIndex").val(index);
        layer.open({
            type: 2,
            title: '修改密码',
            shadeClose: true,
            resize: false,
            shade: 0.3,
            area: ['325px', '260px'],
            content: 'updateAppPassWord', //iframe的url
            scrollbar: false,
            end: function () {
                layer.close();
            }
        });
    })
}

//修改用户
function updateUserByIndex(index) {
    var username = $("#username").val();
    $("#resultNum").val(resultNums);
    confirmIndentity(username, function () {
        $("#userIndex").val(index);
        layer.open({
            type: 2,
            title: '修改App用户',
            shadeClose: true,
            resize: false,
            shade: 0.3,
            area: ['565px', '470px'],
            content: 'updateAppUser', //iframe的url
            scrollbar: false,
            end: function () {
                layer.close();
            }
        });
    })
}

//删除用户
function deleteUserByIndex(index) {
    var username = $("#username").val();
    confirmIndentity(username, function () {
        var userIndex = index;
        var token = $("#token").val();
        layer.confirm('确定删除？', function (index) {
            $.ajax({
                type: "POST",
                url: "/pqs9900/user/deleteAppUserByIndex",
                dataType: "text",
                data: {
                    index: userIndex,
                    token: token
                },
                success: function (data) {
                    var info = $.parseJSON(data);
                    if (info.code == 500) {
                        //删除用户异常、或者失败
                        layer.msg(info.message, {
                            icon: 5,
                            time: 1000
                        }, function () {
                            load(userState, careUser);
                        });
                    } else {
                        //删除用户成功
                        layer.msg(info.message, {
                            icon: 6,
                            time: 1000
                        }, function () {
                            load(userState, careUser);
                        });
                    }
                }

            });
            layer.close(index);
        })
    })
}

$(document).ready(function () {
    window.setInterval("showDialog()", 180000); //3min刷新一次

    //添加用户
    $("#addAppUser").click(function () {
        $("#resultNum").val(resultNums);
        layer.open({
            type: 2,
            title: '新增app用户',
            shadeClose: true,
            resize: false,
            shade: 0.3,
            area: ['565px', '500px'],
            content: 'addAppUser', //iframe的url
            scrollbar: false,
            end: function () {
                layer.close();
            }
        });
    });
    load(userState, careUser);
    loadWarning();
    inter = setInterval('loadWarning()', 60000);
});

function modifyCss(table) {
    dataTable.buttons().container().css("display", "inline-block");
    dataTable.buttons().container().css("float", "right");
    dataTable.buttons().container().css("top", "4px");
    dataTable.buttons().container().find("a").prepend("<i class='glyphicon glyphicon-share'></i>");
    dataTable.buttons().container().appendTo('.header');
    dataTable.buttons().container().after($("#fliteData")[0]);
}

$("#query").click(function () {
    load(userState, careUser);
})

//搜索表中的数据
function searchResult(value) {
    dataTable.search(value).draw();
}

function showDialog() {
    $.ajax({
            url: '/pqs9900/user/judgeuserstate',
            type: 'post',
            success: function (data) {
                if (data != "success") {
                    layer.alert(data);
                }
            }
        }
    );
}

//特殊处理，表头紧缩问题--start
var it = null;

function startQuery() {
    //实时刷新时间单位为毫秒
    it = setInterval('refreshQuery()', 100);

}

/* 刷新查询 */
function refreshQuery() {
    var width = $("#usertId").width();
    if (width > 100) {
        initTable(resultData);
        window.clearInterval(it)
    }
}

//特殊处理，表头紧缩问题--end
