$.root_ = $('body');
$.left_panel = $('#left-panel');

/**
 * 设备能力,通道号等获取 旧设备不支持v2能力 请使用这个传入对应的通道号获取
 */
// 获取设备能力
// 获取设备能力
// 如果没有传入通道号，默认为1
function getDeviceCap(ch) {
    ch = ch || 1;
    $.ajax({
        type: "get",
        url: config.baseUrl + '/System/DeviceCap/'+ch,
        dataType: 'XML',
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function (xmlDoc) {
            var deviceCaps = {};
            deviceCaps.StreamCount = $(xmlDoc).find("StreamCount").eq(0).text() || 2; //支持的码流个数
            deviceCaps.CarDetect = $(xmlDoc).find("CarDetect").find("Support").text().toLowerCase(); //叠加人形
            deviceCaps.Human = $(xmlDoc).find("AIOverlay").find("Human").text().toLowerCase(); //叠加人形
            deviceCaps.Face = $(xmlDoc).find("AIOverlay").find("Face").text().toLowerCase(); //叠加人脸
            deviceCaps.PolygonRegion = $(xmlDoc).find("AIOverlay").find("PolygonRegion").text().toLowerCase(); //叠加布防
            deviceCaps.TraverseLine = $(xmlDoc).find("AIOverlay").find("TraverseLine").text().toLowerCase(); //叠加绊线
            deviceCaps.Car = $(xmlDoc).find("AIOverlay").find("Car").text().toLowerCase(); //叠加绊线
            deviceCaps.allOverlying = $(xmlDoc).find("AIOverlay").find("AllStreamUnity").text().toLowerCase(); //控制整个主子码流的叠加
            deviceCaps.isSupportPolygonRegion = $(xmlDoc).find("DetectRegion").find("PolygonRegion").find("Support").text().toLowerCase(); //是否支持多边行,智能警戒的能力
            deviceCaps.AudioAlarmType = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("AudioAlarmType").eq(0);
            deviceCaps.ydzcAudioAlarmType = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("MotionAlarmType").eq(0); //移动侦测
            deviceCaps.bjsrAudioAlarmType = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("AudioAlarmIn").eq(0); //报警输入
            deviceCaps.CarAudioAlarmType = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("CarAudioAlarmType").eq(0);
            deviceCaps.FaceSnapshot = $(xmlDoc).find('Device').eq(0).find("FaceFunction").eq(0).find("FaceSnapshot").eq(0).text(); //抓拍
            deviceCaps.IsFaceReco = $(xmlDoc).find('FaceFunction').eq(0).find('FaceReco').text().toLowerCase(); //识别
            deviceCaps.IsFaceLibConfig = $(xmlDoc).find('FaceFunction').eq(0).find('FaceLibConfig').text().toLowerCase(); //t5ai新加脸库能力，，有这个能力代表不支持入库
            //灯光报警联动
            deviceCaps.LightAlarm = $(xmlDoc).find('Device').eq(0).find("LightAlarm").eq(0).find("Support").eq(0).text();
            //wifi
            deviceCaps.wifiEnable = $(xmlDoc).find('WIFI').text().toLowerCase(); //是否支持wifi
            //SDK
            deviceCaps.diskEnable = $(xmlDoc).find('SD').text().toLowerCase(); //是否支持SD卡//磁盘信息与录像配置
            deviceCaps.PlaybackSpeed = $(xmlDoc).find('PlaybackSpeed').eq(0).find('Support').text().toLowerCase();
            deviceCaps.Max = parseInt($(xmlDoc).find('PlaybackSpeed').eq(0).find('Max').text().toLowerCase() == '' ? '0' : $(xmlDoc).find('PlaybackSpeed').eq(0).find('Max').text().toLowerCase());
            //宽动态能力
            deviceCaps.wdrClose = $(xmlDoc).find('Device').eq(0).find("WDR").eq(0).find("Close").eq(0).text();
            // 人脸检测
            deviceCaps.FacedetectIn = $(xmlDoc).find("FunctionListAboutChannel").find('FaceFunction').eq(0).find("FaceSnapConfig").eq(0).text();
            // 脸库管理
            deviceCaps.FaceKuoutIn = $(xmlDoc).find("FunctionListAboutChannel").find('FaceFunction').eq(0).find("FaceLibConfig").eq(0).text();
            //email联动
            deviceCaps.Email = $(xmlDoc).find('Device').eq(0).find("FunctionList").eq(0).find("Email").eq(0).text();
            //Ftp联动
            deviceCaps.Ftp = $(xmlDoc).find('Device').eq(0).find("FunctionList").eq(0).find("FTP").eq(0).text();
            deviceCaps.isSupportComplexd = $(xmlDoc).find("RejectEmptyPassword").find("Complex").text().toLowerCase();
            deviceCaps.isSupportEmptyPassword = $(xmlDoc).find("RejectEmptyPassword").find("Support").text().toLowerCase();
            //新增抗闪强度
            deviceCaps.PowerLineFrequency = $(xmlDoc).find('Device').eq(0).find('FunctionList').eq(0).find('PowerLineFrequencyStrength').eq(0).find('Support').text();
            //抗闪模式
            deviceCaps.AntiFlicker = $(xmlDoc).find('ChannelList').eq(0).find("Channel").eq(0).find('AntiFlickerMode').eq(0).find('Support').text();
            //图像模式
            deviceCaps.imageMode = $(xmlDoc).find('Device').eq(0).find('FunctionListAboutChannel').eq(0).find('ImageMode').attr("enable");
            deviceCaps.normalMode = $(xmlDoc).find('Device').eq(0).find('FunctionListAboutChannel').eq(0).find('Normal').text();
            deviceCaps.faceMode = $(xmlDoc).find('Device').eq(0).find('FunctionListAboutChannel').eq(0).find('FaceNoExposure').text();
            deviceCaps.licenseMode = $(xmlDoc).find('Device').eq(0).find('FunctionListAboutChannel').eq(0).find('LicensePlate').text();
            //osd配置
            deviceCaps.osd1linechar = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("osd1").eq(0).find("max_line_char").text();
            //osd2单行长度
            // 点阵osd
            deviceCaps.osddoit = $(xmlDoc).find("MatrixOSD").find('Support').text();
            deviceCaps.osddoitWidth = $(xmlDoc).find("MatrixOSD").find('osd1').find('Resolution').find('MaxWidth').text(); //点阵宽
            deviceCaps.osddoitHeight = $(xmlDoc).find("MatrixOSD").find('osd1').find('Resolution').find('MaxHeight').text(); //点阵高
            deviceCaps.osddoitWidth2 = $(xmlDoc).find("MatrixOSD").find('osd2').find('Resolution').find('MaxWidth').text(); //点阵宽
            deviceCaps.osddoitHeight2 = $(xmlDoc).find("MatrixOSD").find('osd2').find('Resolution').find('MaxHeight').text(); //点阵高
            // osd2 新增的能力
            deviceCaps.osdTag = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("multi_osd").text(); //是否支持多行osd
            deviceCaps.osdShowd = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("OverlayCodecParam").eq(0).find("Support").text(); //是否叠加osd的附加信息
            deviceCaps.osd2support = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("mosd_cntv2").eq(0).find("Support").text(); //是否支持osd2
            deviceCaps.odTwo = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("osd2").eq(0).find("max_char").text(); //osd2总长度
            deviceCaps.odTwol = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("osd2").eq(0).find("max_line_char").text(); //osd2单行长度
            deviceCaps.osdline = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("mosd_line_every_osd").text();
            deviceCaps.osdchar = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("mosd_char_count_every_line").text();
            deviceCaps.osd1line = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("osd1").eq(0).find("max_line").text(); //支持osd1 总共支持多少行
            deviceCaps.osd1char = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("osd1").eq(0).find("max_char").text(); //支持osd1 总字符长度
            deviceCaps.osd1MaxLineChar = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("osd1").eq(0).find("max_line_char").text() //osd1 单行支持最大字符个数
            deviceCaps.G711u = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("AudioCodec").eq(0).find("G711u").eq(0).text();
            deviceCaps.G711a = $(xmlDoc).find("FunctionListAboutChannel").eq(0).find("ChannelList").eq(0).find("Channel").eq(0).find("AudioCodec").eq(0).find("G711a").eq(0).text();
            //移动侦测 这个功能一定要 不需要能力
            deviceCaps.isMotion = $(xmlDoc).find('Motion').eq(0).find("Support").text();
            //隐私遮盖
            deviceCaps.isPrivacyZone = $(xmlDoc).find('PrivacyZone').eq(0).find("Support").text();
            //是否支持邮箱 FTP GB28181
            deviceCaps.IsSupportEmail = $(xmlDoc).find('Email').eq(0).text();
            deviceCaps.IsSupportFTP = $(xmlDoc).find('FTP').eq(0).text();
            deviceCaps.IsSupportFTP = 'false';
            deviceCaps.IsSupportGB28181 = $(xmlDoc).find('Protocol').eq(0).find("GB28181").find("Support").text();
            deviceCaps.IsSupportThirdParty = $(xmlDoc).find('Protocol').eq(0).find("ThirdParty").find("Support").text(); //是否支持第三方协议
            deviceCaps.isSupportLightCapability = $(xmlDoc).find('Device').eq(0).find('LightCapability').eq(0).find('Support').text(); //是否支持新灯板能力
            //非新灯板下的能力
            deviceCaps.colorMode = $(xmlDoc).find('Device').eq(0).find('FunctionListAboutChannel').eq(0).find('ColorNight').text();
            deviceCaps.intelligentMode = $(xmlDoc).find('Device').eq(0).find('FunctionListAboutChannel').eq(0).find('IntelligentNight').text();
            deviceCaps.variableInfrared = $(xmlDoc).find('Device').eq(0).find('FunctionListAboutChannel').eq(0).find('VariableInfrared').text();
            deviceCaps.variableWhite = $(xmlDoc).find('Device').eq(0).find('FunctionListAboutChannel').eq(0).find('VariableWhite').text();
            deviceCaps.NormalInfrared = $(xmlDoc).find('Device').eq(0).find('FunctionListAboutChannel').eq(0).find('NormalInfrared').text();
            deviceCaps.normalWhite = $(xmlDoc).find('Device').eq(0).find('FunctionListAboutChannel').eq(0).find('NormalWhite').text(); //普通红外
            deviceCaps.AlarmInCount = $(xmlDoc).find('Device').eq(0).find('AlarmInCount').text(); //报警输入个数
            deviceCaps.cruiseEnable = $(xmlDoc).find('PTZ_Advance_Cruise').text();
            //移动侦测联动如下：：：：
            //移动侦测联动 灯光报警
            deviceCaps.motionLight = $(xmlDoc).find('Device').eq(0).find('MotionLinkageFunction').eq(0).find('Light').text();
            //移动侦测联动 推送
            deviceCaps.motionPush = $(xmlDoc).find('Device').eq(0).find('MotionLinkageFunction').eq(0).find('Push').text();
            //移动侦测联动 声音报警
            deviceCaps.motionAudio = $(xmlDoc).find('Device').eq(0).find('MotionLinkageFunction').eq(0).find('Audio').text();
            //移动侦测联动 FTP
            deviceCaps.motionFtp = $(xmlDoc).find('Device').eq(0).find('MotionLinkageFunction').eq(0).find('FTP').text();
            //移动侦测联动 报警输出
            deviceCaps.motionAlarmOut = $(xmlDoc).find('Device').eq(0).find('MotionLinkageFunction').eq(0).find('AlarmOut').text();
            //移动侦测联动 邮件
            deviceCaps.motionEmail = $(xmlDoc).find('Device').eq(0).find('MotionLinkageFunction').eq(0).find('Email').text();
            // deviceCap.motionSD = $(xmlDoc).find('Device').eq(0).find('MotionLinkageFunction').eq(0).find('SD').text();
            //配置项目 ddns
            deviceCaps.ddns = $(xmlDoc).find('Device').eq(0).find("FunctionList").eq(0).find('WebUI').eq(0).find('Network').eq(0).find('DDNS').eq(0).text();
            //侧边栏 人形检测
            deviceCaps.HumanShape = $(xmlDoc).find('Device').eq(0).find("HumanShape").eq(0).find("Support").text().toLowerCase();
            deviceCaps.cloudUpgrade = $(xmlDoc).find('Device').eq(0).find("cloud_upgrade").eq(0).text().toLowerCase();
            //NTP时间立即同步
            deviceCaps.NtpTimeSync = $(xmlDoc).find("NtpTimeSync").eq(0).text();
            // 曝光时间是否支持设置
            deviceCaps.ExposureTime =$(xmlDoc).find("ExposureTime").find("Support").text().toLowerCase();
            // 曝光时间选项
            deviceCaps.ExposureTimeList = $(xmlDoc).find("ExposureTime").find("Option").text();
            deviceCaps.wdrClose = $(xmlDoc).find("WDR").eq(0).find("Close").eq(0).text();
            deviceCaps.Defrog = $(xmlDoc).find("Defrog").eq(0).find('Support').text()
            //图形镜像

            // 将设备能力信息存储到数组的ch-1位置
            config.deviceCapV1[ch-1] = deviceCaps;
        },
        error: function(data) {}
    });
    console.log(config.deviceCapV1,'deviceCapV111111111111111');

    return config.deviceCapV1
}
function getDeviceCapV2() {
    var deviceCapV2 = [];
    $.ajax({
        type: "get",
        url: config.baseUrl + '/System/DeviceCapV2',
        dataType: 'XML',
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function (xmlDoc) {
            if ($(xmlDoc).find('ResponseStatus').eq(0).find('statusCode').eq(0).text()) { 
                return;
            }
            config.isSupportDeviceCapV2 = true;
            var deviceCaps = {};
            var channelList = $(xmlDoc).find("FunctionListAboutChannel > ChannelList").first();
            var channels = channelList.children("Channel");
            for (var o = 0; o < channels.length; o++) {
                var channel = channels.eq(o);
                var deviceCaps = {};
                // 请后续开发人员注意，严格根据xml结构一层一层找（需根据实际XML结构调整路径）
                deviceCaps.StreamCount = channel.find("StreamCount").eq(0).text() || 2; //支持的码流个数
                deviceCaps.CarDetect = channel.find('FunctionList').eq(0).find("CarDetect").eq(0).find("Support").text().toLowerCase(); //叠加人形
                deviceCaps.Human = channel.find("AIOverlay").find("Human").text().toLowerCase(); //叠加人形
                deviceCaps.Face = channel.find("AIOverlay").find("Face").text().toLowerCase(); //叠加人脸
                deviceCaps.PolygonRegion = channel.find("AIOverlay").find("PolygonRegion").text().toLowerCase(); //叠加布防
                deviceCaps.TraverseLine = channel.find("AIOverlay").find("TraverseLine").text().toLowerCase(); //叠加绊线
                deviceCaps.Car = channel.find("AIOverlay").find("Car").text().toLowerCase(); //叠加绊线
                deviceCaps.allOverlying = channel.find('FunctionList').eq(0).find("AIOverlay").eq(0).find("AllStreamUnity").text().toLowerCase(); //控制整个主子码流的叠加
                deviceCaps.isSupportPolygonRegion = channel.find("DetectRegion").find("PolygonRegion").find("Support").text().toLowerCase(); //是否支持多边行,智能警戒的能力
                deviceCaps.AudioAlarmType = channel.find("AudioAlarmType").eq(0);
                deviceCaps.ydzcAudioAlarmType = channel.find("MotionAlarmType").eq(0); //移动侦测
                deviceCaps.bjsrAudioAlarmType = channel.find("AudioAlarmIn").eq(0); //报警输入
                deviceCaps.CarAudioAlarmType = channel.find("CarAudioAlarmType").eq(0);
                deviceCaps.FaceSnapshot = channel.find("FaceFunction").eq(0).find("FaceSnapshot").eq(0).text(); //抓拍
                deviceCaps.IsFaceReco = channel.find('FaceFunction').eq(0).find('FaceReco').text().toLowerCase(); //识别
                deviceCaps.IsFaceLibConfig =channel.find('FaceFunction').eq(0).find('FaceLibConfig').text().toLowerCase(); //t5ai新加脸库能力，，有这个能力代表不支持入库
                //灯光报警联动
                deviceCaps.LightAlarm = channel.eq(0).find('FunctionList').eq(0).find('Alarm').eq(0).find("LightAlarm").eq(0).find("Support").eq(0).text();
                //wifi
                deviceCaps.wifiEnable = channel.find('FunctionList').eq(0).find('WIFI').text().toLowerCase(); //是否支持wifi
                //SDK
                deviceCaps.diskEnable = channel.find('FunctionList').eq(0).find('SD').text().toLowerCase(); //是否支持SD卡//磁盘信息与录像配置
                deviceCaps.PlaybackSpeed = channel.find('PlaybackSpeed').eq(0).find('Support').text().toLowerCase();
                deviceCaps.Max = parseInt(channel.find('PlaybackSpeed').eq(0).find('Max').text().toLowerCase() == '' ? '0' : $(xmlDoc).find('PlaybackSpeed').eq(0).find('Max').text().toLowerCase());
                //宽动态能力
                deviceCaps.wdrClose = channel.find('FunctionList').eq(0).find("WDR").eq(0).find("Close").eq(0).text();
                deviceCaps.Defrog = channel.find('FunctionList').eq(0).find("Defrog").eq(0).find('Support').text()
                // 人脸检测
                deviceCaps.FacedetectIn = channel.find("FunctionList").find('FaceFunction').eq(0).find("FaceSnapConfig").eq(0).text();
                // 脸库管理
                deviceCaps.FaceKuoutIn = channel.find("FunctionList").find('FaceFunction').eq(0).find("FaceLibConfig").eq(0).text();
                //email联动
                deviceCaps.Email = channel.find("FunctionList").eq(0).find("Email").eq(0).text();
                //Ftp联动
                deviceCaps.Ftp = channel.find("MotionLinkageFunction").eq(0).find("FTP").eq(0).text();
                deviceCaps.isSupportComplexd = channel.find("RejectEmptyPassword").find("Complex").text().toLowerCase();
                deviceCaps.isSupportEmptyPassword = channel.find("RejectEmptyPassword").find("Support").text().toLowerCase();
                //新增抗闪强度
                deviceCaps.PowerLineFrequency = channel.find('PowerLineFrequencyStrength').eq(0).find('Support').text();
                //图像模式
                deviceCaps.imageMode = channel.find('FunctionListAboutChannel').eq(0).find('ImageMode').eq(0).attr("enable");
                deviceCaps.normalMode = channel.find('FunctionListAboutChannel').eq(0).find('ImageMode').eq(0).find('Normal').text();
                deviceCaps.faceMode = channel.find('FunctionListAboutChannel').eq(0).find('ImageMode').eq(0).find('FaceNoExposure').text();
                deviceCaps.licenseMode = channel.find('FunctionListAboutChannel').eq(0).find('ImageMode').eq(0).find('LicensePlate').text();
                //osd配置
                deviceCaps.osdTag = channel.find("FunctionListAboutChannel").eq(0).find("multi_osd").text();
                deviceCaps.osd1linechar = channel.find("FunctionListAboutChannel").eq(0).find("osd1").eq(0).find("max_line_char").text();
                //osd2单行长度
                deviceCaps.odTwol = channel.find("FunctionListAboutChannel").eq(0).find("osd2").eq(0).find("max_line_char").text(); //osd2单行长度
                // 点阵osd
                deviceCaps.osddoit = channel.find("FunctionListAboutChannel").eq(0).find("MatrixOSD").find('Support').text();
                deviceCaps.osddoitWidth = channel.find("FunctionListAboutChannel").eq(0).find("MatrixOSD").find('osd1').find('Resolution').find('MaxWidth').text(); //点阵宽
                deviceCaps.osddoitHeight = channel.find("FunctionListAboutChannel").eq(0).find("MatrixOSD").find('osd1').find('Resolution').find('MaxHeight').text(); //点阵高
                deviceCaps.osddoitWidth2 = channel.find("FunctionListAboutChannel").eq(0).find("MatrixOSD").find('osd2').find('Resolution').find('MaxWidth').text(); //点阵宽
                deviceCaps.osddoitHeight2 = channel.find("FunctionListAboutChannel").eq(0).find("MatrixOSD").find('osd2').find('Resolution').find('MaxHeight').text(); //点阵高
                // osd2 新增的能力
                deviceCaps.osdShowd = channel.find('FunctionListAboutChannel').eq(0).find("OverlayCodecParam").eq(0).find("Support").text(); //是否叠加osd的附加信息
                deviceCaps.osd2support = channel.find("FunctionListAboutChannel").eq(0).find("mosd_cntv2").eq(0).find("Support").text(); //是否支持osd2
                deviceCaps.odTwo = channel.find("FunctionListAboutChannel").eq(0).find("osd2").eq(0).find("max_char").text(); //osd2总长度
                deviceCaps.osdline = channel.find("FunctionListAboutChannel").eq(0).find("mosd_line_every_osd").text();
                deviceCaps.osdchar =channel.find("FunctionListAboutChannel").eq(0).find("mosd_char_count_every_line").text();
                deviceCaps.osd1line = channel.find("FunctionListAboutChannel").eq(0).find("osd1").eq(0).find("max_line").text(); //支持osd1 总共支持多少行
                deviceCaps.osd1char = channel.find("FunctionListAboutChannel").eq(0).find("osd1").eq(0).find("max_char").text(); //支持osd1 总字符长度
                deviceCaps.osd1MaxLineChar = channel.find("FunctionListAboutChannel").eq(0).find("osd1").eq(0).find("max_line_char").text() //osd1 单行支持最大字符个数
                deviceCaps.osd2line = channel.find("FunctionListAboutChannel").eq(0).find("osd2").eq(0).find("max_line").text(); //支持osd2 总共支持多少行
                deviceCaps.G711u = channel.find("FunctionListAboutChannel").eq(0).find("AudioCodec").eq(0).find("G711u").eq(0).text();
                deviceCaps.G711a = channel.find("FunctionListAboutChannel").eq(0).find("AudioCodec").eq(0).find("G711a").eq(0).text();
                //移动侦测 这个功能一定要 不需要能力
                deviceCaps.isMotion = channel.find('Motion').eq(0).find("Support").text();
                //隐私遮盖
                deviceCaps.isPrivacyZone = channel.find('PrivacyZone').eq(0).find("Support").text();
                //是否支持邮箱 FTP GB28181
                deviceCaps.IsSupportEmail = channel.find('FunctionList').eq(0).find('Email').eq(0).text();
                deviceCaps.IsSupportFTP = channel.find('FunctionList').eq(0).find('FTP').eq(0).text();
                deviceCaps.IsSupportGB28181 = channel.find('Protocol').eq(0).find("GB28181").find("Support").text();
                deviceCaps.IsSupportThirdParty =channel.find('Protocol').eq(0).find("ThirdParty").find("Support").text(); //是否支持第三方协议
                deviceCaps.isSupportLightCapability = channel.find('LightCapability').eq(0).find('Support').text(); //是否支持新灯板能力
                // 非新灯板下的能力
                deviceCaps.colorMode = channel.find('FunctionListAboutChannel').eq(0).find('ColorNight').text();
                deviceCaps.intelligentMode = channel.find('FunctionListAboutChannel').eq(0).find('IntelligentNight').text();
                deviceCaps.variableInfrared = channel.find('FunctionListAboutChannel').eq(0).find('VariableInfrared').text();
                deviceCaps.variableWhite = channel.find('FunctionListAboutChannel').eq(0).find('VariableWhite').text();
                deviceCaps.NormalInfrared = channel.find('FunctionListAboutChannel').eq(0).find('NormalInfrared').text();
                deviceCaps.normalWhite = channel.find('FunctionListAboutChannel').eq(0).find('NormalWhite').text(); //普通红外
                deviceCaps.AlarmInCount = channel.find('AlarmInCount').text(); //报警输入个数
                deviceCaps.cruiseEnable = channel.find('PTZ_Advance_Cruise').text();
                //移动侦测联动如下：：：：
                //移动侦测联动 灯光报警
                deviceCaps.motionLight = channel.find('MotionLinkageFunction').eq(0).find('Light').text();
                //移动侦测联动 推送
                deviceCaps.motionPush = channel.find('MotionLinkageFunction').eq(0).find('Push').text();
                //移动侦测联动 声音报警
                deviceCaps.motionAudio = channel.find('MotionLinkageFunction').eq(0).find('Audio').text();
                //移动侦测联动 FTP
                deviceCaps.motionFtp = channel.find('MotionLinkageFunction').eq(0).find('FTP').text();
                //移动侦测联动 报警输出
                deviceCaps.motionAlarmOut = channel.find('MotionLinkageFunction').eq(0).find('AlarmOut').text();
                //移动侦测联动 邮件
                deviceCaps.motionEmail = channel.find('MotionLinkageFunction').eq(0).find('Email').text();
                //配置项目 ddns
                deviceCaps.ddns = channel.find('WebUI').eq(0).find('Network').eq(0).find('DDNS').eq(0).text();
                //侧边栏 人形检测
                deviceCaps.HumanShape = channel.find("HumanShape").eq(0).find("Support").text().toLowerCase();
                deviceCaps.cloudUpgrade = channel.find("cloud_upgrade").eq(0).text().toLowerCase();
                //NTP时间立即同步
                deviceCaps.NtpTimeSync = channel.find("NtpTimeSync").eq(0).text();
                 // 曝光时间是否支持设置
                 deviceCaps.ExposureTime =channel.find("ExposureTime").find("Support").text().toLowerCase();
                 // 曝光时间选项
                deviceCaps.ExposureTimeList = channel.find("ExposureTime").find("Option").text();
                console.log(deviceCaps.ExposureTimeList,'曝光时间选项');
                
                deviceCaps.AntiFlicker = channel.find('AntiFlickerMode').eq(0).find('Support').text();
                deviceCapV2.push(deviceCaps);
            }
        },
        error: function (data) {
            config.isSupportDeviceCapV2 = false;
        }
    });
    console.log(deviceCapV2, 'deviceCapV2');
    if (deviceCapV2.length == 0) { 
        config.isSupportDeviceCapV2 = false;
    }
    return deviceCapV2
}

