var _tabled = null,
    protocolType = [{
        "3": "P6S",
        "6": "ONVIF"
    }];
var stateList = [];
var row = null;
var currentType = '',
    connectList = [];
var videoManagementList = [];
$(document).ready(function() {
    config.lastnav = "configuration";
    initVideoManagement();
    $("#handAdd").click(function() {
        $("#myModalLabel").text($.i18n.prop("i18n-handle-add"));
        $("#vmModal").modal('show');
        $("#chlabel").hide();
        $("#IPCAddress").val('').prop('readonly', false);;
        $("#IPCPort").val('6060');
        $("#IPCuser").val('admin');
        $("#IPCpw").val('');
        $("#IPCProtocol").select2('val', '3');
        currentType = 'manual_add';
    });
    $("#IPCProtocol").change(function() {
        switch ($(this).select2('val')) {
            case '3':
                $("#IPCPort").val(6060);
                break;
            case '4':
                $("#IPCPort").val(60001);
                break;
            case '5':
                $("#IPCPort").val(80);
                break;
            case '6':
                $("#IPCPort").val(80);
                break;
            case '8':
                $("#IPCPort").val(8091);
                break;
            case '9':
                $("#IPCPort").val(80);
                break;
            default:
                $("#IPCPort").val(6060);
        }
    });
    $("#deleteDev").click(function() {
        deleteDev(row);
    });
    $("#modelSave").click(function() {
        handleClik(currentType);
    });
    $('#IPCuser').blur(function() {
        var value = $(this).val(); // 获取输入框的值
        var isValid = /^[a-zA-Z0-9_.@!#$%^&*\/]+$/.test(value); // 输入校验，只允许字母、数字、点、下划线、@、!、#、$、%、^、&、*、/

        if (!isValid) {
            value = value.replace(/[^\w.@!#$%^&*\/]/ig, ''); // 进行字符替换，过滤非法字符
            $(this).val(value); // 更新输入框的值
        }
        if (value == '') {
            $(this).val('admin');
        }

    });
    $('#IPCPort').blur(function() {
        $(this).val(NumberRangeLimt(this, 1, 65535));
        if ($(this).val() == '') $(this).val('6060');
    });

});

function initVideoManagement() {
    if (!$('.select2').hasClass('select2-offscreen')) {
        $("#IPCProtocol").select2({
            minimumResultsForSearch: -1,
            width: 360
        });
    }
    dataTableDraw();
}

function dataTableDraw() {
    var aoColumns = [{
            "mDataProp": "ChannelID", //mDataProp
            // "sWidth": "10%" //设置列宽
        },
        {
            "mDataProp": "IP",
            "sWidth": "15%" //设置列宽
        },
        {
            "mDataProp": "DevPort",
        },
        {
            "mDataProp": "ProtocolType", //协议
            "mRender": function(data, type, full) { // 返回自定义内容
                return data == "3" ? "P6S" : (data == "6" ? "ONVIF" : "");
            },
        },
        {
            "mDataProp": "MAC",
            "sWidth": "18%" //设置列宽
        },
        {
            "mDataProp": "DevStatus", //状态
        },

        {
            "mRender": function(data, type, full) { // 返回自定义内容
                return '<span class="vm-edit"  onclick="editDevModel(\'' + encodeURIComponent(JSON.stringify(data)) + '\', \'modify\')">' + $.i18n.prop('i18n-edit') + '</span><span style="color:#dadee7;">&nbsp;&nbsp;|&nbsp;&nbsp;</span><span class="vm-del"   onclick="delDevModel(\'' + encodeURIComponent(JSON.stringify(data)) + '\', \'delete\')">' + $.i18n.prop('i18n-delete') + '</span>';

            },
            "mDataProp": null,
        }
    ];
    videoManagementList = getConnectDeviceList();
    _tabled = new table('vmTable', {
        bProcessing: true,
        isCheckBox: false,
        sEmptyTable: $.i18n.prop("i18n-noCreaditps"),
        retrieve: true, //可能是表格重复使用时受到影响 必须加上
        bPaginate: false, //翻页功能
        bLengthChange: false, //改变每页显示数据数量
        bFilter: false, //过滤功能
        bSort: false, //排序功能
        bInfo: false, //页脚信息
        bAutoWidth: false, //自动宽度
        aoColumns: aoColumns,
        aaData: videoManagementList
    });
}

function getDeviceStatusList() {
    var stateList = [];
    $.ajax({
        url: config.baseUrl + "/System/FrontConnectDeviceStatusList",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            var stateMappings = {
                'other error': 'i18n-link-statu1',
                'connectting': 'i18n-link-statu2',
                'connect success': 'i18n-link-statu3',
                'login failed': 'i18n-link-statu4',
                'connect limit': 'i18n-link-statu5',
                'communicate error': 'i18n-link-statu6',
                'disconnected': 'i18n-link-statu7',
                'network disconnect': 'i18n-link-statu8',
                'ip same': 'i18n-link-statu9',
                'weak password': 'i18n-link-statu10'
            };
            var stateLength = $(xmlDoc).find('DevStatusList').eq(0).find('DevStatus').length;
            for (var i = 0; i < stateLength; i++) {
                var stateString = $(xmlDoc).find('DevStatusList').eq(0).find('DevStatus').eq(i).find('LoginStatus').text();
                var state = stateMappings[stateString] || 'i18n-link-statu11';
                stateList.push($.i18n.prop(state));
            }

        }
    });
    return stateList;
}

function getConnectDeviceList() {
    var dataArr = [];
    $.ajax({
        url: config.baseUrl + "/System/FrontConnectDevicetList",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            var stateList = getDeviceStatusList();
            connectList = [];
            var listLength = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').length;
            for (var i = 0; i < listLength; i++) {
                var itme = {};
                itme.ChannelID = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('ChannelID').text();
                itme.IP = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('IP').text();
                connectList.push(itme.IP);
                itme.MAC = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('MAC').text();
                itme.DevPort = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('DevPort').text();
                itme.ProtocolType = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('ProtocolType').text();
                itme.Username = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('Username').text();
                itme.Password = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('Password').text();
                itme.DevStatus = stateList[i];
                dataArr.push(itme);

            }

        }
    });
    return dataArr;
}

function handleClik(type) { //手增 自动曾 编辑



    var ipExp = /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
    if (!ipExp.test($("#IPCAddress").val())) {
        $.optionBootoast($.i18n.prop('i18n-vm-error1'), "danger");
        return false;
    }
    if (currentType == 'auto_add') { //这里判断是否上限应该是在新增的时候去判断
        if (parseInt(config.deviceInfo.VideoInputChannels) == connectList.length) {
            $.optionBootoast($.i18n.prop('i18n-vm-error6'), "danger");
            return false;
        }
    }
    if (currentType == 'manual_add') {
        // 这里也应该在新增的时候去判断是否存在
        for (var i = 0; i < videoManagementList.length; i++) {
            if (videoManagementList[i].IP === $("#IPCAddress").val()) {
                $.optionBootoast($.i18n.prop('i18n-vm-error7'), "danger");
                return false;
            }
        }
    }
    var mac = currentType == 'modify' || currentType == 'auto_add' ? row.MAC : '';
    var cyXml = "<?xml version='1.0' encoding='UTF-8'?><DevConnectList Version='1.0'><DevConnect Version='1.0'><DeviceName></DeviceName>" +
        "<IP>" + $("#IPCAddress").val() + "</IP>" +
        "<Username>" + $("#IPCuser").val() + "</Username>" +
        "<Password>" + $("#IPCpw").val() + "</Password>" +
        "<MAC>" + mac + "</MAC>" +
        "<DevType></DevType>" +
        "<ProtocolType>" + $("#IPCProtocol").select2('val') + "</ProtocolType>" +
        "<DevChannelCount></DevChannelCount>" +
        "<DevPort>" + $("#IPCPort").val() + "</DevPort>" +
        "<ActionState>" + type + "</ActionState>" +
        "<DID></DID>" +
        "</DevConnect>" +
        "</DevConnectList>";
    $.ajax({
        url: config.baseUrl + "/System/FrontConnectDevicetList",
        type: "PUT",
        async: false,
        data: cyXml,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            row = null;
            currentType = '';
            $("#vmModal").modal('hide');
            var statusflg = $(xmlDoc).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();
            //如果是自动添加则返回上一页
            if (0 == statusflg) {
                if (type == 'auto_add') {
                    $("#searchBack,#refresh,#vmSearchTable_wrapper").hide();
                    $("#searchDevbtn,#handAdd,#vmTable_wrapper").show();
                    $.optionBootoast($.i18n.prop('i18n-adddev-success'), "success");
                } else if (type == 'modify') {
                    $.optionBootoast($.i18n.prop('i18n-vm-edit'), "success");
                } else if (type == 'manual_add') {
                    $.optionBootoast($.i18n.prop('i18n-adddev-success'), "success");
                }
            } else {
                if (type == 'auto_add') {
                    $("#searchBack,#refresh,#vmSearchTable_wrapper").hide();
                    $("#searchDevbtn,#handAdd,#vmTable_wrapper").show();
                    $.optionBootoast($.i18n.prop('i18n-vm-error2'), "danger");
                } else if (type == 'modify') {
                    $.optionBootoast($.i18n.prop('i18n-vm-error3'), "danger");
                } else if (type == 'manual_add') {
                    $.optionBootoast($.i18n.prop('i18n-vm-error2'), "danger");
                }
            }
            dataTableDraw();
        },
        error: function() {
            $.optionBootoast($.i18n.prop('i18n-addDev-fail'), "danger")
        }
    })
}

