var lmd = ['high', 'middle', 'low'];
var sylx = ['custom', 'alarm', 'dog', 'warning area', 'monitoring area', 'welcome', 'Deep Water Warning', 'Private territory', 'danger zone', 'Valuable objects', 'High Warning', 'Private Parking']
var bcs = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
var bcm = ['5', '10', '20', '30'];
var imgindex, xmlDocvideo, xmlAudioAlarmConfig, xmlDocPolygon;
var timeplaned, timeplandvoice;
var xhrState;
var motionD = true;
var number = 0;
var ydStatus = false;
$(document).ready(function() {
    motionLink();
    if (!$('.select2').hasClass('select2-offscreen')) {
        $(".select2").select2({
            minimumResultsForSearch: -1,
            width: 220,
        });
    }
    // 初始化时间选择
    var mq = $("#recordDiv").TimePlan({
        sectionNum: 6
    });
    var mh = $("#Broadcast").TimePlan({
        sectionNum: 6
    });
    timeplaned = mq;
    timeplandvoice = mh;
    selectvalue();
    getVideoShelterAlarmCfg(timeplaned, timeplandvoice);
    // 点击使能
    $("#videoCheck").change(function() {
        if ($(this).is(":checked")) {
            $(".ydsty").show();
            $("#syidsave").hide();
            changeTab();
        } else {
            $(".ydsty").hide();
            $("#syidsave").show();
            $("#LinkageMode").hide()
            $(".defence-config").hide()

        }
    });
    // 切换栏目
    $("#place").click(function() {
        $(".ydsty").show();
        $(".defence-config").hide();
        $("#LinkageMode").hide();
        changeTab()
    });
    $("#defence").click(function() {
        var qu = document.getElementById('place')
        var ld = document.getElementById('liand')
        var de = document.getElementById('defence')
        de.classList.add('qutable')
        qu.classList.remove('qutable')
        ld.classList.remove('qutable')
        $("#LinkageMode").hide()
        $(".content-layout").hide()
        $(".defence-config").show()

    });
    $("#liand").click(function() {
        var qu = document.getElementById('place')
        var ld = document.getElementById('liand')
        var de = document.getElementById('defence')
        ld.classList.add('qutable')
        qu.classList.remove('qutable')
        de.classList.remove('qutable')
        $("#LinkageMode").show()
        $(".content-layout").hide()
        $(".defence-config").hide()
    });
    $('#showModel').click(function(v) {
        getVoiceTimeto(timeplandvoice);
    });
    // 是否展示时间控件
    $('#DefensePlan').change(function(v) {
        if (v.val == 'false') {
            $('#recordDiv').show()
        } else {
            $('#recordDiv').hide()
        }
    });
    $('#deploymentTime').change(function(v) {
        if ($(this).select2('val') == 'false') {
            $("#showModel").show();
        } else {
            $("#showModel").hide();
        }
    });

    $('#chuBeepAlert').change(function() {
        if ($(this).is(':checked') == false) {
            $(".lgelecheck").hide();
        } else {
            $(".lgelecheck").show();
        }
    });
    // if (config.deviceCap[number].motionAudio == "true") {
    //     $(".lgelecheck").show();
    // } else {
    //     $(".lgelecheck").hide();
    // };
    // 点击试听按钮
    $("#videobtn").click(function() {
        setTryvoice('VideoShelter')
    });
    // 点击保存
    $("#chusave,#svhusave,#syidsave,#defencesave").click(function() {
            if ("admin" == config.user || "super_admin" == config.user) {
                var timeArrp = takeZero(mq.getvalue()); //普通布防
                var timeArr = takeZero(mh.getvalue()); //声音布防
                setVideoShelterAlarmCfg(timeArrp, timeArr);
            } else {
                $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
            }

        })
        //弹框保存
    $("#voiceSave").click(function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            var timeArrp = takeZero(mq.getvalue()); //普通布防
            var timeArr = takeZero(mh.getvalue()); //声音布防
            setVideoShelterAlarmCfg(timeArrp, timeArr);
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
        }

    })




});