/**
 * Mac地址获取
 */
function getMacAddress() {
    var MacAddress;
    $.ajax({
        type: "get",
        url: config.baseUrl + '/Network/Interfaces',
        dataType: 'XML',
        timeout: 15000,
        async: false,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(data) {
            MacAddress = $(data).find('InterfaceList').find('Interface').eq(0).find('MacAddress').eq(0).text();

        },
        error: function(data) {}
    });
    return MacAddress;
}


/**
 * 网络端口号获取
 */
function getHTTPprot() {
    var Network = {};
    $.ajax({
        type: "get",
        url: config.baseUrl + '/Network/Port',
        dataType: 'XML',
        timeout: 15000,
        async: false,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(data) {
            Network.HTTPprot = $(data).find('Port').eq(0).find('HTTP').eq(0).text();
            Network.commandPort = $(data).find('Port').eq(0).find('Command').eq(0).text();
            Network.mediaPort = $(data).find('Port').eq(0).find('Media').eq(0).text();
            Network.rtspPort = $(data).find('Port').eq(0).find('RTP').eq(0).text();
        },
        error: function(data) {}
    });
    return Network;
}

function enablePush() { //联动 触发推送
    var isPush = false;
    $.ajax({
        url: config.baseUrl + "/Network/P2PV2",
        type: "get",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            var uid = $(xmlDoc).find('P2P').eq(0).find('UUID').eq(0).text();
            isPush = uid.indexOf("#") !== -1;
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
    return isPush;
}


/**
 * 设备AI能力获取
 */
// 获取设备AI能力
function getdeviceAiCap() {
    // 定义一个空对象，用于存储设备AI能力
    var deviceAiCap = [];
    // 发起ajax请求，获取设备AI能力
    $.ajax({
        type: "get",
        url: config.baseUrl + '/System/AICap',
        dataType: 'XML',
        timeout: 15000,
        async: false,
        beforeSend: function(xhr) {
            // 设置请求头，防止缓存
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function (xmlDoc) {
            var deviceAiCaps = {};
            //客流统计查询
            deviceAiCaps.passengerFlow = $(xmlDoc).find("SmartDetect").find("PassengerFlowStatisticsQuery").text().toLowerCase();
            //电子围栏检测目标目标中的车型
            deviceAiCaps.Electcar = $(xmlDoc).find("SmartDetect").find("ElectronicFence").find('DetectTarget').find("car").text().toLowerCase();
            //电子围栏目标检测目标目标中的人型
            deviceAiCaps.Electhumn = $(xmlDoc).find("SmartDetect").find("ElectronicFence").find('DetectTarget').find("human").text().toLowerCase();
            // 电子围栏背景图推送
            deviceAiCaps.elBackgroundImages = $(xmlDoc).find("SmartDetect").find("ElectronicFence").find('BackgroundImage').find("Support").text().toLowerCase();
            // 电子围栏显示警戒线
            deviceAiCaps.Wroningfram = $(xmlDoc).find("SmartDetect").find("ElectronicFence").find('OverlayArea').text();
            // 电子围栏显示目标框
            deviceAiCaps.TargetFrame = $(xmlDoc).find("SmartDetect").find("ElectronicFence").find('OverlayObject').text();
            // 越界侦测目标车型
            deviceAiCaps.Travercar = $(xmlDoc).find("SmartDetect").find("TraversePlane").find('DetectTarget').find("car").text().toLowerCase();
            // 越界侦测目标人型
            deviceAiCaps.Traverhumn = $(xmlDoc).find("SmartDetect").find("TraversePlane").find('DetectTarget').find("human").text().toLowerCase();
            // 越界侦测背景图推送
            deviceAiCaps.trBackgroundImages = $(xmlDoc).find("SmartDetect").find("TraversePlane").find('BackgroundImage').find("Support").text().toLowerCase();
            // 越界侦测显示警戒线
            deviceAiCaps.trWroningfram = $(xmlDoc).find("SmartDetect").find("TraversePlane").find('OverlayArea').text();
            // 越界侦测显示目标框
            deviceAiCaps.trTargetFrame = $(xmlDoc).find("SmartDetect").find("TraversePlane").find('OverlayObject').text();

            // 语音报警车型
            deviceAiCaps.Carsupport = $(xmlDoc).find("AudioAlarmType").find("ForCar").find("support").text().toLowerCase();
            // 语音报警人形
            deviceAiCaps.Peoplesupport = $(xmlDoc).find("AudioAlarmType").find("ForHuman").find("support").text().toLowerCase();
            //客流统计叠加
            deviceAiCaps.PassengerFlowOverlay = $(xmlDoc).find("SmartDetect").find("PassengerFlowStatisticsOverlay").text().toLowerCase();
            deviceAiCaps.Electronsupport = $(xmlDoc).find("SmartDetect").find("ElectronicFence").find('support').text().toLowerCase();
            //越界侦测
            deviceAiCaps.Traversesupport = $(xmlDoc).find("SmartDetect").find("TraversePlane").find('support').text().toLowerCase();
            //离岗侦测
            deviceAiCaps.OffDetectsupport = $(xmlDoc).find("SmartDetect").find("OffDutyDetect").find('support').text().toLowerCase();
            // 离岗侦测显示警戒线
            deviceAiCaps.offWroningfram = $(xmlDoc).find("SmartDetect").find("OffDutyDetect").find('OverlayArea').text();
            // 离岗侦测显示目标框
            deviceAiCaps.offTargetFrame = $(xmlDoc).find("SmartDetect").find("OffDutyDetect").find('OverlayObject').text();
            // 离岗侦测背景图推送
            deviceAiCaps.offBackgroundImages = $(xmlDoc).find("SmartDetect").find("OffDutyDetect").find('BackgroundImage').find("Support").text().toLowerCase();
            //客流统计
            deviceAiCaps.PassengerFlowsupport = $(xmlDoc).find("SmartDetect").find("PassengerFlowStatics").find('support').text().toLowerCase();
            // 客流统计背景图推送
            deviceAiCaps.PasBackgroundImages = $(xmlDoc).find("SmartDetect").find("PassengerFlowStatics").find('BackgroundImage').find("Support").text().toLowerCase();
            // 火焰检测
            deviceAiCaps.Firedetectsupport = $(xmlDoc).find("FireDetect").find('support').text().toLowerCase();
            // 火焰声音类型
            deviceAiCaps.FiredetectAudioType = $(xmlDoc).find("AudioAlarmType").find('ForFire').eq(0).find("AudioType").eq(0);
            // 客流统计区域限制
            deviceAiCaps.LeftTopX = $(xmlDoc).find("SmartDetect").find("PassengerFlowStatics").find('MaxManagerRegion').find('LeftTopX').text();
            deviceAiCaps.LeftTopY = $(xmlDoc).find("SmartDetect").find("PassengerFlowStatics").find('MaxManagerRegion').find('LeftTopY').text();
            deviceAiCaps.RightBottomX = $(xmlDoc).find("SmartDetect").find("PassengerFlowStatics").find('MaxManagerRegion').find('RightBottomX').text();
            deviceAiCaps.RightBottomY = $(xmlDoc).find("SmartDetect").find("PassengerFlowStatics").find('MaxManagerRegion').find('RightBottomY').text();
            //电子围栏声音类型
            deviceAiCaps.electronVoicetype = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForElectronicFence').eq(0).find('support').eq(0).text();
            deviceAiCaps.dzwlaudioVoicetype = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForElectronicFence').eq(0).find('AudioType').eq(0);
            //电子围栏音量
            deviceAiCaps.elevoicelume = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForElectronicFence').eq(0).find('AudioVolume').eq(0).text();
            //越界侦测声音类型
            deviceAiCaps.crossVoicetype = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForTraversePlane').eq(0).find('support').eq(0).text();
            deviceAiCaps.yjzcaudioVoicetype = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForTraversePlane').eq(0).find('AudioType').eq(0);
            //越界侦测音量
            deviceAiCaps.crossvoicelume = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForTraversePlane').eq(0).find('AudioVolume').eq(0).text();
            //离岗侦测声音类型
            deviceAiCaps.offdutyVoicetype = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForOffDutyDetect').eq(0).find('support').eq(0).text();
            deviceAiCaps.lgjcaudioVoicetype = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForOffDutyDetect').eq(0).find('AudioType').eq(0);
            //越界侦测音量
            deviceAiCaps.offvoicelume = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForOffDutyDetect').eq(0).find('AudioVolume').eq(0).text();
            //视频遮挡生意类型
            deviceAiCaps.spzdaudioisShow = $(xmlDoc).find('VideoShelter').eq(0).find('support').eq(0).text();
            deviceAiCaps.spzdaudioVoicetype = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForVideoShelter').eq(0).find('AudioType').eq(0);
            // 人脸检测声音类型
            deviceAiCaps.forfaceVoicetype = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForFace').eq(0).find('AudioType').eq(0);
            // 口罩检测声音类型
            deviceAiCaps.formaskVoicetype = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForMask').eq(0).find('AudioType').eq(0);
            // 口罩检测
            deviceAiCaps.formaskSupport = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForMask').eq(0).find('support').eq(0);
            //客流统计声音类型
            deviceAiCaps.flowpesupport = $(xmlDoc).find("AudioAlarmType").eq(0).find('PassengerEnter').eq(0).find('support').eq(0).text().toLowerCase();
            deviceAiCaps.flowenAudioType = $(xmlDoc).find("AudioAlarmType").eq(0).find('PassengerEnter').eq(0).find('AudioType').eq(0);
            //客流音量
            deviceAiCaps.flowvoicelume = $(xmlDoc).find("AudioAlarmType").eq(0).find('PassengerEnter').eq(0).find('AudioVolume').eq(0).text();
            deviceAiCaps.flowlesupport = $(xmlDoc).find("AudioAlarmType").eq(0).find('PassengerLeave').eq(0).find('Support').eq(0).text().toLowerCase();
            deviceAiCaps.flowleAudioType = $(xmlDoc).find("AudioAlarmType").eq(0).find('PassengerLeave').eq(0).find('AudioType').eq(0);
            //算法仓库
            deviceAiCaps.isSupportAlgorithmWarehouse = $(xmlDoc).find("AlgorithmWarehouse").eq(0).find("support").eq(0).text().toLowerCase();
            //人脸抓拍
            deviceAiCaps.algorithmFaceSnap = $(xmlDoc).find("AlgorithmWarehouse").eq(0).find('FaceSnap').eq(0).find('support').eq(0);
            //人脸音量
            deviceAiCaps.facevoicelume = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForFace').eq(0).find('AudioVolume').eq(0).text();
            //口罩音量
            deviceAiCaps.maskvoicelume = $(xmlDoc).find("AudioAlarmType").eq(0).find('ForMask').eq(0).find('AudioVolume').eq(0).text();
            //声音报警控制
            deviceAiCaps.ControlModeText = $(xmlDoc).find("AudioAlarmType").eq(0).find('ControlMode').eq(0).text();

            //人脸识别
            deviceAiCap.algorithmFaceReco = $(xmlDoc).find("AlgorithmWarehouse").eq(0).find('FaceReco').eq(0).find('support').eq(0);
            // 智能跟踪
            deviceAiCaps.IntelligentTracksuport = $(xmlDoc).find("SmartDetect").find("ObjectTrack").find('support').text().toLowerCase();
            // 智能跟踪目标人形车型
            deviceAiCaps.IntelligentTrackdectecCar = $(xmlDoc).find("SmartDetect").find("ObjectTrack").find("DetectTarget").find("car").eq(0).text().toLowerCase()
            deviceAiCaps.IntelligentTrackdectecHuman = $(xmlDoc).find("SmartDetect").find("ObjectTrack").find("DetectTarget").find("human").eq(0).text().toLowerCase()
            deviceAiCap.push(deviceAiCaps);
            
        },
        error: function(data) {}
    });
    return deviceAiCap
}



/**
 * 设备信息获取
 */
function getDeviceInfo() {
    var deviceInfo = {};
    $.ajax({
        type: "get",
        url: config.baseUrl + '/System/DeviceInfo',
        dataType: 'XML',
        timeout: 15000,
        async: false,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc) {
            if (URL_Request("isp2p") != "p2p" && URL_Request("isp2p") != "p6s") { //非vms
                var ProductType = $(xmlDoc).find('DeviceInfo').eq(0).find('ProductType').eq(0).text();
                if (ProductType) {
                    deviceInfo.DeviceName = ProductType;
                } else {
                    var deviceNameReult = $(xmlDoc).find('DeviceInfo').eq(0).find('DeviceTypeName').eq(0).text();
                    if (deviceNameReult.charAt(0) == "N") {
                        deviceInfo.DeviceName = "NVR";
                    } else if (deviceNameReult.substr(0, 3) == "AHB") {
                        deviceInfo.DeviceName = "HVR";
                    } else {
                        deviceInfo.DeviceName = "IPC";
                    }
                }
            } else {
                deviceInfo.DeviceName = window.deviceType;
            }
            deviceInfo.NameForDevice = $(xmlDoc).find('DeviceInfo').eq(0).find('DeviceName').eq(0).text();
            deviceInfo.AlarmOutputChannels = $(xmlDoc).find('DeviceInfo').eq(0).find('AlarmOutputChannels').eq(0).text();
            deviceInfo.DeviceTypeName = $(xmlDoc).find('DeviceInfo').eq(0).find('DeviceTypeName').eq(0).text();
            deviceInfo.TwoWayAudio = $(xmlDoc).find('DeviceInfo').eq(0).find('TwoWayAudio').eq(0).text();
            deviceInfo.AlarmInputChannels = $(xmlDoc).find('DeviceInfo').eq(0).find('AlarmInputChannels').eq(0).text();
            deviceInfo.DeviceTypeName = $(xmlDoc).find('DeviceInfo').eq(0).find('DeviceTypeName').eq(0).text();
            deviceInfo.SerialNum = $(xmlDoc).find('DeviceInfo').eq(0).find('SerialNum').eq(0).text();
            deviceInfo.SoftWareVersion = $(xmlDoc).find('DeviceInfo').eq(0).find('SoftWareVersion').eq(0).text();
            // 总通道数
            deviceInfo.VideoInputChannels = $(xmlDoc).find('DeviceInfo').eq(0).find('VideoInputChannels').eq(0).text();
            deviceInfo.AudioChannels = $(xmlDoc).find('DeviceInfo').eq(0).find('AudioChannels').eq(0).text();
            deviceInfo.TwoWayAudi = $(xmlDoc).find('DeviceInfo').eq(0).find('TwoWayAudio').eq(0).text();
        },
        error: function(data) {}
    });
    return deviceInfo
}


/**
 * 设备状态分辨率获取
 */
function getBitrate(chn) {
    chn = chn || 1
    var bitrate = {};
    $.ajax({
        type: "get",
        url: config.baseUrl + '/System/DeviceStatus/' + chn,
        dataType: 'XML',
        timeout: 15000,
        async: false,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc) {
            bitrate.MainBitrate = $(xmlDoc).find('DeviceStatus').eq(0).find('MainStreamVideoBitrate').eq(0).text();
            bitrate.FirstBitrate = $(xmlDoc).find('DeviceStatus').eq(0).find('FirstSubStreamVideoBitrate').eq(0).text();
            bitrate.SecondBitrate = $(xmlDoc).find('DeviceStatus').eq(0).find('SecondSubStreamVideoBitrate').eq(0).text();
        },
        error: function(data) {}
    });
    return bitrate
}

/**********************************
 功能: 登陆
 ***********************************/
function Login() {
    config.isSupportUserAuthV2 = false;
    var nonce = generateNonce();
    var created = generateTimestamp();
    // 计算密码摘要
    var passwordDigest = calculatePasswordDigest(nonce, created, config.password);
    if (!passwordDigest) {
        console.log('生成密码摘要失败');
        return false;
    }
    var cyDate = '<Security>' +
                 '<Username>' + config.user + '</Username>' +
                 '<Password>' + passwordDigest + '</Password>' +
                 '<Nonce>' + nonce + '</Nonce>' +
                 '<Created>' + created + '</Created>' +
                 '</Security>';
    console.log('发送的XML:', cyDate);
    $.ajax({
        url: config.baseUrl + "/Security/UserAuthV2",
        type: "PUT",
        timeout: 15000,
        async: false,
        data: cyDate,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            config.isSupportUserAuthV2 = true;
            var statusflg = $(xmlDoc).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();

            if (0 == statusflg) { //成功登陆
                loginLoad();
            } else if (statusflg == "-25") {
                $.optionBootoast($.i18n.prop("i18n-default-msg12"), 'danger');
                return false;
            } else if (-17 == statusflg) { //密码出错
                $.optionBootoast($.i18n.prop("i18n-default-msg13"), 'danger');
                return false;
            } else if ("401" != xhr.status) { //其它异常
                if ("timeout" == textStatus) { //连接超时
                    $.optionBootoast($.i18n.prop("i18n-default-msg14"), 'danger')
                } else { //网络异常
                    $.optionBootoast($.i18n.prop("i18n-default-msg15"), 'danger')
                }
                return false;
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            config.isSupportUserAuthV2 = false;
            userAuths();
            return false;
        }
    });

}
function userAuths(){
    var cyDate = 'Username=' + config.user + '&Password=' + config.password;
    $.ajax({
        url: config.baseUrl + "/Security/UserAuth",
        type: "PUT",
        timeout: 15000,
        async: false,
        data: cyDate,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            var statusflg = $(xmlDoc).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();

            if (0 == statusflg) { //成功登陆
                loginLoad();
            } else if (statusflg == "-25") {
                $.optionBootoast($.i18n.prop("i18n-default-msg12"), 'danger');
                return false;
            } else if (-17 == statusflg) { //密码出错
                $.optionBootoast($.i18n.prop("i18n-default-msg13"), 'danger');
                return false;
            } else if ("401" != xhr.status) { //其它异常
                if ("timeout" == textStatus) { //连接超时
                    $.optionBootoast($.i18n.prop("i18n-default-msg14"), 'danger')
                } else { //网络异常
                    $.optionBootoast($.i18n.prop("i18n-default-msg15"), 'danger')
                }
                return false;
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            $.optionBootoast($.i18n.prop("i18n-default-msg16"), 'danger');
            return false;
        }
    });
}
// 生成随机 Nonce (16字节)
function generateNonce() {
    var randomBytes = new Uint8Array(16);
    if (window.crypto && window.crypto.getRandomValues) {
        window.crypto.getRandomValues(randomBytes);
    } else {
        for (var i = 0; i < 16; i++) {
            randomBytes[i] = Math.floor(Math.random() * 256);
        }
    }
    
    var randomStr = '';
    for (var i = 0; i < randomBytes.length; i++) {
        randomStr += String.fromCharCode(randomBytes[i]);
    }
    
    return btoa(randomStr);
}

// 生成 ISO 格式的时间戳
function generateTimestamp() {
    return new Date().toISOString();
}

// 使用 crypto-js 计算密码摘要
function calculatePasswordDigest(nonce, created, password) {
    try {
        // 2. 拼接数据：Nonce + Created + Password
        var dataToHash = nonce + created + password;
        console.log(password,'password');
        console.log(nonce,'nonce');
        console.log(created,'created');
        
        // 3. 使用 crypto-js 计算 SHA1
        var sha1Hash = CryptoJS.SHA1(dataToHash);
        console.log(sha1Hash,'sha1Hashsha1Hashsha1Hashsha1Hash');
        // 4. 转换为 Base64
        return CryptoJS.enc.Base64.stringify(sha1Hash);
        
    } catch (error) {
        console.error('计算密码摘要错误:', error);
        return null;
    }
}
function loginLoad() {
    $.ajax({
        url: config.baseUrl + "/Network/Port",
        type: "GET",
        async: false,
        username: config.user,
        password: config.password,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            //仅仅针对vms
            var m_cyUserPwdValue = Base64.encode(config.user + ":" + config.password);
            $.cookie('userInfo', m_cyUserPwdValue);
            config.MacAddress = getMacAddress(); //mac地址
            // config.Network = getHTTPprot(); //网络端口号
            config.Network.HTTPprot = $(xmlDoc).find('Port').eq(0).find('HTTP').eq(0).text();
            config.Network.commandPort = $(xmlDoc).find('Port').eq(0).find('Command').eq(0).text();
            config.Network.mediaPort = $(xmlDoc).find('Port').eq(0).find('Media').eq(0).text();
            config.Network.rtspPort = $(xmlDoc).find('Port').eq(0).find('RTP').eq(0).text();
            config.deviceInfo = getDeviceInfo(); //设备信息获取
            config.deviceAiCap = getdeviceAiCap(); //ai能力
            if (window.deviceType == "IPC") {
                config.deviceCap = getDeviceCap(); //设备能力
            } else {
                config.deviceCapV1=[];
                for (let i = 0; i < config.deviceInfo.VideoInputChannels; i++) {
                    config.deviceCapV1.push(null);
                }
                config.deviceCap = getDeviceCap(1); //设备能力
            }
            if (config.deviceInfo.DeviceName == "NVR") {
                config.deviceCapV2 = getDeviceCapV2(); //设备能力
            } 
            config.bitrate = getBitrate(); //设备状态分辨率获取
            config.playMode = getplayMode(); //播放模式数组获取

        },
        error: function(xhr, textStatus, errorThrown) {
            if ("401" != xhr.status) {
                if ("timeout" == textStatus) { //连接超时
                    $.optionBootoast($.i18n.prop("i18n-default-msg14"), 'danger')
                } else { //网络异常
                    $.optionBootoast($.i18n.prop("i18n-default-msg15"), 'danger')
                }
            } else {
                $.optionBootoast($.i18n.prop("i18n-default-msg13"), 'danger')
            }
            return false; //阻止表单提交
        }
    });
}

