var gs_xml_doc, user = config.user,
    pwd = config.password;
var number = 0
var FireSupportVoice, MotionSupportVoice, EleSupportVoice, CroSupportVoice, OffSupportVoice, OutSupportVoice = null
$(document).ready(function() {
    initAudioPage();
    getaudiocfgfromdevice();
    $('#AudioStreamsave,#audioOutSave').click(function() {
        if ("admin" == user || "super_admin" == user) {
            setaudiocfgfromdevice();
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
        }
    });
});

function initAudioPage() {
    if (!$('.select2').hasClass('select2-offscreen')) {
        $(".select2").select2({
            minimumResultsForSearch: -1,
            width: 220
        });
    }
    var st = $.i18n.prop("i18n-str_voice_type").split(",")
    $("<span>" + st[2] + "</span>").appendTo('.dog');
    $("<span>" + st[1] + "</span>").appendTo('.alarm');
    $("<span>" + st[3] + "</span>").appendTo('.warning');
    $("<span>" + st[4] + "</span>").appendTo('.monitoring');
    $("<span>" + st[5] + "</span>").appendTo('.welcome');
    $("<span>" + st[6] + "</span>").appendTo('.DeepWater');
    $("<span>" + st[7] + "</span>").appendTo('.territory');
    $("<span>" + st[8] + "</span>").appendTo('.danger');
    $("<span>" + st[9] + "</span>").appendTo('.Valuable');
    $("<span>" + st[10] + "</span>").appendTo('.High');
    $("<span>" + st[11] + "</span>").appendTo('.Parking');
    FireSupportVoice = getAudioTypelist($(config.deviceAiCap[number].FiredetectAudioType), 'fire')
    MotionSupportVoice = getAudioTypelist($(config.deviceCap[number].ydzcAudioAlarmType), 'Motion')
    EleSupportVoice = getAudioTypelist($(config.deviceAiCap[number].dzwlaudioVoicetype), 'ElectronicDence')
    CroSupportVoice = getAudioTypelist($(config.deviceAiCap[number].yjzcaudioVoicetype), 'CrossBorderDetect')
    OffSupportVoice = getAudioTypelist($(config.deviceAiCap[number].lgjcaudioVoicetype), 'OffDutyDetect')
    OutSupportVoice = getAudioTypelist($(config.deviceAiCap[number].flowleAudioType), 'PassengerOut')
        // var InSupportVoice = getAudioTypelist($(config.deviceAiCap[number].flowenAudioType), 'PassengerIn')
    var mergedArray = [];
    for (var i = 0; i < FireSupportVoice.b.length; i++) {
        if (mergedArray.indexOf(FireSupportVoice.b[i]) == -1) {
            mergedArray.push(FireSupportVoice.b[i]);
        }
    }
    for (var q = 0; q < MotionSupportVoice.b.length; q++) {
        if (mergedArray.indexOf(MotionSupportVoice.b[q]) == -1) {
            mergedArray.push(MotionSupportVoice.b[q]);
        }
    }
    for (var r = 0; r < EleSupportVoice.b.length; r++) {
        if (mergedArray.indexOf(EleSupportVoice.b[r]) == -1) {
            mergedArray.push(EleSupportVoice.b[r]);
        }
    }
    for (var t = 0; t < CroSupportVoice.b.length; t++) {
        if (mergedArray.indexOf(CroSupportVoice.b[t]) == -1) {
            mergedArray.push(CroSupportVoice.b[t]);
        }
    }
    for (var y = 0; y < OffSupportVoice.b.length; y++) {
        if (mergedArray.indexOf(OffSupportVoice.b[y]) == -1) {
            mergedArray.push(OffSupportVoice.b[y]);
        }
    }
    for (let u = 0; u < OutSupportVoice.b.length; u++) {
        if (mergedArray.indexOf(OutSupportVoice.b[u]) == -1) {
            mergedArray.push(OutSupportVoice.b[u]);
        }
    }
    showSupportVoice(mergedArray)
    var deviceCap = config.deviceCap[0];
    if (deviceCap.G711u == "true") {
        $('#auFormat').empty();
        $("<option value='G.711U'>G.711u</option>").appendTo("#auFormat");
    }
    if (deviceCap.G711a == "true") {
        $("<option value='G.711A'>G.711a</option>").appendTo("#auFormat");
    }
    if (deviceCap.AAC == "true") {
        $("<option value='AAC'>AAC</option>").appendTo("#auFormat");
    }
    if (deviceCap.G726 == "true") {
        $("<option value='G.726'>G.726</option>").appendTo("#auFormat");
    }
    var deviceInfo = config.deviceInfo;
    deviceInfo.TwoWayAudio == 'true' ? $('#outVolumeItme').show() : $('#outVolumeItme').hide();
}
// 初始化进度条
function drawVolume() {
    $('#inputvolume').jRange({
        from: 0,
        to: 100,
        // step: 1,
        scale: 1,
        format: '%s',
        width: 360,
        showLabels: false,
        showScale: false,
        onstatechange: function() {
            $("#inputvolumevalues").text($("#inputvolume").val());
        },
        onSetPosition: function() {
            $("#inputvolumevalues").text($("#inputvolume").val());
        },
        onMouseDown: function() {},
        onMouseUp: function() {

        }
    });
    $('#outvolume').jRange({
        from: 0,
        to: 100,
        // step: 1,
        scale: 1,
        format: '%s',
        width: 360,
        showLabels: false,
        showScale: false,
        onstatechange: function() {
            $("#outvolumevalues").text($("#outvolume").val());
        },
        onSetPosition: function() {
            $("#outvolumevalues").text($("#outvolume").val());
        },
        onMouseDown: function() {},
        onMouseUp: function() {

        }
    });
};

