var user = config.user,
    pwd = config.password;
var number = 0;
var userlist = []; //存启用的uers
$(document).ready(function() {
    if (config.deviceCap[number].PWDSpecialChars == "true") {
        $("#umodpwdtip").text($.i18n.prop('i18n-default-msg33'));
    }
    initUser();
    $(".userItme-left div").click(function(e) {
        $('.userItme-left div').removeClass('userSelect');
        $(e.target).addClass('userSelect')
        var text = $(e.target).text();
        $('#umodname').val(text);
        $("#umodpwd").val("");
        if ($(".userItme-left div").index(this)) {
            if (userlist.indexOf(text) !== -1) {
                $("input[name='isChecked']").eq(0).prop("checked", true);
            } else {
                $("input[name='isChecked']").eq(1).prop("checked", true);
            }
            $("input[name='isChecked']").eq(1).attr("disabled", false);
        } else { //admin
            $("input[name='isChecked']").eq(0).prop("checked", "true");
            $("input[name='isChecked']").eq(1).attr("disabled", true);
        }

    });
    getUser();
    $("#saveUser").click(function() {
        if ("admin" == user || "super_admin" == user) {
            setUser();
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
        }
    });
});

function getUser() {
    $.ajax({
        url: config.baseUrl + "/System/Users",
        type: "GET",
        async: true,
        timeout: 15000,
        contentType: "text/xml;charset=utf-8",
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            var k = $(xmlDoc).find('UserList').eq(0).find('User').length - 1; //0
            //获取admin
            $(".userItme-left").children().eq(0).text($(xmlDoc).find('UserList').eq(0).find('User').eq(0).find('UserName').eq(0).text());
            //得到user1-5的状态
            var k = $(xmlDoc).find('UserList').eq(0).find('User').length - 1;
            for (var i = 1; i <= k; i++) {
                var suser = $(xmlDoc).find('UserList').eq(0).find('User').eq(i).find('UserName').eq(0).text();
                userlist.push(suser)
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            if (xhr.status == 401) {
                $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
            }
        }
    });

}