function delDevModel(data, type) {
    row = null;
    row = JSON.parse(decodeURIComponent(data));
    $("#delCh").text(row.ChannelID)
    $("#delDevIp").text(row.IP)
    $("#vmModalDel").modal("show");
}

function addDevModel(data, type) {
    currentType = type;
    row = null;
    row = JSON.parse(decodeURIComponent(data));
    $("#myModalLabel").text($.i18n.prop('i18n-add'));
    $("#chlabel").hide();
    $("#IPCAddress").val(row.IP).prop('readonly', false);;
    $("#IPCProtocol").select2('val', row.ProtocolType);
    $("#IPCPort").val(row.DevPort);
    $("#IPCpw").val('');
    $("#IPCuser").val('admin');
    $("#vmModal").modal("show");
}

function deleteDev(row) { //删
    var cyXml = "<?xml version='1.0' encoding='UTF-8'?><DevConnectList Version='1.0'><DevConnect Version='1.0'><DeviceName></DeviceName>" +
        "<IP>" + row.IP + "</IP>" +
        "<Username>" + row.Username + "</Username>" +
        "<Password>" + row.Password + "</Password>" +
        "<MAC></MAC>" +
        "<DevType></DevType>" +
        "<ProtocolType>" + row.ProtocolType + "</ProtocolType>" +
        "<DevChannelCount></DevChannelCount>" +
        "<DevPort>" + row.DevPort + "</DevPort>" +
        "<ActionState>delete</ActionState>" +
        "<DID></DID>" +
        "</DevConnect>" +
        "</DevConnectList>";
    $.ajax({
        url: config.baseUrl + "/System/FrontConnectDevicetList",
        type: "PUT",
        async: false,
        data: cyXml,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            $("#vmModalDel").modal("hide");
            var statusflg = $(xmlDoc).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();
            if (statusflg == 0) {
                $.optionBootoast($.i18n.prop('i18n-Presetpoint-delsuccess'), "success");
            } else {
                $.optionBootoast($.i18n.prop('i18n-Presetpoint-delfail'), "danger");
            }
            //重新绘制表格
            dataTableDraw();


        }
    })
}