function getaudiocfgfromdevice() {
    $.ajax({
        url: config.baseUrl + "/Streams/AudioStream",
        type: "GET",
        async: true,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            //获取数据成功之后，刷新界面
            gs_xml_doc = xmlDoc;
            $("#AudioInMethod").select2('val', $(xmlDoc).find('AudioStream').eq(0).find('AudioInMethod').eq(0).text());
            $("#auFormat").select2('val', $(xmlDoc).find('AudioStream').eq(0).find('AudioInCodec').eq(0).text());
            $("#inputvolume").val($(xmlDoc).find('AudioStream').eq(0).find('AudioInVolume').text());
            $("#inputvolumevalues").text($(xmlDoc).find('AudioStream').eq(0).find('AudioInVolume').text());
            $("#outvolume").val($(xmlDoc).find('AudioStream').eq(0).find('AudioOutVolume').text());
            $("#outvolumevalues").text($(xmlDoc).find('AudioStream').eq(0).find('AudioOutVolume').text());
            drawVolume();

        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}

function setaudiocfgfromdevice() {
    var cyXml = gs_xml_doc;
    $(cyXml).find('AudioStream').eq(0).find('AudioInMethod').text($("#AudioInMethod").val());
    $(cyXml).find('AudioStream').eq(0).find('AudioInCodec').text($("#auFormat").val());
    $(cyXml).find('AudioStream').eq(0).find('AudioInVolume').text($("#inputvolume").val());
    $(cyXml).find('AudioStream').eq(0).find('AudioOutVolume').text($("#outvolume").val());
    //保存
    var cyURL = config.baseUrl + "/Streams/AudioStream";
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr) {
            SaveState(xhr);
        },
        error: function(xhr) {
            $.optionBootoast($.i18n.prop('i18n-savefail'), "danger")
        }
    });
}

