var user = config.user,
    pwd = config.password;
var userList = [], copyUserList = []; //存启用的uers
$(document).ready(function() {
    getUser();
    //使用on绑定动态添加的元素事件
    $(".userItme-left").on("click", "div", function (e) {
        $('.userItme-left div').removeClass('userSelect');
        $(e.target).addClass('userSelect')
        var text = $(e.target).text();
        $('#umodname').val(text);
        $("#umodpwd").val("");
        if (text == 'admin') {//不可以删也不可更改用户名  但可以更改密码
            $('#umodname').prop('readonly', true);
            $('#umodpwd').prop('readonly', false);
            $("#imgDel").show();
            $("#imgDelAfter").hide();
            $("#delId").removeClass('del-img-black').addClass('del-img');
        } else if (text == 'Default') {
            $('#umodname').prop('readonly', true);
            $('#umodpwd').prop('readonly', true);
            $("#imgDel").show();
            $("#imgDelAfter").hide();
            $("#delId").removeClass('del-img-black').addClass('del-img');
        } else {
            $("#delId").removeClass('del-img').addClass('del-img-black');
            $("#imgDel").hide();
            $("#imgDelAfter").show();
            $('#umodname').prop('readonly', false);
            $('#umodpwd').prop('readonly', false);

        }
    });
    $(".add-img").click(function () {
        if (copyUserList.length > userList.length) {
            $.optionBootoast($.i18n.prop("i18n-user-msgs"), "danger")
            return
        }
        $('.userItme-left div').removeClass('userSelect');
        var pattern = /^user(\d+)$/;
        var maxNumber = 0;
        for (var i = 0; i < copyUserList.length; i++) {
            var item = copyUserList[i];
            var match = item.match(pattern);
            if (match) {
                var number = parseInt(match[1]);
                if (number > maxNumber) {
                    maxNumber = number;
                }
            }
        }
        $('<div class="userSelect add-itme">user' + (maxNumber + 1) + '</div>').appendTo('.userItme-left');
        $('#umodname').val('user' + (maxNumber + 1)).prop('readonly', false);
        copyUserList.push('user' + (maxNumber + 1));
        $('#umodpwd').val('');
        $("#delId").removeClass('del-img').addClass('del-img-black');
        $("#imgDel").hide();
        $("#imgDelAfter").show();
        $('#umodname').prop('readonly', false);
        $('#umodpwd').prop('readonly', false);

        var scrollContainer = document.getElementsByClassName("userItme-left")[0];
        scrollContainer.scrollTop = scrollContainer.scrollHeight;
    });
    $("#delId").click(function () {
        setUser('del');
    });
    $("#saveUser").click(function() {
        if ("admin" == user || "super_admin" == user) {
            setUser('save');
        } 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) {
            userList = [];
            copyUserList = [];
            $(".userItme-left").empty();
            var k = $(xmlDoc).find('UserList').eq(0).find('User').length;
            for (var i = 0; i < k; i++) {
                var user = $(xmlDoc).find('UserList').eq(0).find('User').eq(i).find('UserName').eq(0).text();
                userList.push(user);
                copyUserList.push(user);
                $('<div>'+user+'</div>').appendTo('.userItme-left');
            }
            if ($('.userItme-left div:first-child')) {
                $('.userItme-left div:first-child').addClass('userSelect');
                if (userList[0] == 'admin') {
                    selectAdmin();
                }
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });

}

function setUser(type) {
    var cyXml = "";
    var cyURL = config.baseUrl + "/System/Users/1";
    var ulevel = "Normal";
    var requestType = "";
    var uname = $("#umodname").val();
    var upass = $("#umodpwd").val();
    var selectText = $(".userItme-left .userSelect").text();
    if (type === 'del' && selectText !== 'admin' && selectText !== 'Default') {
        if ($.inArray(selectText, userList) != -1) {//当前选中的是否在设备上存在，还是即时添加没有保存的
            requestType = "DELETE";
        } else { //即时添加没有保存的,那就直接删除不需要下发删除接口
            $('.userSelect').remove();
            $('.userItme-left div:first-child').addClass('userSelect');
            selectAdmin();
            copyUserList.pop();
            return false;
        }

    }
    if (type === 'del' && (selectText == 'admin' || selectText == 'Default')) {
        return false;
    }
    if (type == 'save') {
        var regex = /^[^\u4e00-\u9fa5]+$/; // 使用正则表达式匹配非中文字符
        if (!regex.test($("#umodname").val())) {
            $.optionBootoast($.i18n.prop("i18n-msg20"), "danger")
            return false;
        }
        if (config.deviceCap.isSupportEmptyPassword == "true") { //拒绝空密码
            if (upass.length == 0) {
                $.optionBootoast($.i18n.prop("i18n-user-msg2"), "danger")
                return false;
            };
        };
        if (config.deviceCap.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 (uname == 'admin') {
            ulevel = "Administrator";
            requestType = "PUT";
        } else if (uname == 'Default') {
            if ($.inArray(uname, userList) != -1) {
                $.optionBootoast('Default' + $.i18n.prop("i18n-default-msg9"), "danger");
            }
            return false;
        } else if ($.inArray(uname, userList) != -1) { //修改
            requestType = "PUT";
        }else if ($.inArray(uname, userList) == -1) {//添加
            requestType = "POST";
        }
    }
    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>" + $("#umodpwd").val() + "</Password><IPAddress></IPAddress><MACAddress /><UserLevel>" + ulevel + "</UserLevel></User>";
    $.ajax({
        type: requestType,
        url: cyURL,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            // 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 ("-13" == state) {
                $.optionBootoast($.i18n.prop("i18n-default-msg9"), "danger")
            } else if ("-31" == state) {
                $.optionBootoast($.i18n.prop("i18n-default-msg10"), "danger")
            } else if ("0" == state) {
                if (type == 'del') {
                    $.optionBootoast($.i18n.prop('i18n-Presetpoint-delsuccess'), "success")
                } else {
                    $.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 = [];
                getUser();
            }else {
                $.optionBootoast($.i18n.prop("i18n-savefail"), "danger")
            }
        }
    });
}
function selectAdmin() {
    $('#umodname').prop('readonly', true).val('admin');
    $('#umodpwd').prop('readonly', false).val('');
    $("#imgDel").show();
    $("#imgDelAfter").hide();
    $("#delId").removeClass('del-img-black').addClass('del-img');
}