/**
 * easyvideo返回码翻译
 * @param code
 */
function easyerrortranslation(code) {
    var tiptitle = "";
    if (code == 1000) {
        tiptitle = $.i18n.prop('i18n-parametererror');
    } else if (code == 1001) {
        tiptitle = $.i18n.prop('i18n-unsupportedOperations');
    } else if (code == 1002) {
        tiptitle = $.i18n.prop('i18n-outmemory');
    } else if (code == 1003) {
        tiptitle = $.i18n.prop('i18n-Invalidparameter');
    } else if (code == 1004) {
        tiptitle = $.i18n.prop('i18n-servernotinitialized');
    } else if (code == 1005) {
        tiptitle = $.i18n.prop('i18n-internalerror');
    } else if (code == 1006) {
        tiptitle = $.i18n.prop('i18n-unrealized');
    } else if (code == 1007) {
        tiptitle = $.i18n.prop('i18n-Networkerror');
    } else if (code == 1008) {
        tiptitle = $.i18n.prop('i18n-Serverbusy');
    } else if (code == 1009) {
        tiptitle = $.i18n.prop('i18n-Callsequenceerror');
    } else if (code == 1011) {
        tiptitle = $.i18n.prop('i18n-diskspace');
    } else if (code == 1012) {
        tiptitle = $.i18n.prop('i18n-Equipmentbusy');
    } else if (code == 1013) {
        tiptitle = $.i18n.prop('i18n-Unknownerror');
    } else if (code == 1014) {
        tiptitle = $.i18n.prop('i18n-Connectiontimeout');
    } else if (code == 1015) {
        tiptitle = $.i18n.prop('i18n-Denyaccess');
    } else if (code == 1017) {
        tiptitle = $.i18n.prop('i18n-cancelfile');
    } else if (code == 2000) {
        tiptitle = $.i18n.prop('i18n-Unsupportedbrowser');
    } else if (code == 2001) {
        tiptitle = $.i18n.prop('i18n-notwindow');
    } else if (code == 2002) {
        tiptitle = $.i18n.prop('i18n-Hardwareacceleration');
    } else if (code == 3000) {
        tiptitle = $.i18n.prop('i18n-connectionfailure');
    } else if (code == 3001) {
        tiptitle = $.i18n.prop('i18n-userpasswordincorrect');
    } else if (code == 3002) {
        tiptitle = $.i18n.prop('i18n-Connectiontimeout');
    } else if (code == 3003) {
        tiptitle = $.i18n.prop('i18n-Weakpassworderro');
    } else if (code == 3004) {
        tiptitle = $.i18n.prop('i18n-InvalidDID');
    } else if (code == 3005) {
        tiptitle = $.i18n.prop('i18n-maxline');
    } else if (code == 3006) {
        tiptitle = $.i18n.prop('i18n-filefail');
    } else if (code == 3007) {
        tiptitle = $.i18n.prop('i18n-loginfail');
    } else if (code == 3008) {
        tiptitle = $.i18n.prop('i18n-fail-usermorll');
    } else if (code == 4000) {
        tiptitle = $.i18n.prop('i18n-rembacknolx');
    }
    bootoast({
        message: tiptitle,
        type: 'danger',
        position: 'bottom-center',
        timeout: true,
        animationDuration: 3000,
        dismissable: true
    });
}