function tylensionType(dtype) {
    var type = "";
    var aty = "";
    var bty = "";
    var cty = "";
    var dty = "";
    var ety = "";
    if (MotionSupportVoice.b.indexOf(dtype) != -1) {
        type = MotionSupportVoice.a
        aty = dtype
    } else if (FireSupportVoice.b.indexOf(dtype) != -1) {
        type = FireSupportVoice.a
        bty = dtype
    } else if (EleSupportVoice.b.indexOf(dtype) != -1) {
        type = EleSupportVoice.a
        cty = dtype
    } else if (CroSupportVoice.b.indexOf(dtype) != -1) {
        type = CroSupportVoice.a
        dty = dtype
    } else if (OffSupportVoice.b.indexOf(dtype) != -1) {
        type = OffSupportVoice.a
        ety = dtype
    }
    var voiceXmldoc = '<?xml version="1.0" encoding="UTF-8" ?>' +
        "<AudioAlarmConfig><ChannelID>1</ChannelID>" +
        "<PeopleAudioType></PeopleAudioType><CarAudio></CarAudio>" +
        "<FireAudioType>" + bty + "</FireAudioType><AudioOutputDelay></AudioOutputDelay>" +
        "<AudioVolume></AudioVolume>" +
        "<TryListenType>" + type + "</TryListenType>" +
        "<AlarmInExAudioType></AlarmInExAudioType>" +
        "<VideoShelterAudioType></VideoShelterAudioType>" +
        "<MotionAudioType>" + aty + "</MotionAudioType>" +
        "<ElectronicDenceAudioType>" + cty + "</ElectronicDenceAudioType>" +
        "<CrossBorderDetectAudioType>" + dty + "</CrossBorderDetectAudioType>" +
        "<OffDutyDetectAudioType>" + ety + "</OffDutyDetectAudioType>" +
        "</AudioAlarmConfig>"
    var cyURL = window.config.baseUrl + "/System/1/TryListenSelectedAlarmAudioV1";
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: voiceXmldoc,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr, 1);
        }
    });
}
// 显示支持的声音哦类型
function showSupportVoice(data) {
    for (var i = 0; i < data.length; i++) { //目前最多支持的种类为14，但是实际支持有36，其他不清楚在哪儿获取
        if (data[i] == "alarm") {
            $('.alarmdiv').show()
        } else if (data[i] == "dog") {
            $(".dogdiv").show()
        } else if (data[i] == "warning area") {
            $('.warningdiv').show()
        } else if (data[i] == "monitoring area") {
            $('.monitoringdiv').show()
        } else if (data[i] == "welcome") {
            $('.welcomediv').show()
        } else if (data[i] == "Deep Water Warning") {
            $('.DeepWaterdiv').show()
        } else if (data[i] == "Private territory") {
            $('.territorydiv').show()
        } else if (data[i] == "danger zone") {
            $('.dangerdiv').show()
        } else if (data[i] == "Valuable objects") {
            $('.Valuablediv').show()
        } else if (data[i] == "High Warning") {
            $('.Highdiv').show()
        } else if (data[i] == "Private Parking") {
            $('.Parkingdiv').show()
        }
        // else if (data[i] == "FireAlarm") {
        //     $('.FireAlarm').show()
        // }
    }
}
// 获取设备中每种音频类型
function getAudioTypelist(data, str) {
    var obj = {}
    var arr = []
        //目前最多支持的种类为14，但是实际支持有36，其他不清楚在哪儿获取
    if (data.find("Alarm").text() == "true") {
        arr.push('alarm')
    }
    if (data.find("dog").text() == "true") {
        arr.push("dog")
    }
    if (data.find("warning").text() == "true") {
        arr.push('warning area')
    }
    if (data.find("monitoring").text() == "true") {
        arr.push('monitoring area')
    }
    if (data.find("welcome").text() == "true") {
        arr.push('welcome')
    }
    if (data.find("DeepWater").text() == "true") {
        arr.push('Deep Water Warning')
    }
    if (data.find("PrivateTerritory").text() == "true") {
        arr.push('Private territory')
    }
    if (data.find("DangerZone").text() == "true") {
        arr.push('danger zone')
    }
    if (data.find("ValuableObjects").text() == "true") {
        arr.push('Valuable objects')
    }
    if (data.find("HighWarning").text() == "true") {
        arr.push('High Warning')
    }
    if (data.find("PrivateParking").text() == "true") {
        arr.push('Private Parking')
    }
    if (data.find("FireAlarm").text() == "true") {
        arr.push('FireAlarm')
    }

    obj.a = str;
    obj.b = arr
    return obj;
}