var _tabled = null,
    protocolType = {
        "3": "P6S",
        "6": "ONVIF"
    };
var protocolnum, protocolContent='',serialNumber='',isActiveRegister="",publicNetIP='',isAddDeviceByDomain='',ChannelCount=[];
var stateList = [];
var row = null;
var currentType = '',
    connectList = [], connectListAll = [];
var videoManagementList = [], selectedDatas = [];
var onvifchannelList = [];
var vmsP2PFirst = false;//vmsp2p协议第一次进入
$(document).ready(function() {
    config.lastnav = "configuration";
    //运行环境为以下任意一项时, 需请求此文件
  //设备端
    //EasyTool
    if (!sessionStorage.getItem('currentURL')) { 
        sessionStorage.setItem("currentURL", document.location.toString());
    }
    //EasyVMS, 且添加设备的协议为P6S( P2P暂时写死 )
    if (!(sessionStorage.getItem("isdeviceType") == "vms" && URL_RequestVideo("isp2p") == "p2p")) {//vms p6s跟设备走这里
        getProtocol();
    } else { //p2p协议走这里（vms跟easytool） 默认protocolType取值
        $("#IPCProtocol").empty();
        $.each(protocolType, function (key, value) {
            $("#IPCProtocol").append('<option  value="' + key + '">' + value + '</option>');
        });
    }
    // if (URL_RequestVideo("protocolName") != "P6S") { //这里有问题 vms 的p2p协议也走这里了 先注释掉
    //     protocolType[0]['3'] = URL_RequestVideo( "protocolName" );
    // }//默认为P6S, 但vms针对P6S协议名称的显示存在定制
    initVideoManagement();
    $(".hover-img").hover(
        function () {
            $(this).siblings(".hover-span").show(); // 鼠标进入时显示
        },
        function() {
            $(this).siblings(".hover-span").hide(); // 鼠标离开时隐藏
        }
    );
    $(".hover-imgchannel").hover(
        function () {
            $(this).siblings(".hover-spanchannel").show(); // 鼠标进入时显示
        },
        function() {
            $(this).siblings(".hover-spanchannel").hide(); // 鼠标离开时隐藏
        }
    );
    $("#handAdd").click(function () {//手动添加
        $("#IPCPort,#IPCuser,#IPCProtocol,#http,#commandport,#mediaport,#domain").prop('disabled', false);
        $("#IPCProtocol").find("option[value='rtsp']").remove();
        $("#channel").select2('val', '1');
        $("<option value='rtsp'>RTSP</option>").appendTo("#IPCProtocol");
        $("#controlWay").select2('val', 'false');
        $("#myModalLabel").text($.i18n.prop("i18n-handle-add"));
        $("#vmModal").modal('show');
        $("#chlabel").hide();
        $("#controlWayForm").show();
        $("#channels").show();
        $("#controlWay").show();
        $("#controlWay").change();
        $("#address").text($.i18n.prop("i18n-ddns-IP1"));
        $("#IPCAddress").val('').prop('readonly', false);
        $("#IPCPort").val('6060');
        $("#IPCuser").val('admin');
        $("#IPCpw").val('');
        // $("#IPCProtocol").select2('val', '3').change();
        $("#domain").val('');
        $("#http").val(80);
        $("#rtps").val(6066);
        $("#commandport").val(6060);
        $("#mediaport").val(6066);
        currentType = 'manual_add';
        $("#IPCProtocol").select2('val', '3').change();
        serialNumber = '';
        isActiveRegister = "";
        publicNetIP=''
    });
    $("#controlWay").change(function () {
        if ($(this).select2('val') == 'false') {//ip
            $('.control-box').hide();
            $('.ip-box').show();
            $("#channels").show();
        } else {//域名
            $('.ip-box').hide();
            $('.control-box').show();

        }
        $("#IPCProtocol").change();
    })
    $("#IPCProtocol").change(function () {
        switch ($(this).select2('val')) {
            case '3'://p6s
                $("#IPCPort").val(6060);
                $('.rtspclass').hide();
                $('.rtsp-box').hide();
                if (currentType == 'manual_add') {
                    $("#channels").show();
                    $("#controlWayForm").show();
                 }else {
                    $("#channels").hide();
                    $("#controlWayForm").hide();
                    $('.ip-box').hide();
                    $('.p6sclass').show();
                    $("#portId").hide();
                }
                if ($("#controlWay").select2('val') == 'false') {//ip
                    $('.ip-box').show();
                    $('.p6sclass').hide();
                    $("#portId").show();
                } else { //域名
                    $('.ip-box').hide();
                    $('.p6sclass').show();
                    $("#portId").hide();
                    $('.control-box').show();
                }
                break;
            case '4':
                $("#IPCPort").val(60001);
                $("#channels").prop('disabled', false);
                $('.p6sclass').show();
                $('.rtspclass').hide();
                break;
            case '5':
                $("#IPCPort").val(80);
                break;
            case '6'://ONVIF
                $("#channels").hide();
                $('.rtspclass').hide();
                $('.p6sclass').hide();
                $("#IPCPort").val(80);
                $('.rtsp-box').hide();
                $("#portId").show();
                if (currentType == 'manual_add') {
                    $("#controlWayForm").show();
                } else {
                    $('.ip-box').hide();
                    $("#controlWayForm").hide();
                    $("#portId").hide();
                    $('.rtspclass').show();
                }
                if ($("#controlWay").select2('val') == 'false') {//ip
                    $('.ip-box').show();
                    $('.p6sclass').hide();
                    $("#portId").show();
                    $('.rtspclass').hide();
                } else { 
                    $(".control-box").show();
                    $('.rtspclass').show();
                    $('.ip-box').hide();
                    $('.p6sclass').hide();
                    $("#portId").hide();
                }
                break;
            case '8':
                $("#channel").prop('disabled', false);
                $('.p6sclass').show();
                $('.rtspclass').hide();
                $("#IPCPort").val(8091);
                break;
            case '9':
                $("#channel").prop('disabled', false);
                $('.p6sclass').show();
                $('.rtspclass').hide();
                $("#IPCPort").val(80);
                break;
            case 'rtsp':
                $("#controlWayForm").hide();
                $('.ip-box').hide();
                $("#channels").hide();
                $("#portId").hide();
                $('.rtsp-box').show();
                $('.p6sclass').hide();
                $('.control-box').hide();
                $('.rtspclass').hide(); 
                break;
            default:
                $("#channel").prop('disabled', false);
                $('.p6sclass').show();
                $('.rtspclass').hide();
                $("#IPCPort").val(6060);
        }
    });
    $("#deleteDev").click(function() {
        deleteDev(row);
    });
    $("#modelSave").click(function () {
        if ($('#controlWayForm:visible').length > 0 || $('.control-box:visible').length > 0) { 
            if ($("#controlWay").select2('val') == 'true') { //域名
                for (var i = 0; i < videoManagementList.length; i++) {
                    if (videoManagementList[i].Domain == $("#domain").val() && videoManagementList[i].HTTPPort == $("#http").val() && videoManagementList[i].DevPort == $("#commandport").val() && videoManagementList[i].MediaPort == $("#mediaport").val()&& $("#channel").select2('val').indexOf(videoManagementList[i].DevChannelCount)!=-1) {
                        $.optionBootoast($.i18n.prop('i18n-vm-error7'), "danger");
                        return false;
                    }
                }
                if ($("#domain").val()=='') {
                    $.optionBootoast($.i18n.prop('i18n-media-msg'), "danger");
                    return
                }
    
            } else { //ip
                // 这里也应该在新增的时候去判断是否存在
                for (var i = 0; i < videoManagementList.length; i++) {
                    if (videoManagementList[i].IP === $("#IPCAddress").val() && $("#channel").select2('val').indexOf(videoManagementList[i].DevChannelCount)!=-1) {
                        $.optionBootoast($.i18n.prop('i18n-vm-error7'), "danger");
                        return false;
                    }
                }
                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 ($('#channels:visible').length > 0) {//通道号显示说明是手动添加
            
            var ChannelCount = $("#channel").select2('val');
            if (ChannelCount.indexOf('all')!=-1) {
                for (var index = 1; index <= 36; index++) {
                    currentType = 'manual_add';
                    handleClik(currentType, index);
                    
                }
            } else {
                for (var index = 0; index < ChannelCount.length; index++) {
                    currentType = 'manual_add';
                    handleClik(currentType, ChannelCount[index]);
                    if (index == ChannelCount.length - 1) {
                        break;
                    }
                    
                }
            }

        } else {

            handleClik(currentType);
        }
    });
    $("#channel").change(function () {
        if ($(this).select2('val').length == 0) {
            $(this).select2('val',[1]); 
        }
    });
    $('#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');
    });
     // 监听行复选框的点击事件
     $('#vmSearchTable tbody').on('change', '.row-checkbox', function () {
        updateCheckAllState();
    });

});
function URL_RequestVideo(strName) {
    if (sessionStorage.getItem("currentURL")) {
        var strHref = sessionStorage.getItem("currentURL");
    } else { 
        var strHref = document.location.toString();
    }
    var intPos = strHref.indexOf("?");
    var strRight = strHref.substr(intPos + 1);
    var arrTmp = strRight.split("&");
    for (var i = 0; i < arrTmp.length; i++) {
        var dIntPos = arrTmp[i].indexOf("=");
        var paraName = arrTmp[i].substr(0, dIntPos);
        var paraData = arrTmp[i].substr(dIntPos + 1);
        if (paraName.toUpperCase() == strName.toUpperCase()) {
            return paraData;
        }
    }
    return "";
}
function getProtocol() {
    $.ajax({
        url: config.baseUrl + "/Protocol.html",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function (xmlDoc, textStatus, xhr) {
            var protocolSection = xmlDoc.match(/\[Protocol\]([\s\S]*?)(?=\[|$)/)[0];
            // 2. 初始化 protocolData 对象
            var protocolData = {};
            // 3. 解析每一行键值对
            var lines = protocolSection.split('\n');
            for (var i = 0; i < lines.length; i++) {
                var line = lines[i].trim();
                if (line && line.indexOf('=') !== -1) {
                    var parts = line.split('=');
                    var key = parts[0].trim();
                    var value = parts[1].trim();
                    // 处理数字值（如 Type0=3 → 3 是数字而非字符串）
                    protocolData[key] = isNaN(value) ? value : parseInt(value, 10);
                }
            }
           for (var i = 0; i < protocolData.Count; i++) {
                var option = $('<option></option>');
                option.attr('value', protocolData['Type' + i]);
                option.text(protocolData['Name' + i]);
                option.appendTo("#IPCProtocol");
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log("getProtocol error")
        }
    });
}
// 分割
function getStringBetween(str, start, end) {
    var g_bIsIE = !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
    if (!g_bIsIE||config.forceEV) {
        const regex = new RegExp(start + '(.*?)' + end, 's'); // 's' 标志允许 . 匹配换行符
        const match = str.match(regex);
        return match ? match[1] : null;
    } else {
        const startIndex = str.indexOf(start);
        if (startIndex === -1) return null; // start 不在 str 中
        const endIndex = str.indexOf(end, startIndex + start.length);
        if (endIndex === -1) return null; // end 不在 start 之后
        return str.substring(startIndex + start.length, endIndex);
    }
}

function initVideoManagement() {
    for (let index = 1; index <= 36; index++) {
        $("<option value='" + index + "'>" + index + "</option>").appendTo("#channel");
        
    }
    if (!$('.select2').hasClass('select2-offscreen')) {
        $(".select2").select2({
            minimumResultsForSearch: -1,
            width: 220
        });
    }
    dataTableDraw();
}

function dataTableDraw() {
    onvifchannelList = [];
    var aoColumns = [{
            "mDataProp": "ChannelID", //mDataProp
            // "sWidth": "10%" //设置列宽
        },
        {
            "mDataProp": "IP",
            "mRender": function (data, type, full) {//表格ip一栏的显示
                if (full.RtspConnectFlag == 'true') {
                    return atob(full.RtspUrl);
                } else { 
                    if (full.ProductType == 'NVR') {
                        if (full.IsActiveRegister =='true' && full.PublicNetIP != '') {//主动注册用公网ip-局域网ip
                            return full.PublicNetIP + '-' + data;
                        } else if (full.IsAddDeviceByDomain=='true') { //域名
                            return full.Domain + '-' + full.DevChannelCount;
                        }else { //ip
                            return data + '-' + full.DevChannelCount;
                        }
                    } else { 
                        if (full.IsActiveRegister =='true' && full.PublicNetIP != '') {//主动注册用公网ip-局域网ip
                            return full.PublicNetIP + '-' + data;
                        } else if (full.IsAddDeviceByDomain == 'true') { //域名
                            return full.Domain;
                        }else { //ip
                            return data;
                        }
                    }
                }
               
               

            },
            "sWidth": "15%" //设置列宽
        },
        {
            "mDataProp": "DevPort",
        },
        {
            "mDataProp": "ProtocolType", //协议
            "mRender": function (data, type, full) { // 返回自定义内容
                if (full.RtspConnectFlag == 'true') {
                    return 'RTSP';
                } else { 
                    if (data == "6") {//ONVIF协议需要单独处理
                        onvifchannelList.push(parseInt(full.ChannelID));
                    }
                    sessionStorage.setItem('onvifchannelList', JSON.stringify(onvifchannelList));
                    return data == 3 ? 'P6S' : (data == "6" ? "ONVIF" : "");
                }
                
            },
        },
        {
            "mDataProp": "MAC",
            "sWidth": "18%", //设置列宽
        },
        {
            "mDataProp": "DevStatus", //状态
        },

        {
            "mRender": function (data, type, full) { // 返回自定义内容
                if (full.IsActiveRegister == 'true' || full.RtspConnectFlag == 'true') {
                    return '<span class="vm-del"   onclick="delDevModel(\'' + encodeURIComponent(JSON.stringify(data)) + '\', \'delete\')">' + $.i18n.prop('i18n-delete') + '</span>';
                } else {
                    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();
                if (stateString) {
                    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 = [],connectListAll=[];
            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();
                itme.DevChannelCount = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('DevChannelCount').text();
                itme.PublicNetIP = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('PublicNetIP').text();
                itme.Domain = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('Domain').text();
                itme.IsAddDeviceByDomain = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('IsAddDeviceByDomain').text();
                connectList.push(itme.IP);
                connectListAll.push(itme.ChannelID);
                itme.MAC = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('MAC').text();
                itme.IsActiveRegister = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('IsActiveRegister').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.MediaPort = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('MediaPort').text();
                itme.HTTPPort = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('HTTPPort').text();
                itme.DevType = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('DevType').text();
                itme.RtspConnectFlag = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('RtspConnectFlag').text();
                itme.ProductType = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('ProductType').text();
                itme.RtspUrl = $(xmlDoc).find('DevConnectList').eq(0).find('DevConnect').eq(i).find('RtspUrl').text();
                itme.DevStatus = stateList[i];
                dataArr.push(itme);

            }

        }
    });
    return dataArr;
}

function handleClik(type, Channel) { //手增 自动曾 编辑
    $("#vmModal").modal('hide');
    var rtspConnectFlag = false;
    if (currentType == 'auto_add') { //这里判断是否上限应该是在新增的时候去判断
        isAddDeviceByDomain = '';
        if (parseInt(config.deviceInfo.VideoInputChannels) == connectList.length) {
            $.optionBootoast($.i18n.prop('i18n-vm-error6'), "danger");
            return false;
        }
    }
    var DevPort = $("#IPCPort").val(), MediaPort = $("#mediaport").val(), ProtocolType = $("#IPCProtocol").select2('val');
    if (currentType == 'manual_add') {
        if (parseInt(config.deviceInfo.VideoInputChannels) == connectListAll.length) {
            $.optionBootoast($.i18n.prop('i18n-vm-error6'), "danger");
            return false;
        }
        if ($("#IPCProtocol").select2('val') == 'rtsp') {
            if ($("#mainStream").val() == '' || $("#subStream").val() == '') {
                $.optionBootoast('请输入主子码流', "danger");
                return false;
            }
            if ($("#mainStream").val() == $("#subStream").val()) {
                $.optionBootoast('主子码流链接不能相同', "danger");
                return false;
            }

            // 获取并处理主码流和子码流
           var mainStream = $("#mainStream").val();
            if (!mainStream.startsWith('rtsp://')) {
                mainStream = btoa('rtsp://' + mainStream);
            } else { 
                mainStream = btoa(mainStream);
            }
            var subStream = $("#subStream").val();
            if (!subStream.startsWith('rtsp://')) {
                subStream = btoa('rtsp://' + subStream);
            } else { 
                subStream = btoa(subStream);
            }
            rtspConnectFlag = true;
            ProtocolType = '6';
        } else { 
            isAddDeviceByDomain = $("#controlWay").select2('val');
            if ($("#controlWay").select2('val') == 'true') { //域名
                ProtocolType= $("#IPCProtocol").select2('val');
                $("#IPCAddress").val('');
                if ($("#IPCProtocol").select2('val') == '6') {
                    DevPort = $("#http").val();
                    MediaPort = $("#rtps").val();
                } else {
                    DevPort = $("#commandport").val();
                }
    
            } else { //ip
                $("#domain,#http,#commandport,#mediaport").val('');
            }
        }
        $.MaskUtil.mask($.i18n.prop("i18n-video-msg"));
        
    }
    if (currentType == 'modify') {
        if (isAddDeviceByDomain == 'true') {
            // DevPort = $("#commandport").val();
            ProtocolType= $("#IPCProtocol").select2('val');
            if ($("#IPCProtocol").select2('val') == '6') {
                DevPort = $("#http").val();
                MediaPort = $("#rtps").val();
            } else {
                DevPort = $("#commandport").val();
            }
        }

    }
    var serial = isActiveRegister == "true" ? serialNumber : '';
    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>" + ProtocolType + "</ProtocolType>" +
        "<DevChannelCount>"+(Channel?Channel:'')+"</DevChannelCount>" +
        "<DevPort>" + DevPort + "</DevPort>" +
        "<ActionState>" + type + "</ActionState>" +
        "<DID></DID>" +
        "<IsActiveRegister>" + isActiveRegister + "</IsActiveRegister>" +
        "<PublicNetIP>" + publicNetIP + "</PublicNetIP>"+
        "<HTTPPort>"+$("#http").val()+"</HTTPPort>"+
        "<MediaPort>"+ MediaPort +"</MediaPort>"+
        "<IsAddDeviceByDomain>" + isAddDeviceByDomain + "</IsAddDeviceByDomain>" +
        "<SerialNumber>" + serial + "</SerialNumber>" +
        "<Domain>" + (rtspConnectFlag ?subStream:$("#domain").val()) + "</Domain>" +
        "<RtspUrl>"+mainStream+"</RtspUrl>"+
        "<RtspConnectFlag>"+rtspConnectFlag+"</RtspConnectFlag><ProductType></ProductType>"+
        "</DevConnect>" +
    "</DevConnectList>";
        $.ajax({
            url: config.baseUrl + "/System/FrontConnectDevicetList",
            type: "PUT",
            async: true,
            data: cyXml,
            timeout: 15000,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            success: function (xmlDoc, textStatus, xhr) {
                if (config.isSupportDeviceCapV2 && config.deviceInfo.DeviceName == "NVR") {
                    setTimeout(function(){
                        config.deviceCapV2 = getDeviceCapV2();
                        console.log("设备能力集:", config.deviceCapV2);
                    }, 500); // 适当调整延迟时间
                }
                row = null;
                currentType = '';
                $.MaskUtil.unmask();
                var statusflg = $(xmlDoc).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();
                //如果是自动添加则返回上一页
                if (0 == statusflg) {
                    if (type == 'auto_add') {
                        $("#searchBack,#refresh,#vmSearchTable_wrapper,#batchAdd,#searchDev").hide();
                        $("#searchDevbtn,#handAdd,#vmTable_wrapper,#videoManagementShow").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,,#batchAdd,#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() {
                $.MaskUtil.unmask();
                $.optionBootoast($.i18n.prop('i18n-addDev-fail'), "danger")
            }
        })
}
// 统一处理 RTSP 流地址
function formatStreamUrl(url) {
    if (!url) return url; // 防止空值
    
    // 1. 确保以 rtsp:// 开头
    if (!url.startsWith('rtsp://')) {
        url = 'rtsp://' + url;
    }
    
    // 2. 转义 & 为 &amp;
    url = url.replace(/&/g, '&amp;');
    
    return url;
}

// 获取并处理主码流和子码流
var mainStream = formatStreamUrl($("#mainStream").val());
var subStream = formatStreamUrl($("#subStream").val());
function handleSingleChannel() { 

}
function delDevModel(data, type) {
    row = null;
    row = JSON.parse(decodeURIComponent(data));
    $("#delCh").text(row.ChannelID);
    if (row.IsActiveRegister == "true") { //主动注册
        $("#delDevIp").text(row.PublicNetIP + '-' + row.IP);
    } else if (row.IsAddDeviceByDomain == 'true') { //域名
        $("#delDevIp").text(row.Domain);
    } else { //ip
        $("#delDevIp").text(row.IP);
    }
    $("#vmModalDel").modal("show");
}

function addDevModel(data, type) {
    $("#IPCPort,#IPCuser,#IPCProtocol,#http,#commandport,#mediaport,#domain").prop('disabled', false);
    currentType = type;
    row = null;
    row = JSON.parse(decodeURIComponent(data));
    serialNumber = row.SerialNumber;
    isActiveRegister = row.IsActiveRegister;
    publicNetIP = row.PublicNetIP;
    $("#domain").val("");
    $("#http").val('');
    $("#commandport").val('');
    $("#mediaport").val('');
    $("#address").text($.i18n.prop("i18n-ipAddress"));
    $("#myModalLabel").text($.i18n.prop('i18n-add'));
    $("#controlWayForm").hide();
    $("#channels").hide();
    $(".control-box,.rtsp-box").hide();
    $('.ip-box').show();
    $("#chlabel").hide();
    $("#IPCAddress").val(row.IP).prop('readonly', true);
    const selectElement = document.getElementById('IPCProtocol');
    for (let i = 0; i < selectElement.options.length; i++) {
        const option = selectElement.options[i];
        if (option.value == 'rtsp') {
            // 找到value为rtsp的选项并移除
            selectElement.removeChild(option);
            break; 
        }
    }
    $("#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>" +
        "<DevPort>" + row.DevPort + "</DevPort>" +
        "<ActionState>delete</ActionState>" +
        "<DID></DID>" +
        "<IsActiveRegister>" + row.IsActiveRegister + "</IsActiveRegister>" +
        "<PublicNetIP>" + row.PublicNetIP + "</PublicNetIP>" +
        "<HTTPPort>" + row.HTTPPort + "</HTTPPort>" +
        "<MediaPort>" + row.MediaPort + "</MediaPort>" +
        "<IsAddDeviceByDomain>" + row.IsAddDeviceByDomain + "</IsAddDeviceByDomain>" +
        "<SerialNumber></SerialNumber>" +
        "<Domain>" + row.Domain + "</Domain>" +
        "<RtspUrl>" + row.RtspUrl + "</RtspUrl><DevChannelCount>" + row.DevChannelCount + "</DevChannelCount>"+
        "<RtspConnectFlag>" + row.RtspConnectFlag + "</RtspConnectFlag><ProductType>" + row.ProductType + "</ProductType>"+
        "</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) {
            if (config.isSupportDeviceCapV2 && config.deviceInfo.DeviceName == "NVR") {
                setTimeout(function() {
                    config.deviceCapV2 = getDeviceCapV2();
                    console.log("设备能力集:", config.deviceCapV2);
                }, 500); // 适当调整延迟时间
            }
            $("#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) {
    $("#IPCPort,#IPCuser,#IPCProtocol,#http,#commandport,#mediaport,#domain").prop('disabled', false);
    const selectElement = document.getElementById('IPCProtocol');
    for (let i = 0; i < selectElement.options.length; i++) {
        const option = selectElement.options[i];
        if (option.value == 'rtsp') {
            // 找到value为rtsp的选项并移除
            selectElement.removeChild(option);
            break; 
        }
    }
    row = null;
    currentType = type;
    row = JSON.parse(decodeURIComponent(data));
    $(".control-box").hide();
    $("#myModalLabel").text($.i18n.prop("i18n-edit"));
    $("#chlabel").show();
    $("#controlWayForm").hide();
    $("#channels").hide();
    $(".rtspclass").hide();
    $('.ip-box').show();
    $("#chEdit").text(row.ChannelID);
    $("#address").text($.i18n.prop("i18n-ipAddress"));
    isAddDeviceByDomain = row.IsAddDeviceByDomain;
    if (row.IsAddDeviceByDomain == "true" && row.Domain != '') { //显示域名之类
        $("#controlWay").select2('val', 'true');
        $(".ip-box").hide();
        $(".control-box").show();
        $("#domain").val(row.Domain);
        $("#http").val(row.HTTPPort);
        $("#commandport").val(row.DevPort);
        $("#mediaport").val(row.MediaPort);
        $("#IPCProtocol").select2('val', row.ProtocolType);
    } else {
        $("#controlWay").select2('val', 'false');
        $(".control-box").hide()
        $(".ip-box").show();
        $("#IPCAddress").val(row.IP).prop('readonly', true);
        $("#IPCProtocol").select2('val', row.ProtocolType);
        $("#IPCPort").val(row.DevPort);
    }
    $("#IPCProtocol").change();
    $("#IPCpw").val(row.Password);
    $("#IPCuser").val(row.Username);
    if (row.ProductType == 'NVR') { 
        $("#IPCPort,#IPCuser,#IPCProtocol,#http,#commandport,#mediaport,#domain").prop('disabled', true);
    }
    $("#vmModal").modal("show");
    serialNumber = "";
    isActiveRegister = "";
    publicNetIP = '';


}

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

function dataSearchTableDraw(msg) {
    // if (_tabled) {
    //     _tabled.destroy();
    //     _tabled = null;
    // }
    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%" //设置列宽
        },
        {
            "mDataProp": "IsActiveRegister",
            "mRender": function(data, type, full) { // 返回自定义内容
                return data == "true" ? $.i18n.prop('i18n-yes') : $.i18n.prop('i18n-no');
            },
            "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: true,
        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,#batchAdd").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.IsActiveRegister = $(xmlDoc).find('DetectList').eq(0).find('DevDetect').eq(i).find('IsActiveRegister').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();
                    itme.SerialNumber = $(xmlDoc).find('DetectList').eq(0).find('DevDetect').eq(i).find('SerialNumber').text();
                    itme.PublicNetIP = $(xmlDoc).find('DetectList').eq(0).find('DevDetect').eq(i).find('PublicNetIP').text();
                    deviceList.push(itme);
                }
            }
            msg && $.optionBootoast($.i18n.prop("i18n-refresh-success"), "success");
        }
    });
    return deviceList;
}
function batchAddFun() {
    selectedDatas = [];
    selectedDatas = _tabled.getSelectedDatas();
    if (selectedDatas.length == 0) {
        $.optionBootoast($.i18n.prop("i18n-select-device"), "warning");
        return;
    }
    $("#batchModal").modal("show");
    
    
}
function modelBatchSave() { 
    for (var index = 0; index < selectedDatas.length; index++) {
        var cyXml = "<?xml version='1.0' encoding='UTF-8'?><DevConnectList Version='1.0'><DevConnect Version='1.0'><DeviceName></DeviceName>" +
        "<IP>" + selectedDatas[index].IP + "</IP>" +
        "<Username>" + $("#user").val() + "</Username>" +
        "<Password>" + $("#pw").val() + "</Password>" +
        "<MAC>" + selectedDatas[index].MAC  + "</MAC>" +
        "<DevType></DevType>" +
        "<ProtocolType>" + (selectedDatas[index].ProtocolType || 3) + "</ProtocolType>" +
        "<DevChannelCount></DevChannelCount>" +
        "<DevPort>" + selectedDatas[index].DevPort + "</DevPort>" +
        "<ActionState>auto_add</ActionState>" +
        "<DID></DID>" +
        "<IsActiveRegister>" + selectedDatas[index].IsActiveRegister + "</IsActiveRegister>" +
        "<PublicNetIP>" + selectedDatas[index].PublicNetIP + "</PublicNetIP>"+
        "<HTTPPort></HTTPPort>"+
        "<MediaPort></MediaPort>"+
        "<IsAddDeviceByDomain></IsAddDeviceByDomain>" +
        "<SerialNumber>" + selectedDatas[index].SerialNumber + "</SerialNumber>" +
        "<Domain></Domain>"+
        "</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) {
             // 判断是否为最后一次请求
             if (index === selectedDatas.length - 1) {
                $("#batchModal").modal('hide');
                var statusflg = $(xmlDoc).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();
                 if (0 == statusflg) {
                    $("#searchBack,#refresh,#vmSearchTable_wrapper,#batchAdd,#searchDev").hide();
                    $("#searchDevbtn,#handAdd,#vmTable_wrapper,#videoManagementShow").show();
                    $.optionBootoast($.i18n.prop('i18n-adddev-success'), "success");
                } else {
                    $("#searchBack,#refresh,#batchAdd,#vmSearchTable_wrapper").hide();
                    $("#searchDevbtn,#handAdd,#vmTable_wrapper").show();
                    $.optionBootoast($.i18n.prop('i18n-vm-error2'), "danger");
                 }
                 if (config.isSupportDeviceCapV2 && config.deviceInfo.DeviceName == "NVR") {
                    setTimeout(function(){
                        config.deviceCapV2 = getDeviceCapV2();
                        console.log("设备能力集:", config.deviceCapV2);
                    }, 500); // 适当调整延迟时间
                }
                 dataTableDraw();
            }
        },
        error: function() {
            $.optionBootoast($.i18n.prop('i18n-addDev-fail'), "danger")
        }
    })
    }
}