function getVoiceTimeto(m) {
    $.ajax({
        url: window.config.baseUrl + "/System/VideoShelterAlarmCfg",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            setScheduleX(xmlDoc, m);
            $("#myModal").modal('show');
            $('#Broadcast').show();
        },
        error: function(xhr, textStatus, errorThrown) {}
    });

}

function motionLink() {
    $(".email").toggle(config.deviceCap[number].motionEmail == "true");
    $(".isChuTriggerpush").toggle(config.deviceCap[number].motionPush == "true");
    $(".isChuBeepAlert").toggle(config.deviceCap[number].motionAudio == "true");
    $(".isChuftp").toggle(config.deviceCap[number].motionFtp == "true");
    $(".isChuAlarmOut").toggle(config.deviceCap[number].motionAlarmOut == "true");
    $(".isSD").toggle(config.deviceCap[number].diskEnable == "true");

    if (config.deviceAiCap[number].ControlModeText == '' || config.deviceAiCap[number].ControlModeText == 'Duration') {
        $(".Frequency-broadcast").toggle(false);
        $(".Delay-time").toggle(true);
    } else {
        $(".Frequency-broadcast").toggle(true);
        $(".Delay-time").toggle(false);
    }
}
// 栏目切换
function changeTab() {
    var qu = document.getElementById('place')
    var ld = document.getElementById('liand')
    var de = document.getElementById('defence')
    qu.classList.add('qutable')
    ld.classList.remove('qutable')
    de.classList.remove('qutable')
}
// 初始化下拉框数据
function selectvalue() {
    changeTab()
    $("<option value='true'>" + $.i18n.prop("i18n-allday") + "</option>").appendTo("#DefensePlan");
    $("<option value='false'>" + $.i18n.prop("i18n-customize") + "</option>").appendTo("#DefensePlan");
    var ni = $.i18n.prop("i18n-sensitivity-value").split(",")
    for (var i = 0; i < ni.length; i++) {
        $("<option value='" + lmd[i] + "'>" + ni[i] + "</option>").appendTo("#sensitivity");
    }
    // 声音类型
    if (config.deviceAiCap[number].voiceAlarmint == 'true') {
        soundType('SoundType', config.deviceCap[number].AudioAlarmType);
    } else {
        soundType('SoundType', config.deviceAiCap[number].spzdaudioVoicetype);
    }
    // 阈值和间隔
    for (var i = 1; i < 61; i++) {
        $("<option value='" + i + "'>" + i + "s</option>").appendTo("#VideoTimechexk");
        $("<option value='" + i + "'>" + i + "s</option>").appendTo("#smallTimeto");
    }
    // 播报次数
    var bc = $.i18n.prop("i18n-broadcast").split(",")
    for (var i = 0; i < bc.length; i++) {
        $("<option value='" + bcs[i] + "'>" + bc[i] + "</option>").appendTo("#FrequencyBroadcast");
    }

    // 延长时间
    var bm = $.i18n.prop("i18n-broadcast-miao").split(",")
    for (var i = 0; i < bm.length; i++) {
        $("<option value='" + bcm[i] + "'>" + bm[i] + "</option>").appendTo("#FrequencyDelay");
    }
}
//试听
function setTryvoice(v) {
    var voiceXmldoc = '<?xml version="1.0" encoding="UTF-8" ?>' +
        "<AudioAlarmConfig><ChannelID>1</ChannelID>" +
        "<PeopleAudioType></PeopleAudioType><CarAudio></CarAudio>" +
        "<FireAudioType></FireAudioType><AudioOutputDelay></AudioOutputDelay>" +
        "<AudioVolume></AudioVolume>" +
        "<TryListenType>" + v + "</TryListenType>" +
        "<AlarmInExAudioType></AlarmInExAudioType>" +
        "<VideoShelterAudioType>" + $("#SoundType").val() + "</VideoShelterAudioType>" +
        "<MotionAudioType></MotionAudioType>" +
        "<ElectronicDenceAudioType></ElectronicDenceAudioType>" +
        "<CrossBorderDetectAudioType></CrossBorderDetectAudioType>" +
        "<OffDutyDetectAudioType></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 getVideoShelterAlarmCfg(mq, mh) {
    $.ajax({
        url: window.config.baseUrl + "/System/VideoShelterAlarmCfg",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            xmlDocvideo = xmlDoc;
            ydStatus = JSON.parse($(xmlDoc).find('VideoShelterAlarmCfg').eq(0).find('Enable').eq(0).text());
            $("#videoCheck").prop('checked', ydStatus)
            if (!ydStatus) {
                $(".content-layout").hide()
                $(".tab-sty").hide()
                $("#syidsave").show()

            } else {
                $(".content-layout").show()
                $(".tab-sty").show();
                changeTab();
            }
            $("#sensitivity").val($(xmlDoc).find('VideoShelterAlarmCfg').eq(0).find('Sensitivity').eq(0).text()).trigger('change');
            $("#VideoTimechexk").val($(xmlDoc).find('VideoShelterAlarmCfg').eq(0).find('ShelterTimeThreshold').eq(0).text()).trigger('change');
            $("#smallTimeto").val($(xmlDoc).find('VideoShelterAlarmCfg').eq(0).find('MinShelterInterval').eq(0).text()).trigger('change');
            //普通布防
            $("#DefensePlan").val($(xmlDoc).find('VideoShelterAlarmCfg').eq(0).find('Schedule').eq(0).find('AllDay').eq(0).text()).trigger('change');
            if ($("#DefensePlan").val() == 'false') {
                $("#recordDiv").show()
            } else {
                $("#recordDiv").hide()
            }
            setScheduleXp(xmlDoc, mq);
            // 联动
            $("#chuBeepAlert").prop('checked', JSON.parse($(xmlDoc).find('VideoShelterAlarmCfg').eq(0).find('BeepAlert').eq(0).find('Enable').text())); //触发声音报警
            if ($("#chuBeepAlert").is(':checked') == false) {
                $(".lgelecheck").hide();
            } else {
                $(".lgelecheck").show();
            }
            $("#chuAlarmOut").prop('checked', JSON.parse($(xmlDoc).find('VideoShelterAlarmCfg').eq(0).find('AlarmOut').eq(0).find('Enable').text())); //触发报警输出
            $("#chuTriggerpush").prop('checked', JSON.parse($(xmlDoc).find("Push").find("Enable").text())); //触发推送
            // 声音报警
            $("#SoundType").val($(xmlDoc).find('VideoShelterAlarmCfg').eq(0).find('VoiceType').eq(0).text()).trigger('change'); //声音报警类型
            $("#FrequencyBroadcast").val($(xmlDoc).find('VideoShelterAlarmCfg').eq(0).find('BroadcastCount').eq(0).text()).trigger('change'); //播报次数
            var o = $(xmlDoc).find('VideoShelterAlarmCfg').eq(0).find('DayMode').eq(0).text(); //声音报警布防时间
            if (o == "disable") {
                $("#deploymentTime").val($(xmlDoc).find('VideoShelterAlarmCfg').eq(0).find('AllDay').eq(0).text()).trigger('change');
            } else {
                $("#deploymentTime").val(o).trigger('change')
            }
            // 声音报警布防时间
            if ($("#deploymentTime").val() == 'false') {
                $("#showModel").show()
            } else {
                $("#showModel").hide()
            }
            setScheduleX(xmlDoc, mh);

        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}
// 设置声音报警布防区域
function setScheduleX(d, btimecaset) {
    // 转换xml中的时间
    var timeArr = [];
    var time = [];
    for (var i = 0; i < 7; i++) {
        timeArr[i] = $(d).find('VoiceAlarmSchedule').find('TimeBlock_' + i).eq(0).text()
        for (var o = 0; o < 24; o++) {
            if (timeArr[i].charAt(2 * o) == 1) {
                time.push(1)
            } else {
                time.push(0)
            }
        }
    }
    btimecaset.setValue(changetimeFool(group(time, 24)));
}
// 设置普通布防区域
function setScheduleXp(d, btimecasetp) {
    // 转换xml中的时间
    var timeArr = [];
    var time = [];
    for (var i = 0; i < 7; i++) {
        timeArr[i] = $(d).find('Schedule').find('TimeBlock_' + i).eq(0).text()
        for (var o = 0; o < 24; o++) {
            if (timeArr[i].charAt(2 * o) == 1) {
                time.push(1)
            } else {
                time.push(0)
            }
        }
    }
    btimecasetp.setValue(changetimeFool(group(time, 24)));
}
// 保存视频遮挡
function setVideoShelterAlarmCfg(vale, quert) {
    $(xmlDocvideo).find("VideoShelterAlarmCfg").eq(0).find("Sensitivity").eq(0).text($("#sensitivity").val());
    $(xmlDocvideo).find("VideoShelterAlarmCfg").eq(0).find("ShelterTimeThreshold").eq(0).text($("#VideoTimechexk").val());
    $(xmlDocvideo).find("VideoShelterAlarmCfg").eq(0).find("MinShelterInterval").eq(0).text($("#smallTimeto").val());
    $(xmlDocvideo).find("VideoShelterAlarmCfg").eq(0).find("Enable").eq(0).text($("#videoCheck").is(':checked'));
    $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('Schedule').eq(0).find('AllDay').text($("#DefensePlan").val());
    $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('BeepAlert').eq(0).find('Enable').text($("#chuBeepAlert").is(':checked'));
    $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('AlarmOut').eq(0).find('Enable').text($("#chuAlarmOut").is(':checked'));
    $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('Push').eq(0).find('Enable').text($("#chuTriggerpush").is(':checked'));
    $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('Mail').eq(0).find('Enable').text($("#chuemail").is(':checked'));
    $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('Ftp').eq(0).find('Enable').text($("#chuftp").is(':checked'));
    $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('Snapshot').eq(0).find('Enable').text($("#chudpick").is(':checked'));
    $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('Record').eq(0).find('Enable').text($("#chudvdeo").is(':checked'));
    $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('VoiceType').text($("#SoundType").val()); //声音报警布防类型
    $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('BroadcastCount').text($("#FrequencyBroadcast").val()); //播报次数
    var d, t
    d = $("#deploymentTime").val()
    if (d == "false") {
        d = "false"
        t = "disable"
    } else if (d == "true") {
        d = "true"
        t = "disable"
    } else if (d == "evening") {
        d = "true"
        t = "evening"
    } else {
        d = "true"
        t = "day"
    }
    $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('AllDay').eq(1).text($("#DefensePlan").val());
    $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('DayMode').eq(0).text(t);
    $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('AllDay').eq(0).text(d);
    var adarr = vale[vale.length - 1]
    vale.unshift(adarr)
    vale.pop()
        // 原本的布防区域
    for (i = 0; i < 7; i++) {
        $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('Schedule').find('TimeBlock_' + i).eq(0).text(vale[i]);
    };

    var pdarr = quert[quert.length - 1]
    quert.unshift(pdarr)
    quert.pop()
        // 声音报警布防区域
    for (k = 0; k < 7; k++) {
        $(xmlDocvideo).find('VideoShelterAlarmCfg').eq(0).find('VoiceAlarmSchedule').find('TimeBlock_' + k).eq(0).text(quert[k]);
    };

    var cyURL = window.config.baseUrl + "/System/VideoShelterAlarmCfg";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: xmlDocvideo,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            // getMotionconfig(timeplaned, timeplandvoice)
            SaveState(xhr);

        }
    });

}