function editDevModel(data, type) {
    row = null;
    currentType = type;
    row = JSON.parse(decodeURIComponent(data));
    $("#myModalLabel").text($.i18n.prop("i18n-edit"));
    $("#chlabel").show();
    $("#chEdit").text(row.ChannelID);
    $("#IPCAddress").val(row.IP).prop('readonly', true);
    $("#IPCProtocol").select2('val', row.ProtocolType);
    $("#IPCPort").val(row.DevPort);
    $("#IPCpw").val(row.Password);
    $("#IPCuser").val(row.Username);
    $("#vmModal").modal("show");
}

function searchDevFun() {
    $("#videoManagementShow,#vmTable_wrapper").hide();
    $("#searchDev,#refresh,#searchBack,#vmSearchTable,#vmSearchTable_wrapper").show();
    $("#searchDevbtn,#handAdd").hide();
    _tabled = null;
    dataSearchTableDraw();
}

function dataSearchTableDraw(msg) {
    var aoColumns = [{
            "mDataProp": "ID", //mDataProp
            // "sWidth": "10%" //设置列宽
        },
        {
            "mDataProp": "IP",
            "sWidth": "15%" //设置列宽
        },
        {
            "mDataProp": "DevPort",
        },
        {
            "mDataProp": "DeviceName",
            "sWidth": "15%" //设置列宽
        },
        {
            "mDataProp": "ProtocolType", //协议
            "mRender": function(data, type, full) { // 返回自定义内容
                return data == "3" ? "P6S" : (data == "6" ? "ONVIF" : "");
            },
        },
        {
            "mDataProp": "MAC",
            "sWidth": "18%" //设置列宽
        },
        {
            "mRender": function(data, type, full) { // 返回自定义内容
                return '<span class="vm-edit"  onclick="addDevModel(\'' + encodeURIComponent(JSON.stringify(data)) + '\', \'auto_add\')">' + $.i18n.prop('i18n-user-add') + '</span>';

            },
            "mDataProp": null,
        }
    ];
    var retrieveData = getSerachDeviceList(msg);
    _tabled = new table('vmSearchTable', {
        bProcessing: true,
        isCheckBox: false,
        retrieve: true, //可能是表格重复使用时受到影响 必须加上
        bPaginate: false, //翻页功能
        bLengthChange: false, //改变每页显示数据数量
        bFilter: false, //过滤功能
        bSort: false, //排序功能
        bInfo: false, //页脚信息
        bAutoWidth: false, //自动宽度
        aoColumns: aoColumns,
        aaData: retrieveData
    });
}