/**
 * 脸库返回信息状态码提示
 */
function statuscode(code) {
    var title = "";
    if (-1 == code) {
        title = $.i18n.prop('i18n-facecode1');
    }
    if (-2 == code) {
        title = $.i18n.prop('i18n-facecode2');
    }
    if (-3 == code) {
        title = $.i18n.prop('i18n-facecode3');
    }
    if (-5 == code) {
        title = $.i18n.prop('i18n-facecode4');
    }
    if (-6 == code) {
        title = $.i18n.prop('i18n-facecode5');
    }
    if (-7 == code) {
        title = $.i18n.prop('i18n-facecode6');
    }
    if (-8 == code) {
        title = $.i18n.prop('i18n-facecode7');
    }
    if (-9 == code) {
        title = $.i18n.prop('i18n-facecode8');
    }
    if (-10 == code) {
        title = $.i18n.prop('i18n-facecode9');
    }
    if (-11 == code) {
        title = $.i18n.prop('i18n-facecode10');
    }
    if (-12 == code) {
        title = $.i18n.prop('i18n-facecode11');
    }
    if (-13 == code) {
        title = $.i18n.prop('i18n-facecode12');
    }
    if (0x1001 == code) {
        title = $.i18n.prop('i18n-facecode13');
    }
    if (0x1002 == code) {
        title = $.i18n.prop('i18n-facecode14');
    }
    if (0x1003 == code) {
        title = $.i18n.prop('i18n-facecode15');
    }
    if (0x1004 == code) {
        title = $.i18n.prop('i18n-facecode16');
    }
    if (0x1005 == code) {
        title = $.i18n.prop('i18n-facecode17');
    }
    if (0x1006 == code) {
        title = $.i18n.prop('i18n-facecode18');
    }
    if (0x1007 == code) {
        title = $.i18n.prop('i18n-facecode19');
    }
    if (0x1008 == code) {
        title = $.i18n.prop('i18n-facecode20');
    }
    if (0x1009 == code) {
        title = $.i18n.prop('i18n-facecode21');
    }
    if (0x100A == code) {
        title = $.i18n.prop('i18n-facecode22');
    }
    if (0x100B == code) {
        title = $.i18n.prop('i18n-facecode23');
    }
    if (0x100C == code) {
        title = $.i18n.prop('i18n-facecode24');
    }
    if (0x100D == code) {
        title = $.i18n.prop('i18n-facecode25');
    }
    if (0x100E == code) {
        title = $.i18n.prop('i18n-facecode26');
    }
    if (0x100F == code) {
        title = $.i18n.prop('i18n-facecode27');
    }
    if (0x1064 == code) {
        title = $.i18n.prop('i18n-facecode28');
    }
    if (0x1065 == code) {
        title = $.i18n.prop('i18n-facecode29');
    }
    if (0x1066 == code) {
        title = $.i18n.prop('i18n-facecode30');
    }
    if (0x1067 == code) {
        title = $.i18n.prop('i18n-facecode31');
    }
    if (0x1068 == code) {
        title = $.i18n.prop('i18n-facecode32');
    }
    if (0x1069 == code) {
        title = $.i18n.prop('i18n-facecode33');
    }
    if (0x106a == code) {
        title = $.i18n.prop('i18n-facecode34');
    }
    if (0x106b == code) {
        title = $.i18n.prop('i18n-facecode35');
    }
    if (0x106c == code) {
        title = $.i18n.prop('i18n-facecode36');
    }
    if (0x106d == code) {
        title = $.i18n.prop('i18n-facecode37');
    }
    bootoast({
        message: title,
        type: 'danger',
        position: 'bottom-center',
        timeout: true,
        animationDuration: 3000,
        dismissable: true
    });

}

