var user = config.user,
    pwd = config.password;
var quality = ['high', 'middle', 'low']
var rWidths, rHeights;
var Resolutions = [];
var gs_arrResolution = [{
        Resolution: "352*288",
        ResolutionVal: "CIF(352*288)"
    },
    {
        Resolution: "704*576",
        ResolutionVal: "D1(704*576)"
    },
    {
        Resolution: "1280*960",
        ResolutionVal: "1280*960"
    },
    {
        Resolution: "1280*1024",
        ResolutionVal: "1280*1024"
    },
    {
        Resolution: "1600*1200",
        ResolutionVal: "1600*1200"
    },
    {
        Resolution: "1280*720",
        ResolutionVal: "720P(1280*720)"
    },
    {
        Resolution: "1920*1080",
        ResolutionVal: "1080P(1920*1080)"
    },
    {
        Resolution: "640*480",
        ResolutionVal: "640*480"
    },
    {
        Resolution: "2048*1536",
        ResolutionVal: "QXGA(2048*1536)"
    },
    {
        Resolution: "640*360",
        ResolutionVal: "640*360"
    },
    {
        Resolution: "320*240",
        ResolutionVal: "320*240"
    },
    {
        Resolution: "2592*1520",
        ResolutionVal: "UWXGA(2592*1520)"
    },
];
$(document).ready(function() {
    initAudioPage();
    getSnapCapability();
    getashortcfgfromdevice();
    if (config.deviceCap.TimeSnapshot == "true") {
        $(".isAll").show();
        getShorttimeCaoture();
    } else {
        $(".isAll").hide();
    }
    // 根据能力显示 SD、FTP、MQTT 联动方式
    if (config.deviceCap.diskEnable == "true") {
        $("#SD").show();
    } else {
        $("#SD").hide();
    }
    if (config.deviceCap.Ftp == "true") {
        $("#FTP").show();
    } else {
        $("#FTP").hide();
    }
    if (config.deviceCap.MqttContrl == "true") {
        $("#MQTT").show();
    } else {
        $("#MQTT").hide();
    }
    $('#AudioStreamsave').click(function() {
        if ("admin" == user || "super_admin" == user) {
            setashortcfgfromdevice();
            if (config.deviceCap.TimeSnapshot == "true") {
                setShorttimeCaoture();
            }
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
        }
    });

});