function backDevFun() {
    $("#videoManagementShow,#vmTable_wrapper").show();
    $("#searchDev,#refresh,#searchBack,#vmSearchTable_wrapper").hide();
    $("#searchDevbtn,#handAdd").show();
    _tabled = null;
    dataTableDraw();
}

function getSerachDeviceList(msg) {
    var deviceList = [];
    $.ajax({
        url: config.baseUrl + "/System/FrontDeviceDetectList",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            var listLength = $(xmlDoc).find('DetectList').eq(0).find('DevDetect').length;
            var id = 1;
            for (var i = 0; i < listLength; i++) {
                var ip = $(xmlDoc).find('DetectList').eq(0).find('DevDetect').eq(i).find('IP').text();
                if ($.inArray(ip, connectList) == -1) { //当前ip不在之前数组中，则执行
                    var itme = {};
                    itme.ID = id++;
                    itme.DeviceName = $(xmlDoc).find('DetectList').eq(0).find('DevDetect').eq(i).find('DeviceName').text();
                    itme.IP = ip;
                    itme.MAC = $(xmlDoc).find('DetectList').eq(0).find('DevDetect').eq(i).find('MAC').text();
                    itme.DevPort = $(xmlDoc).find('DetectList').eq(0).find('DevDetect').eq(i).find('DevPort').text();
                    itme.ProtocolType = $(xmlDoc).find('DetectList').eq(0).find('DevDetect').eq(i).find('ProtocolType').text();
                    deviceList.push(itme);
                }
            }
            msg && $.optionBootoast($.i18n.prop("i18n-refresh-success"), "success");
        }
    });
    return deviceList;
}