function URL_Request(strName) {
    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:        createxmlDoc
 Description:    创建xml DOM对象
 Input:            无
 Output:            无
 return:            无
 *************************************************/
function createxmlDoc() {
    var xmlDoc;
    var aVersions = ["MSXML2.DOMDocument", "MSXML2.DOMDocument.5.0", "MSXML2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0", "Microsoft.XmlDom"];

    for (var i = 0; i < aVersions.length; i++) {
        try {
            xmlDoc = new ActiveXObject(aVersions[i]);
            break;
        } catch (oError) {
            xmlDoc = document.implementation.createDocument("", "", null);
            break;
        }
    }
    xmlDoc.async = "false";
    return xmlDoc;

}
/*************************************************
 Function:        parseXmlFromStr
 Description:    从xml字符串中解析xml
 Input:            szXml xml字符串
 Output:            无
 return:            xml文档
 *************************************************/
// 是否ie
function isIElANCE() {
    if (!!window.ActiveXObject || "ActiveXObject" in window) {
        return true;
    } else {
        return false;
    }
}

function parseXmlFromStr(szXml) {
    if (null == szXml || '' == szXml) {
        return null;
    }
    var xmlDoc = new createxmlDoc();
    if (!isIElANCE()) {
        var oParser = new DOMParser();
        xmlDoc = oParser.parseFromString(szXml, "text/xml");
    } else {
        xmlDoc.loadXML(szXml);
    }
    return xmlDoc;

}



//将base64转换为Blob
function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        // bstr = Base64.decode(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
        type: mime
    });
}

//将blob转换为file
function blobToFile(theBlob, fileName) {
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}


/*************************************************
 Function:        Base64
 Description:    Base64加密解密
 Input:            无
 Output:            无
 return:            无
 *************************************************/
var Base64 = {

    // private property
    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode: function(input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode: function(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            } else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            } else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode: function(utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }
};



/**
 * 获取播放模式
 */

function getplayMode() {
    var playModeList = [];
    $.ajax({
        url: 'custom/playMode.json',
        dataType: 'json',
        async: false,
        success: function(data) {
            if (data.playList.length == 0) { //如果客户不小心把全部的播放模式都删除了，，默认JPEG
                playModeList = ["MJPEG"];
            } else {
                playModeList = data.playList;
            }
        },
        error: function(data) {}
    });
    return playModeList
}

/**
 * 目标浏览器判断
 * @returns {boolean}
 */
function getBrowserType() {
    var ua = navigator.userAgent.toLocaleLowerCase();
    var isopera = ua.match(/opera/) != null || ua.match(/opr/) != null;
    var isEdge = ua.match(/edg/) != null;
    var isFirefox = ua.match(/firefox/) != null;
    var isSafari = ua.match(/safari/) != null && ua.match(/chrome/) == null;
    var isChrome = ua.match(/chrome/) != null;
    var isUC = ua.match(/ubrowser/) != null;
    var isQQ = ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null;
    var issogou = ua.match(/metasr/) != null;
    var is360 = check360() && ua.match(/chrome/) != null;

    if (isopera || isEdge || isFirefox || isSafari || isChrome || isUC || isQQ || is360 || issogou) {
        return true;
    } else {
        return false;
    }
}

function check360() {
    var result = false;
    for (var key in navigator.plugins) {
        if (navigator.plugins[key].filename == "internal-nacl-plugin ") {
            return !result;
        }
    }
    return result;
}


/**
 * 插件下载
 *正式服:http://erp.zwcloud.wang:8090/----新http://utilerp.p6sai.com:8090
 * 測試服:http://139.9.6.140:8090
 */

function downloweasyvideo() {
    $.ajax({
        url: "http://utilerp.p6sai.com:8090/UtilERP/device/web/last-pack?boardId=" + "FFFF" + '&deviceType=' + "FFF7" + '&customer=' + "C009" + '&versionId=' + "V001",
        type: "GET",
        // async: false,
        dataType: 'jsonp', //同源策略
        jsonp: "callbackName", //指定参数名称
        jsonpCallback: "showData", //指定回调函数名称
        timeout: 5000,
        success: function(result) {
            console.info("调用success");
            $("#myModal").modal('hide');
        },
        error: function(jqXHR, textStatus) {
            bootoast({
                message: $.i18n.prop('i18n-Downloadtimeout'),
                type: 'danger',
                position: 'top-center',
                timeout: true,
                animationDuration: 3000,
                dismissable: true
            });
        },
    })
}