function setUser() {
    var cyXml = "";
    var cyURL = config.baseUrl + "/System/Users/1";
    var ulevel = "Normal";
    var requestType = "";
    var uname = $("#umodname").val();
    var upass = $("#umodpwd").val();
    var isOpen = $('input[name="isChecked"]:checked').val();
    var selectText = $(".userItme-left .userSelect").text();
    if (isOpen == "true") { //启用时候校验密码
        if (config.deviceCap[0].isSupportEmptyPassword == "true") { //拒绝空密码
            if (upass.length == 0) {
                $.optionBootoast($.i18n.prop("i18n-user-msg2"), "danger")
                return false;
            };
        };
        if (config.deviceCap[0].PWDSpecialChars == "true") {
            var testpwd = /^(?=.*[a-zA-Z])(?=.*\d)[\s\S]{8,16}$/;
            var isPass = testpwd.test(upass);
            if (!isPass) {
                $.optionBootoast($.i18n.prop("i18n-user-msg3"), "danger")
                return false;
            };
        } else {
            if (config.deviceCap[0].isSupportComplexd == "true") { //支持强密码
                var testpwd = /^(?=.*?[A-Z])(?=.*?[0-9])[0-9a-zA-Z]{8,16}$/g;
                var isPass = testpwd.test(upass);
                if (!isPass) {
                    $.optionBootoast($.i18n.prop("i18n-user-msg3"), "danger")
                    return false;
                };
            };
        }



        if ('admin' == uname) {
            ulevel = "Administrator";
        }
        if (selectText == "admin") {
            requestType = "put";

        } else { //判断当前选中是不是之前就启用 如果启用 就put 如果是禁用就发post
            if (userlist.indexOf(selectText) !== -1) { //发送delete
                requestType = "put";
            } else {
                requestType = "post";
            }
        }
    } else { //禁用 只有uesr用户才会禁用 admin是一直启用  此时有两种情况 初始化就是禁用（不下发接口） 初始化是启用（下发delete）
        if (userlist.indexOf(selectText) !== -1) { //发送delete
            requestType = "DELETE";
        } else {
            return false;
        }
    }
    var PWDSpecial = config.deviceCap[0].PWDSpecialChars || false;
    var ps = '';
    if (config.deviceCap[number].PWDSpecialChars == "true") { //特殊字符用base64加密
        ps = btoa($("#umodpwd").val());
    } else {
        ps = $("#umodpwd").val();
    }
    cyXml = "<?xml version='1.0' encoding='UTF-8' ?><User Version='1.0' xmlns='http://www.zwcloud.wang/ver10/XMLSchema'><ID></ID><UserName>" + $("#umodname").val() + "</UserName><Password>" + ps + "</Password><IPAddress></IPAddress><MACAddress /><UserLevel>" + ulevel + "</UserLevel><IsPasswordEncrypted>" + PWDSpecial + "</IsPasswordEncrypted></User>";
    $.ajax({
        type: requestType,
        url: cyURL,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function (xhr, textStatus) {
            console.log(userlist,'userlist');
            // var xmlDoc = xhr.responseXML;
            var xmlDoc;
            if (sessionStorage.getItem("xystyle") == "p2p") {
                xmlDoc = xmlStr2XmlObj(Base64.decode(xhr.responseJSON[0].attach.response));
            } else {
                xmlDoc = xhr.responseXML;
            }
            var state = $(xmlDoc).find('statusCode').eq(0).text();
            if (state == 0) {
                $.optionBootoast($.i18n.prop('i18n-savesuccess'), "success")
                if (sessionStorage.getItem("xystyle") == "p6s"||sessionStorage.getItem("xystyle") == "p2p"){
                    var data={
                        key:config.NOTIFY_KEYS.SYS_SETTING_USER_MANAGEMENT,
                        value:cyXml,
                        id:config.p2pId
                    }
                    notifyVms(data);
                }
                // userlist = [];
                if (sessionStorage.getItem("xystyle") == "p6s") { //vms修改密码401问题
                    config.user = $("#umodname").val(); //用户名
                    config.password = $("#umodpwd").val(); //密码
                    Login();
                }
                // getUser();
            } else {
                if ("-13" == state) {
                    $.optionBootoast($.i18n.prop("i18n-default-msg9"), "danger")
                } else if ("-31" == state) {
                    $.optionBootoast($.i18n.prop("i18n-default-msg10"), "danger")
                } else {
                    $.optionBootoast($.i18n.prop("i18n-savefail"), "danger")
                }
            }
        }
    });
}

function initUser() {
    $('.userItme-left div').removeClass('userSelect');
    // $('.userItme-left div:first-child').addClass('userSelect');
    $('#umodname').val(config.user);
    if (config.user === "admin") {
        // admin 选中第一个 div（空的）
        $('.userItme-left div:first-child').addClass('userSelect');
    } else if (config.user === "user1") {
        // user1 选中第二个 div
        $('.userItme-left div:nth-child(2)').addClass('userSelect');
    } else if (config.user === "user2") {
        // user2 选中第三个 div
        $('.userItme-left div:nth-child(3)').addClass('userSelect');
    } else if (config.user === "user3") {
        // user3 选中第四个 div
        $('.userItme-left div:nth-child(4)').addClass('userSelect');
    } else if (config.user === "user4") {
        // user4 选中第五个 div
        $('.userItme-left div:nth-child(5)').addClass('userSelect');
    } else if (config.user === "user5") {
        // user5 选中第六个 div
        $('.userItme-left div:nth-child(6)').addClass('userSelect');
    } else {
        // 默认选中第一个（admin 模式）
        $('.userItme-left div:first-child').addClass('userSelect');
    }
    $("input[name='isChecked']").eq(0).prop("checked", "true");
    $("input[name='isChecked']").eq(1).attr("disabled", true);
}