function initAudioPage() {
    if (!$('.select2').hasClass('select2-offscreen')) {
        $(".select2").select2({
            minimumResultsForSearch: -1,
            width: 360
        });
    }
    var sylx = $.i18n.prop("i18n-sensitivity-value").split(",");
    for (var i = 0; i < sylx.length; i++) {
        $("<option value='" + quality[i] + "'>" + sylx[i] + "</option>").appendTo("#CaptureQuality");
    }
    // 时间改变
    $("#Capturesnowtime").change(function() {
        if ($("#Capturesnowtime").val() == "user") {
            $(".isshowUser").show();
        } else {
            $(".isshowUser").hide();
        }
    });
    // 选择定时抓拍
    $("#CaptureEnable").change(function() {
        if ($(this).is(':checked')) {
            $('.allpcte').show();
            $("#Capturesnowtime").change();
        } else {
            $('.allpcte').hide();
            $('.isshowUser').hide();

        }
    });
}
// 获取当前抓图配置
function getashortcfgfromdevice() {
    $.ajax({
        url: config.baseUrl + "/Snapshot/Config",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            $("#CaptureQuality").select2('val', $(xmlDoc).find('Quality').eq(0).text());
            // SupportStreamType字段，决定下拉框显示
            // 按位获取，第0位表示主码流，第一位表示子码流，依此类推
            // 比如 110000 显示同主、子码流;100000只显示同主码流;010000只显示同子码流
            if ($(xmlDoc).find('StreamType').eq(0).text()) {
                var listPower = $(xmlDoc).find('SupportStreamType').eq(0).text();
                if (listPower.charAt(0) === '1') {
                    $("<option value='main'>" + $.i18n.prop('i18n-Samemain-stream') + "</option>").appendTo("#CaptureFbjso");
                }
                if (listPower.charAt(1) === '1') {
                    $("<option value='sub'>" + $.i18n.prop('i18n-Samesub-stream') + "</option>").appendTo("#CaptureFbjso");
                }
                if (listPower.substr(0, 2) === '00') {
                    $("<option value='main'>" + $.i18n.prop('i18n-Samemain-stream') + "</option>").appendTo("#CaptureFbjso");
                }
                $("#CaptureFbjso").select2('val', $(xmlDoc).find('StreamType').eq(0).text())
            } else {
                for (var j = 0; j < gs_arrResolution.length; j++) {
                    for (var q = 0; q < Resolutions.length; q++) {
                        if (Resolutions[q] == gs_arrResolution[j].Resolution) {
                            $("<option value='" + Resolutions[q] + "'>" + gs_arrResolution[j].ResolutionVal + "</option>").appendTo("#CaptureFbjso");
                        }

                    }
                }
                var rWidth = $(xmlDoc).find('SnapshotConfig').eq(0).find('ResolutionWidth').text();
                var rHeight = $(xmlDoc).find('SnapshotConfig').eq(0).find('ResolutionHeight').text();
                console.log(Resolutions);
                console.log(rWidth + '*' + rHeight);
                $("#CaptureFbjso").select2('val', rWidth + '*' + rHeight)
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}

function setashortcfgfromdevice() {
    if ($("#CaptureFbjso").val() == "main" || $("#CaptureFbjso").val() == "sub") {
        var cyXml = "<?xml version='1.0'' encoding='utf-8' ?>" +
            "<SnapshotConfig>" +
            "<ResolutionWidth></ResolutionWidth>" +
            "<ResolutionHeight></ResolutionHeight>" +
            "<Quality>" + $("#CaptureQuality").val() + "</Quality>" +
            "<SnapshotCount></SnapshotCount>" +
            "<SnapshotIntervalTime></SnapshotIntervalTime>" +
            "<StreamType>" + $("#CaptureFbjso").val() + "</StreamType>"
        "</SnapshotConfig>";

    } else {
        var rWidth = $("#CaptureFbjso").val().split("*")[0];
        var rHeight = $("#CaptureFbjso").val().split("*")[1];
        var cyXml = "<?xml version='1.0'' encoding='utf-8' ?>" +
            "<SnapshotConfig>" +
            "<ResolutionWidth>" + rWidth + "</ResolutionWidth>" +
            "<ResolutionHeight>" + rHeight + "</ResolutionHeight>" +
            "<Quality>" + $("#CaptureQuality").val() + "</Quality>" +
            "<SnapshotCount></SnapshotCount>" +
            "<SnapshotIntervalTime></SnapshotIntervalTime>" +
            "</SnapshotConfig>";

    }

    var cyURL = config.baseUrl + "/Snapshot/Config";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: true,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
        }
    });
}
// 以前就没有备注看逻辑好像是获取当前支持的分辨率
function getSnapCapability() {
    $("#CaptureFbjso").empty();
    $.ajax({
        url: config.baseUrl + "/Snapshot/Capability",
        type: "get",
        async: false,
        timeout: 15000,

        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            var ResolutionLength = $(xmlDoc).find('SnapshotCapabilityList').eq(0).find('SnapshotCapability').length;
            for (var i = 0; i < ResolutionLength; i++) {
                rWidths = $(xmlDoc).find('SnapshotCapabilityList').eq(0).find('SnapshotCapability').eq(i).find('ResolutionWidth').text();
                rHeights = $(xmlDoc).find('SnapshotCapabilityList').eq(0).find('SnapshotCapability').eq(i).find('ResolutionHeight').text();
                Resolutions.push(rWidths + '*' + rHeights);
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });

}
// 获取当前定时抓图配置
function getShorttimeCaoture() {
    $.ajax({
        url: config.baseUrl + "/Snapshot/TimedCaptureCfg",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            $("#CaptureEnable").prop('checked', JSON.parse($(xmlDoc).find('TimedCaptureConfig ').eq(0).find('Enable').eq(0).text()));
            $("#ptosd").prop('checked', JSON.parse($(xmlDoc).find('TimedCaptureSD').eq(0).find('Enable').eq(0).text()));
            $("#ptoftp").prop('checked', JSON.parse($(xmlDoc).find('TimedCaptureFTP').eq(0).find('Enable').eq(0).text()));
            // $("#ptomqtt").prop('checked', JSON.parse($(xmlDoc).find('TimedCaptureMQTT').eq(0).find('Enable').eq(0).text()));
            $("#Capturecounts").select2('val', $(xmlDoc).find('CapturePictureCount').eq(0).text()); //抓拍张数
            var time = $(xmlDoc).find('TimeInterval').eq(0).text(); //间隔时间
            $("#userForsnowtime").val(time);
            $("#CaptureEnable").change();
        },
        error: function(xhr, textStatus, errorThrown) {}
    })
}

function isIntegerInRange(input) {
    // 先转换为数字，以便进行数值比较
    const number = Number(input);

    // 检查数字是否在指定范围内（包括边界）
    if (number >= 10 && number <= 86400) {
        // 使用正则表达式检查输入是否为正整数
        // ^表示字符串开始，\d+表示一个或多个数字，$表示字符串结束
        const regex = /^\d+$/;
        return regex.test(input);
    }

    // 如果数字不在范围内，返回false
    return false;
}

// 下发当前定时抓图配置
function setShorttimeCaoture() {
    var interval;
    if (isIntegerInRange($("#userForsnowtime").val())) {
        interval = $("#userForsnowtime").val() - 0;
    } else {
        $.optionBootoast($.i18n.prop('i18n-inputrange'), "danger");
        return;
    }
    var xml = "<?xml version='1.0'' encoding='utf-8' ?>" +
        "<TimedCaptureConfig Version='1.0'>" +
        "<Enable>" + $("#CaptureEnable").is(':checked') + "</Enable>" +
        "<TimedCaptureFTP Version='1.0'><Enable>" + $("#ptoftp").is(':checked') + "</Enable>" +
        "<CapturePictureCount>" + ($("#Capturecounts").val() || '') + "</CapturePictureCount>" +
        "<TimeInterval>" + interval + "</TimeInterval>" +
        "</TimedCaptureFTP><TimedCaptureSD Version='1.0'>" +
        "<Enable>" + $("#ptosd").is(':checked') + "</Enable>" +
        "<CapturePictureCount>" + ($("#Capturecounts").val() || '') + "</CapturePictureCount>" +
        "<TimeInterval>" + interval + "</TimeInterval>" +
        "</TimedCaptureSD></TimedCaptureConfig>"
    var cyURL = config.baseUrl + "/Snapshot/TimedCaptureCfg";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: true,
        processData: false,
        data: xml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr);
        }
    });
}