function showData(data) {
    if (data.code == '200') {
        if (data.data.url) {
            location.href = data.data.url
        } else {
            bootoast({
                message: $.i18n.prop('i18n-noeasyvideofile'),
                type: 'danger',
                position: 'top-center',
                timeout: true,
                animationDuration: 3000,
                dismissable: true
            });
        }
    } else {
        bootoast({
            message: $.i18n.prop('i18n-Downloadfaileasy'),
            type: 'danger',
            position: 'top-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
    }
}

/**
 * 载入视频流
 * @param szPluginType  播放模式
 * @param vType 用来区分是否是预览框还是回放框，1是，2否,settings是否是配置页面，true，是，false否
 */

function getVideoPlugin(szPluginType, vType, param, settings, dzwl, paramdata,opentype,chn) {
    InitBrowseFrameInfo(JSON.parse(sessionStorage.getItem('mousePos')));
    var g_bIsIE = !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
    if (!g_bIsIE||config.forceEV) //如果是非IE的情况
    {
        if ("MJPEG" == szPluginType) {
            $("#downlodeasyvideo").hide();
            $("#playcz").hide();
            onloadMy();
            if (sessionStorage.getItem('connectionfail') != "2") {
                if (typeof Playervideo !== 'undefined' && typeof Playervideo === 'function') {
                    self.playervideo = new Playervideo();
                    self.playervideo.intervaleasy = setInterval(self.playervideo.connection, 2000);
                } else {
                    // 函数未定义
                    console.log('Playervideo函数不存在');
                }
            }
        } else if ("WebPlayer" == szPluginType) {
            $("#downlodeasyvideo").hide();
            $("#playcz").hide();
            initwebvideo();
            if (sessionStorage.getItem('connectionfail') != "2") {
                if (typeof Playervideo !== 'undefined' && typeof Playervideo === 'function') {
                    self.playervideo = new Playervideo();
                    self.playervideo.intervaleasy = setInterval(self.playervideo.connection, 2000);
                } else {
                    // 函数未定义
                    console.log('Playervideo函数不存在');
                }
            }
        } else if ("EasyVideo" == szPluginType) {
            $("#downloadeasyplay").hide();
            $("#downlodeasyvideo").hide();
            $("#playcz").show();
            if (vType == 1) {
                initwebeasy(param, settings, dzwl, paramdata,opentype,chn);
            }
        }
    } else {
        if ("ActiveX" == szPluginType) {
            // if (window.location.hash == "#preview.html" || window.location.hash == "") {
            //     $("#axdiv").html("<object id='previewocx' name='previewocx' width='100%' height='100%' classid='CLSID:d276963c-7c62-41a0-88b7-79e818ffb28b'  codebase='VideoClientControl.exe#version=" + config.iePlugVersion + "'  standby='控件加载中...'></object>")
            //     if (vType == 1) { //nvr走的是单独的出流接口，这里为了配置就直接注释了，应该要兼容以后的，没时间所以暂时注释
            //         InitPrivatePreviewEvent();
            //     }
            // } else {
            $("#axdiv").html('<object id="dvrocx" name="dvrocx" width="100%" height="100%" classid="clsid:7C45B963-98D8-50CB-6D22-E0A1C8D258AF" codebase="VideoPlugNVR.exe#version=1,0,0,4381"></object>')
            InitPrivatePreviewEvent(chn);
            // }
        } else if ("MJPEG" == szPluginType) {
            onloadMy();
        }
    }
}


function initwebeasy(param, settings, dzwl, paramdata,opentype,chn) {
    var pt = GetAbsoluteLocationEx($("#axdiv")[0]);
    var ua = navigator.userAgent.toLocaleLowerCase();
    var adjustPos = true;
    if (ua.match(/firefox/) != null || URL_Request("isp2p") == "p6s" || URL_Request("isp2p") == "p2p") { //火狐特殊处理
        adjustPos = false
    } else {
        adjustPos = true
    }
    var obj = {};
    obj.Fountion = "live";
    obj.LiveCtrl = {};
    obj.LiveCtrl.Preview = {};
    obj.LiveCtrl.type = 1;
    obj.LiveCtrl.uniqueId = parseInt(sessionStorage.getItem('uniqueId'), 10);
    obj.LiveCtrl.channel = chn;
    obj.LiveCtrl.settings = settings;
    obj.LiveCtrl.Preview.browser = getBrowsername();
    obj.LiveCtrl.Preview.title = document.getElementsByTagName("title")[0].text;
    obj.LiveCtrl.Preview.x = parseInt(pt.Left, 10);
    obj.LiveCtrl.Preview.y = parseInt(pt.Top, 10);
    if (dzwl == 1 || dzwl == 6 || dzwl == 7 || dzwl == 8) {
        obj.LiveCtrl.Preview.w = parseInt(558, 10);
        obj.LiveCtrl.Preview.h = parseInt(418, 10);
    } else {
        obj.LiveCtrl.Preview.w = parseInt(pt.Width, 10);
        obj.LiveCtrl.Preview.h = parseInt(pt.Height, 10);
    }
    obj.LiveCtrl.Preview.adjustPos = adjustPos;
    obj.LiveCtrl.Preview.streamType = 1;
    if (config.deviceInfo.DeviceName != 'IPC' && window.location.hash == "#preview.html") {
        obj.LiveCtrl.Preview.open = false;
        if (config.deviceInfo.VideoInputChannels == 1) {
            obj.LiveCtrl.Preview.layout = 1;
        } else if (config.deviceInfo.VideoInputChannels == 4) {
            obj.LiveCtrl.Preview.layout = 2;
        } else if (config.deviceInfo.VideoInputChannels == 8 || config.deviceInfo.VideoInputChannels == 9) {
            obj.LiveCtrl.Preview.layout = 3;
        } else if (config.deviceInfo.VideoInputChannels >= 10) {
            obj.LiveCtrl.Preview.layout = 4;
        }
    } else {
        obj.LiveCtrl.Preview.open = true;
    }
    var ARR = [];
    for (var o = 1; o <= config.deviceInfo.VideoInputChannels; o++) {
        ARR.push('CAM' + o);
    }
    obj.LiveCtrl.Preview.channelName = ARR;
    if (param == "cerate" || config.devicelose) { //走这一步的时候必须是easyvideo模式，devicelose这个状态也是针对它的，不判断刷新之后找不到资源会无法创建
        // console.log("当设备没有资源或者已关闭 创建设备")
        self.playervideo.reconcreatedev(obj, "", "", "", dzwl, paramdata,opentype);
    } else {
        if (self.playervideo) {
            // console.log("如果playervideo存在则直接live设备")
            // 这里只有IPc才走nvr第一次进入还未存在第二次因为存在了但是不开流所以不走
            self.playervideo.live(obj, dzwl, paramdata,opentype);
        } else {
            // console.log("如果playervideo不存在则重新new一个然后去创建设备")
            self.playervideo = new Playervideo();
            self.playervideo.reconcreatedev(obj, "", "", "", dzwl, paramdata,opentype);
        }
    }


}

function initwebvideo() {
    if (sessionStorage.getItem("stream") == "miancodestream") {
        self.player = new Player("main");
    } else if (sessionStorage.getItem("stream") == "codestream1") {
        self.player = new Player("sub1");
    } else {
        self.player = new Player("sub2");
    }
}


/**
 * 页面可见性监听
 * @param cb
 */

function registerVisibilityEvent(cb) {
    var hidden = "hidden";
    // Standards:
    if (hidden in document) {
        document.addEventListener("visibilitychange", onchange);
    } else if ((hidden = "mozHidden") in document) {
        document.addEventListener("mozvisibilitychange", onchange);
    } else if ((hidden = "webkitHidden") in document) {
        document.addEventListener("webkitvisibilitychange", onchange);
    } else if ((hidden = "msHidden") in document) {
        document.addEventListener("msvisibilitychange", onchange);
    } else if ("onfocusin" in document) {
        // IE 9 and lower.
        document.onfocusin = document.onfocusout = onchange;
    } else {
        // All others.
        window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange;
    }

    function onchange(evt) {
        var v = true;
        var h = false;
        var evtMap = {
            focus: v,
            focusin: v,
            pageshow: v,
            blur: h,
            focusout: h,
            pagehide: h
        };

        evt = evt || window.event;
        var visible = v;
        if (evt.type in evtMap) {
            visible = evtMap[evt.type];
        } else {
            visible = this[hidden] ? h : v;
        }
        cb(visible);
    }

    // set the initial state (but only if browser supports the Page Visibility API)
    if (document[hidden] !== undefined) {
        onchange({
            type: document[hidden] ? "blur" : "focus"
        });
    }
}



function GetDevicePixelRatio() {
    return window.devicePixelRatio || window.screen.deviceXDPI / window.screen.logicalXDPI;
}

function GetPageOffset() {
    var bGetPos = window.pageXOffset !== undefined;
    var bStandard = (document.compatMode || "") === "CSS1Compat";
    var posX = bGetPos ? window.pageXOffset : bStandard ? document.documentElement.scrollLeft :
        document.body.scrollLeft;
    var posY = bGetPos ? window.pageYOffset : bStandard ? document.documentElement.scrollTop :
        document.body.scrollTop;
    return {
        "x": posX,
        "y": posY
    };
}

/**
 * 获取当前easyvideo的播放窗口
 * @param ele
 * @returns {*}
 * @constructor
 */
function GetAbsoluteLocationEx(ele) {
    if (ele == null) {
        return null;
    }

    var u = GetDevicePixelRatio();
    // var u = 1;
    var offsetT = ele.offsetTop;
    var offsetL = ele.offsetLeft;

    while (ele = ele.offsetParent) {
        if (ele.style.position == "absolute" || ele.style.position == "relative" ||
            ele.style.overflow != "visible" &&
            ele.style.overflow != "") {
            break;
        }
        offsetT += ele.offsetTop;
        offsetL += ele.offsetLeft;
        offsetT -= ele.scrollTop;
        offsetL -= ele.scrollLeft;
    }
    var a = GetPageOffset();
    var q = $("#axdiv")[0].getBoundingClientRect();
    var t = {
        Left: q.left > 0 ? q.left : 0,
        Top: q.top > 0 ? q.top : 0,
        Width: q.width,
        Height: q.height
    };
    if (q.left < 0) {
        t.Width += q.left;
    }
    if (q.top < 0) {
        t.Height += q.top;
    }
    if ((q.height + offsetT) > (window.innerHeight + a.y))
        t.Height -= ((q.height + offsetT) - (window.innerHeight + a.y));
    if ((q.width + offsetL) > (window.innerWidth + a.x))
        t.Width -= ((q.width + offsetL) - (window.innerWidth + a.x));

    t.Left *= u;
    t.Top *= u;
    t.Width *= u;
    t.Height *= u;

    var ua = navigator.userAgent.toLocaleLowerCase();

    if (ua.match(/firefox/) != null) { //火狐特殊处理
        t.Top += config.BrowseMenuH;
    }

    t.Left = Math.round(t.Left);
    t.Top = Math.round(t.Top);
    t.Width = Math.round(t.Width);
    t.Height = Math.round(t.Height);
    return t;
}


function InitBrowseFrameInfo(event) {
    var u = GetDevicePixelRatio();
    var ua = navigator.userAgent.toLocaleLowerCase();
    // var u =1;
    var browseT = window.screenY || window.screenTop;
    var browseW = window.screenX || window.screenLeft;

    var BrowseW = 0;
    var BrowseH = 0;



    if (browseT < 0) {
        browseT = 0
    }

    if (ua.match(/firefox/) != null) { //火狐特殊处理
        browseT = parseInt(browseT * u);
        browseW = parseInt(browseW * u);
        BrowseH = parseInt(event.screenY * sessionStorage.getItem('dpiRadio')) - parseInt(event.clientY * u) - browseT;
        BrowseW = parseInt(event.screenX * sessionStorage.getItem('dpiRadio')) - parseInt(event.clientX * u) - browseW;
    }
    // else {
    //     BrowseH = parseInt(event.screenY) - parseInt(event.clientY * u);
    //     BrowseW = parseInt(event.screenX) - parseInt(event.clientX * u);
    // }
    if (Math.abs(BrowseW) > parseInt(4 * u) || Math.abs(BrowseH) > parseInt(4 * u)) {
        config.BrowseMenuH = BrowseH;
        config.BrowseMenuW = BrowseW;
    }
}

// 为了去更新存储里面的mousePos坐标
$("#content").click(function(event) {
    // var event = arguments.callee.caller.arguments[0] || window.event;
    var event = event || window.event;
    if (!event && window.event) {
        event = window.event;
    }
    var mousePos = {};
    mousePos.clientX = event.clientX;
    mousePos.clientY = event.clientY;
    mousePos.screenX = event.screenX;
    mousePos.screenY = event.screenY;
    // if (sessionStorage.getItem('mousePos') == null) {
    //     sessionStorage.setItem('mousePos', JSON.stringify(mousePos));
    // } else
    if (event.clientY == 0 && event.screenY == 0) {
        console.log("我不写入新数据");
    } else {
        sessionStorage.setItem('mousePos', JSON.stringify(mousePos));
    }
});
// 为了去更新存储里面的mousePos坐标
$("#header").click(function(event) {
    // var event = arguments.callee.caller.arguments[0] || window.event;
    var event = event || window.event;
    if (!event && window.event) {
        event = window.event;
    }
    var mousePos = {};
    mousePos.clientX = event.clientX;
    mousePos.clientY = event.clientY;
    mousePos.screenX = event.screenX;
    mousePos.screenY = event.screenY;
    sessionStorage.setItem('mousePos', JSON.stringify(mousePos));
});
// 为了去更新存储里面的mousePos坐标
$("#left-panel").click(function(event) {
    // var event = arguments.callee.caller.arguments[0] || window.event;
    var event = event || window.event;
    if (!event && window.event) {
        event = window.event;
    }
    var mousePos = {};
    mousePos.clientX = event.clientX;
    mousePos.clientY = event.clientY;
    mousePos.screenX = event.screenX;
    mousePos.screenY = event.screenY;
    sessionStorage.setItem('mousePos', JSON.stringify(mousePos));
});

//判断浏览器 登录后复制
function getBrowsername() {
    var ua = navigator.userAgent.toLocaleLowerCase();
    if (ua.match(/firefox/) != null) {
        return "firefox.exe";
    } else if (ua.match(/ubrowser/) != null) {
        return "UCBrowser.exe";
    } else if (ua.match(/opera/) != null || ua.match(/opr/) != null) {
        return "opera.exe";
    } else if (ua.match(/edg/) != null) {
        return "msedge.exe";
    } else if (ua.match(/metasr/) != null) {
        return "SogouExplorer.exe";
    } else if (ua.match(/tencenttraveler/) != null || ua.match(/qqbrowse/) != null) {
        return "QQBrowser.exe";
    } else if (ua.match(/chrome/) != null) {
        if (checkChromeFor360()) {
            return "360se.exe";
        } else {
            return "chrome.exe";
        }
    } else if (ua.match(/safari/) != null && ua.match(/chrome/) == null) {
        return "SafariSetup.exe";
    }

}


// 检测极速内核下的360浏览器
function checkChromeFor360() {
    var uas = navigator.userAgent.split(' '),
        result = false;
    // 排除ua自带标志的双核浏览器, 余下chrome,chromium及360浏览器
    if (uas[uas.length - 1].indexOf('Safari') == -1) {
        return result;
    }
    for (var key in navigator.plugins) {
        // np-mswmp.dll文件在chromium及chrome未查询到
        if (navigator.plugins[key].filename == 'np-mswmp.dll') {
            return !result;
        }
    }
    return result;
}

/**
 * 画面比例方法
 * @param W 宽的比例
 * @param H 高的比例
 *
 */
function screenMode(W, H) {
    var axdivParentH, axdivW, axdivH;
    if ((W == 4 && H == 3) || (W == 16 && H == 9)) {
        axdivParentH = $(".play").height();
        //高度固定，算宽度
        axdivW = axdivParentH / H * W;
        //宽度固定，算高度
        axdivH = axdivParentH;
    } else {
        axdivW = "100%";
        //宽度固定，算高度
        axdivH = "100%";
    }
    if (sessionStorage.getItem("playstyle") == "WebPlayer") {
        $("#playCanvas").height(axdivH);
        $("#playCanvas").width(axdivW);
    } else {
        $("#axdiv").height(axdivH);
        $("#axdiv").width(axdivW);

        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            if (config.deviceInfo.DeviceName == "IPC") {
                preWindowfollowing(false);
            } else {
                nvrOriginalScale(config.thoroughfare, false);
                config.bine_push_list.splice(config.bine_push_list.indexOf(config.thoroughfare), 1) //自定义的通道就清除掉
            }
            // preWindowfollowingNVR(thoroughfare);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
            AspectRatioControl(0, config.chnelNum); //自定义
        }
    }


}



function enventwesoket(ml) {
    this.downloaderenventWorker = null;
    this.stream = ml;
    this.url = 'ws://' + location.hostname + ":" + config.m_HttpPort + "/WebSocket/Connect";
    this.fun = "event";
    this.initDownloaderenventWorker();
}


/**
 * websoket线程
 */

enventwesoket.prototype.initDownloaderenventWorker = function() {
    var self = this;
    this.downloaderenventWorker = new Worker('js/components/downloaderenvent.js');
    if (this.downloaderenventWorker) {
        var obj = {};
        obj.auth = {};
        obj.auth.user = config.user;
        obj.auth.mode = "0";
        obj.auth.time = new Date().getTime().toString();
        obj.auth.pass = hex_md5(config.password + obj.auth.time);

        obj.req = {};
        obj.req.fun = this.fun;
        obj.req.ctrl = "open";
        obj.req.ch = "1";
        obj.req.stream = this.stream;
        this.downloaderenventWorker.postMessage({
            t: kGetwasmReqenvent,
            url: this.url,
            msg: obj,
            type: ""
        });
    }
    this.downloaderenventWorker.onmessage = function(evt) {
        var objData = evt.data;
        switch (objData.t) {
            case kGetwasmRspenvent:
                self.onmessageWS(objData.i);
                break;
        }
    };
};


enventwesoket.prototype.onmessageWS = function(envent) {
    //$("<img src='img/enventicon/yidon.png' title='i18n-Motion-detection' id='spzd'>").appendTo("#previewMiddle10Img");
    if (envent.code == 200) {
        var data = JSON.parse(envent.data);
        if (data.cmd == "event") {
            if (data.body.type == "videoShade") { //视频遮挡事件
                if (data.body.param3 == 4) { //结束事件
                    $("#spzd").remove();
                } else {
                    if (!document.getElementById("spzd")) {
                        $("<img src='img/preview/spzd.png' id='spzd'>").appendTo("#previewMiddle" + data.body.param2 + "Img");
                    }
                    // $("#spzd").show();
                    var index = config.enventList.map(function(a) {
                        return a.type;
                    }).indexOf("videoShade");
                    var obj = {};
                    obj.type = "videoShade";
                    obj.time = Math.round(Date.parse(new Date()) / 1000).toString();
                    if (index == -1) { //无则添加
                        config.enventList.push(obj);
                    } else { //有则替换
                        config.enventList.splice(index, 1, obj);
                    }
                }

            } else if (data.body.type == "leavePost") { //离岗侦测事件
                if (data.body.param3 == 4) { //结束事件
                    $("#ligang").remove();
                } else {
                    if (!document.getElementById("ligang")) {
                        $("<img src='img/preview/lgzc.png' id='ligang'>").appendTo("#previewMiddle" + data.body.param2 + "Img");
                    }

                    // $("#ligang").show();
                    var index = config.enventList.map(function(a) {
                        return a.type;
                    }).indexOf("leavePost");
                    var obj1 = {};
                    obj1.type = "leavePost";
                    obj1.time = Math.round(Date.parse(new Date()) / 1000).toString();
                    if (index == -1) { //无则添加
                        config.enventList.push(obj1);
                    } else { //有则替换
                        config.enventList.splice(index, 1, obj1);
                    }
                }

            } else if (data.body.type == "outOfBound") { //越界事件
                if (data.body.param3 == 4) { //结束事件
                    $("#yuejie").remove();
                } else {
                    if (!document.getElementById("yuejie")) {
                        $("<img src='img/preview/yjzc.png' id='yuejie'>").appendTo("#previewMiddle" + data.body.param2 + "Img");
                    }

                    // $("#yuejie").show();
                    var index = config.enventList.map(function(a) {
                        return a.type;
                    }).indexOf("outOfBound");
                    var obj2 = {};
                    obj2.type = "outOfBound";
                    obj2.time = Math.round(Date.parse(new Date()) / 1000).toString();
                    if (index == -1) { //无则添加
                        config.enventList.push(obj2);
                    } else { //有则替换
                        config.enventList.splice(index, 1, obj2);
                    }
                }

            } else
            //     if (data.body.type == "fenceDetectAlarm") { //电子围栏
            //     if (data.body.param3 == 4) { //结束事件
            //         $("#quyu").remove();
            //     } else {
            //         if (!document.getElementById("quyu")) {
            //             $("<img src='img/preview/quyu.png' id='quyu'>").appendTo("#eventnotice");
            //         }
            //
            //         // $("#quyu").show();
            //         var index = config.enventList.map(function(a) {
            //             return a.type;
            //         }).indexOf("fenceDetectAlarm");
            //         var obj3 = {};
            //         obj3.type = "fenceDetectAlarm";
            //         obj3.time = Math.round(Date.parse(new Date()) / 1000).toString();
            //         if (index == -1) { //无则添加
            //             config.enventList.push(obj3);
            //         } else { //有则替换
            //             config.enventList.splice(index, 1, obj3);
            //         }
            //     }
            //
            // } else
            if (data.body.type == "motionDetection") { //移动侦测
                if (data.body.param3 == 4) { //结束事件
                    $("#yidon").remove();
                } else {
                    var title = $.i18n.prop('i18n-Motion-detection');
                    if ($("#previewMiddle" + data.body.param2 + "Img").children("#yidon").length == 0) {
                        $("<img src='img/preview/ydzc.png' title=" + title + " id='yidon'>").appendTo("#previewMiddle" + data.body.param2 + "Img");
                    }
                    // $("#yidon").show();

                    var index = config.enventList.map(function(a) {
                        return a.EVtype;
                    }).indexOf(data.body.param2);
                    var obj4 = {};
                    obj4.type = "motionDetection";
                    obj4.EVtype = data.body.param2;
                    obj4.time = Math.round(Date.parse(new Date()) / 1000).toString();
                    if (index == -1) { //无则添加
                        config.enventList.push(obj4);
                    } else { //有则替换
                        config.enventList.splice(index, 1, obj4);
                    }
                }

            } else if (data.body.type == "humanDetection") { //人形侦测
                if (data.body.param3 == 4) { //结束事件
                    $("#renxin").remove();
                } else {
                    var title = $.i18n.prop('i18n-Human-Form-Detection');
                    if ($("#previewMiddle" + data.body.param2 + "Img").children("#renxin").length == 0) {
                        $("<img src='img/preview/rxjc.png' title=" + title + " id='renxin'>").appendTo("#previewMiddle" + data.body.param2 + "Img");
                    }
                    // $("#yidon").show();

                    var index = config.enventList.map(function(a) {
                        return a.EVtype;
                    }).indexOf(data.body.param2);
                    var obj5 = {};
                    obj5.type = "humanDetection";
                    obj5.EVtype = data.body.param2;
                    obj5.time = Math.round(Date.parse(new Date()) / 1000).toString();
                    if (index == -1) { //无则添加
                        config.enventList.push(obj5);
                    } else { //有则替换
                        config.enventList.splice(index, 1, obj5);
                    }
                }

            } else if (data.body.type == "faceCaptured") { //只支持人脸抓拍事件

            } else if (data.body.type == "faceRecognition") { //只支持人脸识别事件


            } else if (data.body.type == "faceRecognitionV4") { //既支持人脸抓怕也支持人脸识别
                if (config.stopjs || config.enableelectron) { //暂停接收不再接收人脸事件或者识别按钮没开启
                    return;
                }
                var checkImage = data.body.msg.HasFaceMatchInfoV2;
                if (checkImage == "0") {
                    var snapImagePath = "img/face/bdtg.png" //识别图
                } else {
                    var snapImagePath = data.body.msg.faceMatchInfoV3.faceMatchImage.picture; //识别图
                }
                var MatchCount = data.body.msg.faceMatchInfoV3.match;
                var caputImagePath = data.body.msg.faceCaptureInfoV3.faceCaptureImage.picture; //抓拍图
                var otherface_property = {};
                otherface_property.path = data.body.msg.BackgroundInfo.HasBackground; //背景图标识
                if (MatchCount != 0) {
                    otherface_property.snapImagePath = data.body.msg.faceMatchInfoV3.faceMatchImage.picture; //识别图片
                } else {
                    otherface_property.snapImagePath = "img/face/bdtg.png"
                }
                otherface_property.caputImagePath = data.body.msg.faceCaptureInfoV3.faceCaptureImage.picture;
                otherface_property.chancel = data.body.param2; //通道名
                otherface_property.time = new Date(parseInt(data.body.msg.timeSec) * 1000 + new Date()
                    .getTimezoneOffset() * 60000).Format('yyyy-MM-dd hh:mm:ss');
                otherface_property.match = data.body.msg.faceMatchInfoV3.match; //匹配度
                otherface_property.faceLibName = data.body.msg.faceMatchInfoV3.faceLibName; //脸库名称
                otherface_property.serial = data.body.msg.faceMatchInfoV3.serial; //匹配序号
                otherface_property.faceLibID = data.body.msg.faceMatchInfoV3.libID; //脸库ID
                otherface_property.faceID = data.body.msg.faceMatchInfoV3.FaceID; //人脸ID
                otherface_property.faceName = data.body.msg.faceMatchInfoV3.faceName; //人脸名称
                otherface_property.MatchCount = data.body.msg.faceMatchInfoV3.match; //比对通过不通过标志
                while (config.peopleface_detect_list.length == 50) {
                    config.peopleface_detect_list.shift(); //当等于100的时候数组清空
                    $(".zppeople").last().remove();
                }
                config.peopleface_detect_list.push(otherface_property);

                while (config.face_detect_list.length == 50) {
                    config.face_detect_list.shift(); //删除数组的第一个元素
                    $(".onepeopleFaceReco").last().remove(); //删除li的最后一个元素
                }
                config.face_detect_list.push(otherface_property);

                if (MatchCount != 0) { //比对通过
                    var facename = data.body.msg.faceMatchInfoV3.faceLibName;
                    $("#face_Feature").prepend("<div class='zppeople' style='background-image:url(" + caputImagePath + ");background-size: 100% 100%;'></div>");
                    $("#face_Analysis").prepend(
                        "<div class='onepeopleFaceReco'>" +
                        "<div class='peopleparent'>" +
                        "<div class='sbpeople'><img src='" + caputImagePath + "' style='width: 100%;height: 100%'></div>" +
                        "<div class='sbpeople'><img src='" + snapImagePath + "' class='" + (checkImage == "0" ? "" : "snapImageimg") + "'></div></div>" +
                        "<div class='name'>" + data.body.msg.faceMatchInfoV3.faceName + "</div>" +
                        "<div class='facegroup'><img src='img/face/facegroup.png'><span class='timeandgrouptitle'>" + facename + "</span><span class='bdresult'>" + (data.body.msg.faceMatchInfoV3.match).toFixed(2) + "%" + "</span></div>" +
                        "<div class='time'><img src='img/face/time.png'><span class='timeandgrouptitle'>" + new Date(parseInt(data.body.msg.timeSec) * 1000 + new Date().getTimezoneOffset() * 60000).Format('yyyy-MM-dd hh:mm:ss') + "</span></div>" +
                        "</div>");
                } else { //比对不通过
                    $("#face_Feature").prepend("<div class='zppeople'  style='background-image:url(" + caputImagePath + ");background-size: 100% 100%;'></div>");
                    $("#face_Analysis").prepend(
                        "<div class='onepeopleFaceReco'>" +
                        "<div class='peopleparent'>" +
                        "<div class='sbpeople'><img src='" + caputImagePath + "' style='width: 100%;height: 100%'></div>" +
                        "<div class='sbpeople'><img src='" + snapImagePath + "'  class='" + (checkImage == "0" ? "" : "snapImageimg") + "'></div></div>" +
                        "<div class='bdnottg'>" + $.i18n.prop('i18n-noPass-thecomparison') + "</div>" +
                        "<div class='time'><img src='img/face/time.png'><span class='timeandgrouptitle'>" + new Date(parseInt(data.body.msg.timeSec) * 1000 + new Date().getTimezoneOffset() * 60000).Format('yyyy-MM-dd hh:mm:ss') + "</span></div>" +
                        "</div>");

                }

            } else if (data.body.type == "breathMask") { //口罩事件

            }
        }

    }
};

/**
 * xml字符串转换xml对象数据
 * @param {Object} xmlStr
 */
function xmlStr2XmlObj(xmlStr) {
    var xmlObj = {};
    if (document.all) {
        var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
        xmlDom.loadXML(xmlStr);
        xmlObj = xmlDom;
    } else {
        xmlObj = new DOMParser().parseFromString(xmlStr, "text/xml");
    }
    return xmlObj;
}


/**
 * 快速入库
 * @param param
 */

function funquck(param) {
    var options = {};
    options.extData = param.caputImagePath;
    options.dataId = $("#facezhupairule").select2("val"); //脸库id
    CustomOpenModal.openDialogByData("addPeopleModal", "nvr/pages/events/addpeople.html?m=" + Math.random(), "", "添加", 1040, options);
}

/**********************************
 功能: 计算字符串的长度
 参数: szString: 输入的字符串
 ***********************************/
function JudgeTextLength(szString) {
    var iLength = 0;
    for (var i = 0; i < szString.length; i++) {
        if (szString.charCodeAt(i) > 255) {
            iLength += 2;
        } else {
            iLength += 1;
        }
    }
    return iLength
}


// 组织一周的布防时间
function group(array, subGroupLength) {
    var index = 0;
    var newArray = [];
    while (index < array.length) {
        newArray.push(array.slice(index, index += subGroupLength));
    }
    var a = newArray[0];
    newArray.push(a);
    newArray.shift();
    return newArray;
}

// 取出所有为1的时间的下标
function changetimeFool(arr) {
    var lastArr = []
    var lastArrs = []
    var lastArrt = []
    var lastArrb = []
    for (var i = 0; i < arr.length; i++) {
        var checkArr = []
        var checkArrs = []
        var checkArrt = []
        var checkArrb = []
        for (var o = 0; o < arr[i].length; o++) {
            if (arr[i][o] == "1") {
                checkArr.push(o + 1)
            } else if (arr[i][o] == "2") {
                checkArrs.push(o + 1)
            } else if (arr[i][o] == "3") {
                checkArrt.push(o + 1)
            }else if(arr[i][o] == "4"){
                checkArrb.push(o+1)
            }
        }
        lastArr.push(checkArr)
        lastArrs.push(checkArrs)
        lastArrt.push(checkArrt)
        lastArrb.push(checkArrb)
    }
    var realt = []
    var realts = []
    var realtt = []
    var realtb = []
    for (var q = 0; q < lastArr.length; q++) {
        realt.push(arrange(lastArr[q]))
    }
    for (var q = 0; q < lastArrs.length; q++) {
        realts.push(arrange(lastArrs[q]))
    }
    for (var q = 0; q < lastArrt.length; q++) {
        realtt.push(arrange(lastArrt[q]))
    }
    for (var q = 0; q < lastArrb.length; q++) {
        realtb.push(arrange(lastArrb[q]))
    }
    var lastRealt = []
    for (var j = 0; j < timeSlot(realt).length; j++) {
        lastRealt.push(timeSlot(realt, 1)[j])
    }
    var lastRealts = []
    for (var j = 0; j < timeSlot(realts).length; j++) {
        lastRealts.push(timeSlot(realts, 2)[j])
    }
    var lastRealtt = []
    for (var j = 0; j < timeSlot(realtt).length; j++) {
        lastRealtt.push(timeSlot(realtt, 3)[j])
    }
    var lastRealtb = []
    for (var j = 0; j < timeSlot(realtb).length; j++) {
        lastRealtb.push(timeSlot(realtb, 4)[j])
    }

    var lstRealt = []
    for (var l = 0; l < 7; l++) {
        lstRealt.push([].concat(lastRealt[l], lastRealts[l], lastRealtt[l],lastRealtb[l]))
    }
    return lstRealt;
}
// 转换成连续的数组方法
function arrange(arr) {
    var result = [],
        temp = [];
    arr.sort(function(source, dest) {
        return source - dest;
    }).concat(Infinity).reduce(function(source, dest) {
        temp.push(source);
        if (dest - source > 1) {
            result.push(temp);
            temp = [];
        }
        return dest;
    });
    return result;
};
// 彻底转换为符合条件的时间段
function timeSlot(t, n) {
    var arr = []
    for (var a = 0; a < t.length; a++) {
        var k = t[a]
        var bigArr = [];
        for (var i = 0; i < k.length; i++) {
            var q = k[i]
            var obj = {};
            if (q[0] > 10) {
                obj.sTime = q[0] - 1 + ':00:00'
            } else if (q[0] == 1) {
                obj.sTime = '00' + ':00:00'
            } else {
                obj.sTime = '0' + (q[0] - 1) + ':00:00'
            }
            if (q[q.length - 1] > 9 && q[q.length - 1] != 23) {
                obj.eTime = q[q.length - 1] + ':00:00'
            } else if (q[q.length - 1] == 23) {
                obj.eTime = (q[q.length - 1] + 1) + ':00:00'
            } else {
                obj.eTime = '0' + q[q.length - 1] + ':00:00'
            }
            obj.type = n
            bigArr.push(obj)
        }
        arr.push(bigArr)
    }
    return arr;
}
//将每一天的选中时间段转换为00和11
function takeZero(data) {
    var arr = []
    var arrs = []
    var arrss = []
    var arrst = []
    for (var r = 0; r < data.length; r++) {
        var v = data[r]
        var arr2 = []
        var arr3 = []
        var arr4 = []
        var arr5 = []
        for (var p = 0; p < v.length; p++) {
            var k = v[p]
            if (k.type == "1") {
                var newArr = []
                if (k.sTime.split(':')[0] == k.eTime.split(':')[0]) {
                    newArr.push(Number(k.sTime.split(':')[0]))
                    newArr.push(Number(k.sTime.split(':')[0]) + 1)
                } else {
                    if (Number(k.sTime.split(':')[1]) > 29) {
                        newArr.push(Number(k.sTime.split(':')[0]) + 1)
                    } else {
                        newArr.push(Number(k.sTime.split(':')[0]))
                    }
                    if (Number(k.eTime.split(':')[1]) > 29) {
                        newArr.push(Number(k.eTime.split(':')[0]) + 1)
                    } else {
                        newArr.push(Number(k.eTime.split(':')[0]))
                    }
                }
                arr2.push(newArr)
            } else if (k.type == "2") {
                var newArr = []
                if (k.sTime.split(':')[0] == k.eTime.split(':')[0]) {
                    newArr.push(Number(k.sTime.split(':')[0]))
                    newArr.push(Number(k.sTime.split(':')[0]) + 1)
                } else {
                    if (Number(k.sTime.split(':')[1]) > 29) {
                        newArr.push(Number(k.sTime.split(':')[0]) + 1)
                    } else {
                        newArr.push(Number(k.sTime.split(':')[0]))
                    }
                    if (Number(k.eTime.split(':')[1]) > 29) {
                        newArr.push(Number(k.eTime.split(':')[0]) + 1)
                    } else {
                        newArr.push(Number(k.eTime.split(':')[0]))
                    }
                }
                arr3.push(newArr)
            } else if (k.type == "3") {
                var newArr = []
                if (k.sTime.split(':')[0] == k.eTime.split(':')[0]) {
                    newArr.push(Number(k.sTime.split(':')[0]))
                    newArr.push(Number(k.sTime.split(':')[0]) + 1)
                } else {
                    if (Number(k.sTime.split(':')[1]) > 29) {
                        newArr.push(Number(k.sTime.split(':')[0]) + 1)
                    } else {
                        newArr.push(Number(k.sTime.split(':')[0]))
                    }
                    if (Number(k.eTime.split(':')[1]) > 29) {
                        newArr.push(Number(k.eTime.split(':')[0]) + 1)
                    } else {
                        newArr.push(Number(k.eTime.split(':')[0]))
                    }
                }
                arr4.push(newArr)
            }else if (k.type == "4") {
                var newArr = []
                if (k.sTime.split(':')[0] == k.eTime.split(':')[0]) {
                    newArr.push(Number(k.sTime.split(':')[0]))
                    newArr.push(Number(k.sTime.split(':')[0]) + 1)
                } else {
                    if (Number(k.sTime.split(':')[1]) > 29) {
                        newArr.push(Number(k.sTime.split(':')[0]) + 1)
                    } else {
                        newArr.push(Number(k.sTime.split(':')[0]))
                    }
                    if (Number(k.eTime.split(':')[1]) > 29) {
                        newArr.push(Number(k.eTime.split(':')[0]) + 1)
                    } else {
                        newArr.push(Number(k.eTime.split(':')[0]))
                    }
                }
                arr5.push(newArr)
            }
        }
        arr.push(arr2)
        arrs.push(arr3)
        arrss.push(arr4)
        arrst.push(arr5)
    }
    var timeContent = changeTimefor(arr, 1)
    var timeContentTwo = changeTimefor(arrs, 2)
    var timeContentThird = changeTimefor(arrss, 3)
    var timeContentFour = changeTimefor(arrst, 4)
    var timeplag = claosAll(timeContent, timeContentTwo, timeContentThird,timeContentFour)
    return timeplag
}
// 把需要替换的时间段转换为特殊字符
function changeTimefor(parms, num) {
    var timeContent = []
    for (var m = 0; m < parms.length; m++) {
        var p = parms[m]
        var ctext = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24']
        for (var x = 0; x < p.length; x++) {
            var j = p[x]
            for (var i = 0; i < 24; i++) {
                if (ctext[i] > j[0] && ctext[i] < j[1]) {
                    ctext.splice(i, 1, "tt")
                } else if (ctext[i] > j[0] && ctext[i] == j[1]) {
                    ctext.splice(i, 1, "tt")
                }
            }
        }
        for (var r = 0; r < ctext.length; r++) {
            if (ctext[r] == 'tt') {
                if (num == 1) {
                    ctext[r] = '11'
                } else if (num == 2) {
                    ctext[r] = '22'
                } else if (num == 3) {
                    ctext[r] = '44'
                }else if (num == 4) {
                    ctext[r] = '33'
                }
            } else {
                ctext[r] = '00'
            }
        }
        timeContent.push(ctext.join(""))
    }
    return timeContent
}
// 把三个数组合起来
function claosAll(Content, ContentTwo, ContentThird,timeContentFour) {
    var realse = []
    for (var i = 0; i < 7; i++) {
        var arr = ""
        for (q = 0; q < 48; q++) {
            if (Content[i][q] != "0") {
                arr += Content[i][q]
            } else if (ContentTwo[i][q] != "0") {
                arr += ContentTwo[i][q]
            } else if (ContentThird[i][q] != "0") {
                arr += ContentThird[i][q]
            } else if(timeContentFour[i][q] != "0"){
                arr += timeContentFour[i][q]
            }else{
                arr += "0"
            }
        }
        realse.push(arr)
    }

    return realse
}
//过滤方向键
function keyboardFilter(e) {
    e = e || window.event;
    if (!e.srcElement)
        e.srcElement = e.target;
    if ((e.keyCode >= 37 && e.keyCode <= 40) /*|| (e.keyCode == 8)*/ || (e.keyCode == 9)) { //取消 退格键 过滤
        return false;
    }
    return true;
}
//对端口进行限制
function NumberRangeLimt(ctrId, minVal, maxVal) {
    var str = ($("#" + ctrId.id).val()).replace(/\D/g, '');
    if (minVal != maxVal) {
        if (str != "" && str < minVal) {
            return minVal;
        }
        if (str > maxVal) {
            return maxVal;
        }
    }
    return str;
}

function WidthCheck(str, maxLen) {
    var w = 0;
    var tempCount = 0;
    //length 获取字数数，不区分汉子和英文
    for (var i = 0; i < str.value.length; i++) {
        //charCodeAt()获取字符串中某一个字符的编码
        var c = str.value.charCodeAt(i);
        //单字节加1
        if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
            w++;
        } else {
            w += 2;
        }
        if (w > maxLen) {
            str.value = str.value.substr(0, i);
            break;
        }
    }
}
