var qualityvl = ['20', '40', '60', '80', '100'];
var zdlx = ['custom', 'alarm', 'dog', 'warning area', 'monitoring area', 'welcome', 'Deep Water Warning', 'Private territory', 'danger zone', 'Valuable objects', 'High Warning', 'Private Parking', 'HasFaceMask', 'NoFaceMask'];
var bbcs = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
var imgindex;
var lx, ly, botx, boty;
var menbfrx = 9999 / 560;
var menbfry = 9999 / 420;
var newPointList;
var newLineList = [];
var newPersonList = [];
var ptonbuf, yuyinbuf;
var xhrState;
var faceState = true;
var number = 0;
var faceTime, faceTimeVoice, kouBrathTime;
var trgle = [{
    x: Math.floor(30 * 100 / getRatio()),
    y: Math.floor(30 * 100 / getRatio())
}, {
    x: Math.floor(200 * 100 / getRatio()),
    y: Math.floor(30 * 100 / getRatio())
}, {
    x: Math.floor(30 * 100 / getRatio()),
    y: Math.floor(200 * 100 / getRatio())
}]; //三角形默认位置
var trgleFour = [{
    x: 30,
    y: 30
}, {
    x: 300,
    y: 30
}, {
    x: 300,
    y: 200
}, {
    x: 30,
    y: 200
}]; //四边形默认位置
var trgleFive = [{
    x: 180,
    y: 30
}, {
    x: 30,
    y: 130
}, {
    x: 60,
    y: 250
}, {
    x: 300,
    y: 250
}, {
    x: 330,
    y: 130
}]; //五边形默认位置
var trgleSex = [{
    x: 30,
    y: 30
}, {
    x: 300,
    y: 30
}, {
    x: 300,
    y: 50
}, {
    x: 150,
    y: 50
}, {
    x: 150,
    y: 100
}, {
    x: 30,
    y: 100
}]; //六边形默认位置
var trgleSeven = [{
    x: 60,
    y: 100
}, {
    x: 100,
    y: 70
}, {
    x: 200,
    y: 80
}, {
    x: 250,
    y: 160
}, {
    x: 200,
    y: 220
}, {
    x: 100,
    y: 200
}, {
    x: 50,
    y: 150
}]; //七边形默认位置
var trgleEight = [{
    x: 100,
    y: 50
}, {
    x: 300,
    y: 50
}, {
    x: 300,
    y: 100
}, {
    x: 250,
    y: 100
}, {
    x: 250,
    y: 150
}, {
    x: 150,
    y: 150
}, {
    x: 150,
    y: 100
}, {
    x: 100,
    y: 100
}, ]; //八边形默认位置
var IsNeedReboot = false,
    rebootObj = {};

//识别
var qualityvl = ['20', '40', '60', '80', '100'];
var zdlx = ['custom', 'alarm', 'dog', 'warning area', 'monitoring area', 'welcome', 'Deep Water Warning', 'Private territory', 'danger zone', 'Valuable objects', 'High Warning', 'Private Parking', 'HasFaceMask', 'NoFaceMask'];
var bbcs = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
var bcs = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
var bcm = ['5', '10', '20', '30'];
var week = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"]
var linkOverlayHumanBox = "";
var mustdon, openstake;
var OpenDoorMode = "";
var oldXml;
var recordlistData; //存放所有脸库
var recordCount = 0; //是别记录总条数
var _table = null;
var _tabled = null;
var persionData = []; //人员数据收集
var blistData = []; //用于比较的数组
var oldvalue = ""; //旧的id
var pagesize = 10;
var currentpagenumber = 1;
var setData = [];
var yuyinbuf, ptonbuf;
var personCount, currentfaceXmld, currentsXmld; ///人员总条数
var gunstate = true; //默认为true,处理滚动时不需要调插件移动方法导致的问题
var faceTime, faceTimeVoice, kouBraceTime;
var menbfrx = 9999 / 560;
var menbfry = 9999 / 420;
var react, react1; //保存时间对象
var dd, IsNeedReboot = false,
    xmlAlarmLink, xmlLight;
var number = 0;
var rebootObj = {};
$(document).ready(function() {
    if (!config.isPush) {
        config.isPush = enablePush(); //网络端口号
    }
    if (!$('.select2').hasClass('select2-offscreen')) {
        $(".select2").select2({
            minimumResultsForSearch: -1,
            width: 220,
        });
    }
    ScalePitchImg('svgimgdef')
        //识别****************
    $("#weekMode,#effectiveMode").select2({
        width: 280,
        minimumResultsForSearch: -1,
    });
    react = $("#alarm-plan").TimePlan({ //语音布放
        sectionNum: 6
    });
    react1 = $("#alarm-plan-schedule").TimePlan({ //布放时间
        sectionNum: 6
    });
    if (config.deviceCap[number].AlarmLinkage == 'true') {
        $('#alarm-linkage').show();
    } else {
        $('#alarm-linkage').hide();
    }
    if (config.deviceAiCap[number].Audiovolumex == 'true') {
        $('#isshowactiveBrightness').show();
    } else {
        $('#isshowactiveBrightness').hide();
    }
    //人脸初始化时间选择
    changeTabFacerecognition(); //默認點擊
    faceGroupsQueryAll();
    getFacesManagement();
    $("#facesmanagement").click();
    var lk = document.getElementById('facesmanagement');
    var ry = document.getElementById('personrecord');
    var alarm = document.getElementById('alarm-linkage');
    var de = document.getElementById('persondefence');
    $('#isShowFaces').change(function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            if ($(this).is(':checked')) {
                config.isShowFaces = true;
                if (config.deviceCap[number].FaceRecoFlag == "true") {
                    rebootObj = needReboot(7);
                    IsNeedReboot = rebootObj.isReBoot;
                    if (rebootObj.isReBoot == 'true') {
                        var isUpplementary = rebootObj.hasOwnProperty('isUpplementary') ? rebootObj.isUpplementary : 0;
                        $.RestartModel.mask(setFaceRecoBaseConfig, isUpplementary);
                        return;
                    }
                }
                setFaceRecoBaseConfig();
            } else {
                config.isShowFaces = false;
                IsNeedReboot = false;
                setFaceRecoBaseConfig();
            }

        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
        }
    })

    // 脸库管理
    $("#facesmanagement").click(function() {
        gunstate = false;
        config.dzld = true
        faceGroupsQueryAll();
        lk.classList.add('qutable');
        ry.classList.remove('qutable');
        alarm.classList.remove('qutable');
        $("#facesManagement").show();
        $("#personrecords").hide();
        $("#alarm-linkage-content").hide();
        getFacesManagement();
    });

    function getFacesManagement() {
        if (config.deviceCap[number].FaceLibConfig == '1') {
            $("#creatbtn").hide()
            $("#daorubtn").hide()
            $("#daochubtn").hide()
            $("#clearAllbtn").hide()
            var aoColumns = [{
                    "mData": "xid", //mDataProp
                    // "sWidth":"10%"//设置列宽
                },
                {
                    "mData": "GroupName",
                    "mRender": function(data) {
                            if (data == "VisitorList") {
                                return $.i18n.prop('i18n-face4');
                            } else if (data == "WhiteList") {
                                return $.i18n.prop('i18n-face2');
                            } else if (data == "BlackList") {
                                return $.i18n.prop('i18n-face3');
                            } else {
                                return data;
                            }
                        }
                        // "sWidth":"25%"//设置列宽
                },
                {
                    "mData": "PersonInfoCount",
                },
                {
                    "mData": "GroupThresholdValue",
                },
                {
                    "mData": "ValidPersonCount",
                },
                {
                    "mData": "InvalidPersonCount",
                },
                {
                    "mRender": function(data, type, full) { // 返回自定义内容
                        return '<span>' + $.i18n.prop('i18n-wifi-none') + '</span>';
                    },
                    "mData": null,
                }

            ];
        } else {
            var aoColumns = [{
                    "mData": "xid", //mDataProp
                    // "sWidth":"10%"//设置列宽
                },
                {
                    "mData": "GroupName",
                    "mRender": function(data) {
                            if (data == "VisitorList") {
                                return $.i18n.prop('i18n-face4');
                            } else if (data == "WhiteList") {
                                return $.i18n.prop('i18n-face2');
                            } else if (data == "BlackList") {
                                return $.i18n.prop('i18n-face3');
                            } else {
                                return data;
                            }
                        }
                        // "sWidth":"25%"//设置列宽
                },
                {
                    "mData": "PersonInfoCount",
                },
                {
                    "mData": "ValidPersonCount",
                },
                {
                    "mData": "InvalidPersonCount",
                },
                {
                    "mRender": function(data, type, full) { // 返回自定义内容
                        if (data.name == "unBindGroup" || data.name == "blackListGroup") {
                            return '<span class="operate" id="faceck">查看</span>';
                        } else {
                            return '<span class="operate" id="faceck">查看</span><span class="operate">编辑</span><span class="operate" style="color:red">删除</span>';
                        }

                    },
                    "mData": null,
                }
            ];
        }
        _tabled = new table("faceTable", {
            bProcessing: true,
            isCheckBox: false,
            retrieve: true, //可能是表格重复使用时受到影响 必须加上
            bPaginate: false, //翻页功能
            bLengthChange: false, //改变每页显示数据数量
            bFilter: false, //过滤功能
            bSort: false, //排序功能
            bInfo: false, //页脚信息
            bAutoWidth: false, //自动宽度
            aoColumns: aoColumns,
            aaData: recordlistData
        });
        $("#faceWeekDay").empty();
        for (var index = 1; index <= 7; index++) {
            $('<div class="week-itme weekItme' + index + '">' +
                '<label label class= "checkbox-inline labelcy" style = "margin-right:12px" > ' +
                '<input type="checkbox" class="faceweek_' + index + '"><span>' + week[index - 1] + '</span>' +
                '</label > ' +
                '<div class="time-box">' +
                '<input type = "text" class= "time-input form-control date-picker start_time">' +
                '<span>-</span>' +
                '<input type = "text" class= "time-input form-control date-picker end_time"> ' +
                '</div> ' +
                '<div class="time-box add-event add_' + index + '" data-index=' + index + '><img src="ipc/img/icon/shij_tianj.png" alt=""><span>添加</span></div>' +
                '<img src="ipc/img/icon/shij_fuzhi.png" class="copy" data-copy=' + index + '>' +
                '</div >').appendTo("#faceWeekDay")

        }
        initDatetimepicker();
    }
    //单双周tab切换
    $(".face-weekMode span").click(function(e) {
        $(".face-weekMode span").removeClass("weekActive");
        $(this).addClass("weekActive");
    });
    //使用on绑定动态添加的元素事件
    $("#faceWeekDay").on("click", ".add-event", function() {
        var index = $(this).attr("data-index");
        //在该事件对象的前面添加一个可以删除的时间输入框
        var html = '<div class="time-box deleteItme">' +
            '<input type="text"  class="time-input form-control start_time">' +
            '<span>-</span></span>' +
            '<input type="text"  class="time-input form-control end_time">' +
            '<img src="ipc/img/icon/shij_sc.png"class="delete-img" data-deletImg=' + index + '>' +
            '</div>'
        $(this).before(html);
        //给当前添加可删除时间输入框绑定datetimepicker
        $(this).prev(".deleteItme").find("input").datetimepicker({
            format: "hh:ii",
            autoclose: true, // 选择日期后关闭
            language: 'zh-cn', //显示语言为中文
            minuteStep: 1, //分钟步调
            startView: 1, //日期时间选择器打开之后首先显示的视图
        });
        $(this).prev(".deleteItme").find("input").eq(0).val("00:00");
        $(this).prev(".deleteItme").find("input").eq(1).val("23:59");
        $(".deleteItme .start_time").datetimepicker().on('changeDate', function(e) {
            $(this).siblings(".end_time").datetimepicker('setStartDate', e.date);

        });
        $(".deleteItme-box .end_time").datetimepicker().on('changeDate', function(e) {
            $(this).siblings(".start_time").datetimepicker('setEndDate', e.date);

        });
        if ($(this).siblings(".deleteItme").length > 5) {
            $(this).hide();
        }
    });
    //删除时间输入框事件
    $("#faceWeekDay").on("click", ".delete-img", function() {
        var index = $(this).attr("data-deletImg");
        $(this).parent(".deleteItme").remove();
        $(".add_" + index).show();
    });
    //点击复制 显示弹框
    $("#faceWeekDay").on("click", ".copy", function() {
        var index = $(this).attr("data-copy");
        $(".copy-week").find("input").eq(index - 1).prop("checked", true).attr("disabled", true);
        $(".copy-box").show();

    });
    // 所有周选中 则全选选中
    $(".copy-week").click(function(e) {
        var flag = true;
        var inputs = $(this).find("input");
        for (var index = 0; index < inputs.length; index++) {
            if (!$(inputs[index]).is(":checked")) {
                flag = false;
                break;
            }

        }
        $("#selectAll").prop("checked", flag);
    });
    //给全选按钮绑定点击事件
    $("#selectAll").change(function() {
        var ele = $(".copy-week").find("input");
        var selectAllState = $(this).is(":checked");
        ele.each(function(e) {
            $(this).prop("checked", selectAllState);
            if ($(this).attr("disabled")) $(this).prop("checked", true);
        });
    });
    //取消复制到
    $("#copyCancel").click(function() {
        var ele = $(".copy-week").find("input");
        ele.each(function(e) {
            $(this).prop("checked", false).attr("disabled", false);
        });
        $(".copy-box").hide();
    });

    // 点击查询
    $("#faceserch").click(function() {
        queryFaceRecognition();
    });
    $(".form_datetime").datetimepicker({
        format: 'yyyy-mm-dd hh:ii'
    });
    $(".form_datetimes").datetimepicker({
        format: 'yyyy-mm-dd hh:ii'
    });

    // 人员管理
    if (config.deviceCap[number].FaceLibConfig == "1") {
        $("#personrecord").show();
        $("#facesmanagement").show();
    } else {
        $("#personrecord").hide();
        $("#facesmanagement").hide();
    }
    $("#personrecord").click(function() {
        gunstate = false;
        config.dzld = true;
        c();
        d = new dTree('d');
        d.add(0, -1, $.i18n.prop('i18n-os'));
        for (var i = 0; i < persionData.length; i++) {
            var names = persionData[i].OrganizationName;
            if (names == 'WhiteList') {
                names = $.i18n.prop('i18n-face2');
            } else if (names == 'BlackList') {
                names = $.i18n.prop('i18n-face3');
            } else if (names == 'VisitorList') {
                names = $.i18n.prop('i18n-face4');
            }
            if (persionData[i].ParentLayerID == "0") {
                d.add(persionData[i].LayerID, 0, names,
                    "javascript: checkoUt(" + persionData[i].LayerID + ")")
            } else {
                d.add(persionData[i].LayerID, persionData[i].ParentLayerID, names, "javascript: checkoUt(" + persionData[i].LayerID + ")")
            }
        }
        document.getElementById("kjl").innerHTML = d;
        lk.classList.remove('qutable');
        alarm.classList.remove('qutable');
        de.classList.remove('qutable');
        ry.classList.add('qutable');
        $("#facesManagement").hide();
        $("#personrecords").show();
        $("#alarm-linkage-content").hide();
        $(".person-defence").hide();
        _table = null; //销毁
    });
    // **********报警联动start******************************************************************
    $("#alarm-linkage").click(function() {
        gunstate = false;
        config.dzld = true;
        lk.classList.remove('qutable');
        ry.classList.remove('qutable');
        alarm.classList.add('qutable');
        de.classList.remove('qutable');
        $("#facesManagement").hide();
        $("#personrecords").hide();
        $("#alarm-linkage-content").show();
        $(".person-defence").hide();
        initConfig();
        getAlarmLink();
        initTreeData();

    });
    $("#persondefence").click(function() {
        gunstate = false;
        config.dzld = true;
        lk.classList.remove('qutable');
        ry.classList.remove('qutable');
        alarm.classList.remove('qutable');
        de.classList.add('qutable');
        $("#facesManagement").hide();
        $("#personrecords").hide();
        $("#alarm-linkage-content").hide();
        $(".person-defence").show();


    });
    $('#eledeploymentTime').change(function(v) {
        if ($(this).select2('val') == 'false') {
            $('#showdelModel').show();
        } else {
            $('#showdelModel').hide();
        }
    });
    $("#alarm-link-save").click(function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            saveTreeData();
            saveAlarmLink();
            saveAlarmContronl();
            saveLightAlarm();
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
        }
    })
    $("#control-person").change(function() {
        var val = $(this).select2('val');
        if (val == 'OrganizationMember') {
            $('.stranger').show();
        } else {
            $('.stranger').hide();
        }
    });
    $("#schedule-time").change(function() {
        var val = $(this).select2('val');
        if (val == 'true') {
            $('.is-schedule-time').hide();
        } else {
            $('.is-schedule-time').show();
        }
    });
    $('#chuBeepAlert').change(function() {
        if ($(this).is(':checked') == false) {
            $(".alram-show").hide();
        } else {
            $(".alram-show").show();
        }
    });
    $('#FCLightalarm').change(function() {
        if ($(this).is(':checked') == false) {
            $(".light-show").hide();
        } else {
            $(".light-show").show();
        }
    });
    // 点击试听
    $("#eleCheckVoice").click(function() {
        var xml = '<FaceRecoAudioType>' + $("#eleSoundType").select2('val') + '</FaceRecoAudioType>';
        tryListen('FaceReco', xml);
    });
    // **********报警联动end******************************************************************
    // 点击人员查询
    $("#peoSearch").click(function() {
        if (!_table) {
            dataTableDraw("#personMange")
        } else {
            $("#personMange").dataTable().fnDraw()
        }
    });
    // 抓拍*******************************************************************
    if (config.deviceCap[number].Email == "true") {
        $(".email").show()
    } else {
        $(".email").hide()
    }
    if (config.isPush == true) {
        $(".isPush").show()
    } else {
        $(".isPush").hide()
    }
    if (config.deviceCap[number].diskEnable == "true") {
        $(".isSD").show()
    } else {
        $(".isSD").hide()
    }
    if (config.deviceCap[number].LightAlarm == "true") {
        $(".lightAlarm").show()
    } else {
        $(".lightAlarm").hide()
    }

    // 音量
    if (config.deviceAiCap[number].facevoicelume == "true") {
        $("#isshowfaceVoice").show()
    } else {
        $("#isshowfaceVoice").hide()
    }
    if (config.deviceAiCap[number].maskvoicelume == "true") {
        $("#isshowMaskVoice").show()
    } else {
        $("#isshowMaskVoice").hide()
    }
    if (config.gs_interval) {
        clearInterval(config.gs_interval)
    }
    ScalePitch("box-boder");
    // 初始化下拉框
    $("#Capturemode,#Facequality,#facezDefensePlan,#kouAlarmtype").select2({
        width: 360,
        minimumResultsForSearch: -1,
    });
    $("#kouFrequencyBroadcast,#koudeploymentTime,#FCFrequencyBroadcast,#FCdeploymentTime,#lglightmode,#lglightmode1").select2({
        width: 360,
        minimumResultsForSearch: -1,
    });
    $("#kouSoundType,#FCSoundType").select2({
        width: 320,
        minimumResultsForSearch: -1,
    });
    // 初始化时间选择
    var timespal = $("#recordDiv").TimePlan({
        sectionNum: 6
    });
    var timespald = $("#FCvoicelrecordDiv").TimePlan({
        sectionNum: 6
    });
    var koutimespald = $("#kouBroadcast").TimePlan({
        sectionNum: 6
    });
    faceTime = timespal;
    faceTimeVoice = timespald;
    kouBrathTime = koutimespald;
    $('#showKou').click(function(v) {
        $("#myModal").modal('show');
        $('#kouBroadcast').show();
        $('#FCvoicelrecordDiv').hide();
        $('#alarm-plan').hide();
    });
    $('#showdelModel').click(function(v) {
        $("#myModal").modal('show');
        $('#kouBroadcast').hide();
        $('#FCvoicelrecordDiv').hide();
        $('#alarm-plan').show();

    });
    $('#showLink').click(function(v) {
        $("#myModal").modal('show');
        $('#kouBroadcast').hide();
        $('#FCvoicelrecordDiv').show();
        $('#alarm-plan').hide();
    });
    $('#myTab a').click(function(e) {
        e.preventDefault();
        $(this).tab('show');
        if ($(this).attr("aria-controls") == "Facedetection") {
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                preHiddenDisplaywindow(4)
            }
        } else if ($(this).attr("aria-controls") == "Facerecognition") {
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                preHiddenDisplaywindow(4)
            }
        }
    });
    // 切换展示时间控件
    $('#facezDefensePlan').change(function(v) {
        if (v.val == 'false') {
            $('#recordDiv').show()
        } else {
            $('#recordDiv').hide()
        }
    });
    $('#FCdeploymentTime').change(function(v) {
        if (v.val == 'false') {
            $('#showLink').show()
        } else {
            $('#showLink').hide()
        }
    });
    $("#koudeploymentTime").change(function(v) {
        if (v.val == 'false') {
            $('#showKou').show()
        } else {
            $('#showKou').hide()
        }

    });
    // 抓拍模式切换
    $("#Capturemode").change(function(v) {
        if (v.val == 'custom') {
            $('.isshowCustom').show()
        } else {
            $('.isshowCustom').hide()
        }
    });
    // 0-90的限制
    $('#facedo,#doMaximum,#rollMaximum').on('input', function(e) {
        var input = $(this).val();
        var intRegex = /^(?:[1-8]?\d|90)$/;
        var isValid = intRegex.test(input);
        if (!isValid) {
            // 设置输入框的值为上一次的有效值
            $(this).val(input.substr(0, input.length - 1));
        }
    });
    // 0-100的限制
    $('#ambiguityMaximum').on('input', function(e) {
        var input = $(this).val();
        var intRegex = /^(?:[1-9]?\d|100)$/;
        var isValid = intRegex.test(input);
        if (!isValid) {
            // 设置输入框的值为上一次的有效值
            $(this).val(input.substr(0, input.length - 1));
        }
    });
    // 最长时间限制
    $('#timeScreening').on('input', function(e) {
        var input = $(this).val();
        var intRegex = /^(?:[1-2]?\d{1,4}|30000)$/;
        var isValid = intRegex.test(input);
        if (!isValid) {
            // 设置输入框的值为上一次的有效值
            $(this).val(input.substr(0, input.length - 1));
        }
    });
    changeTab(); //默認點擊
    getselectValue(); //初始化下拉框
    // 栏目切换
    $("#facezplace").click(function() {
        faceState = true;
        config.dzld = false
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(5)
        }
        changeTab()
        getfacetime(timespal, timespald)
    });
    $("#facedefence").click(function() {
        faceState = false;
        config.dzld = true
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(4)
        }
        var qu = document.getElementById('facezplace');
        var ld = document.getElementById('facezliand');
        var de = document.getElementById('facedefence');
        var lds = document.getElementById('faceliand');
        de.classList.add('qutable');
        ld.classList.remove('qutable');
        qu.classList.remove('qutable');
        lds.classList.remove('qutable');
        $('.defence-config').show();
        $("#facezLinkageMode").hide();
        $("#facezRegional").hide();
        $("#facezLinkage").hide();
        getbreathMaskitme(koutimespald);
        getLightAlarm();
    });
    $("#faceliand").click(function() { //联动方式
        faceState = false;
        config.dzld = true
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(4)
        }
        var qu = document.getElementById('facezplace');
        var ld = document.getElementById('facezliand');
        var de = document.getElementById('facedefence');
        var lds = document.getElementById('faceliand');
        lds.classList.add('qutable');
        ld.classList.remove('qutable');
        qu.classList.remove('qutable');
        de.classList.remove('qutable');
        $("#facezLinkage").show();
        $("#facezLinkageMode").hide();
        $("#facezRegional").hide();
        $('.defence-config').hide();
        getbreathMaskitme(koutimespald);
        getLightAlarm();
    });
    $("#facezliand").click(function() {
        faceState = false;
        config.dzld = true
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(4)
        }
        var qu = document.getElementById('facezplace');
        var ld = document.getElementById('facezliand');
        var de = document.getElementById('facedefence');
        var lds = document.getElementById('faceliand');
        ld.classList.add('qutable');
        qu.classList.remove('qutable');
        lds.classList.remove('qutable');
        de.classList.remove('qutable');
        $("#facezLinkageMode").show();
        $("#facezRegional").hide();
        $('.defence-config').hide();
        $("#facezLinkage").hide();
        getbreathMaskitme(koutimespald);
        getLightAlarm();
    });
    $("#personrecord").click(function() {

        lk.classList.remove('qutable');
        alarm.classList.remove('qutable');
        ry.classList.add('qutable');
        $("#facesManagement").hide();
        $("#personrecords").show();
        $("#alarm-linkage-content").hide();
    });
    $('#KOULightalarm').change(function() {
        if ($(this).is(':checked') == false) {
            $(".light-show").hide();
        } else {
            $(".light-show").show();
        }
    });
    $('#FCLightalarm').change(function() {
        if ($(this).is(':checked') == false) {
            $(".light-show1").hide();
        } else {

            $(".light-show1").show();
        }
    });
    // 点击试听
    $("#FCTyvolice").click(function() {
        setTryvoice('FaceCapture');
    });
    $("#kouVoicel").click(function() {
        setTryvoice('MaskDetection');
    });
    if (config.devicelose) {
        addEventListener("resize", function(event) {});
    }
    $(window).resize(function() {
        if (sessionStorage.getItem("xystyle") == "p6s" || sessionStorage.getItem("xystyle") == "p2p") {
            if (window.location.hash.indexOf("#ipc/pages/events/FaceCapture.html") !== -1 && sessionStorage.getItem('dpiRadio') != null) {
                ScalePitch("box-boder")
                if (faceState) {
                    preWindowfollowing(true)
                }
            }
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash == "#ipc/pages/events/FaceCapture.html") {
                ScalePitch("box-boder")
                if (faceState) {
                    preWindowfollowing(true)
                }
            } else if (window.location.hash == "#ipc/pages/events/FaceCapture.html" && sessionStorage.getItem("playstyle") == "MJPEG") {
                ScalePitch("box-boder")
                getfacetime(timespal, timespald)
            } else if (window.location.hash == "#ipc/pages/events/FaceCapture.html" && sessionStorage.getItem("playstyle") == "WebPlayer") {
                ScalePitch("box-boder")
                getfacetime(timespal, timespald)
            }
        }
    });
    // 选择旁边的预定义区域
    $("#facezpolygonimg li img").click(function(e) {
        var imgindex = $(this).attr("imgindex");
        for (var i = 0; i < $("#facezpolygonimg li img").length; i++) {
            if (i + 3 == imgindex) {
                continue
            } else {
                $("#facezpolygonimg li img")[i].src = "ipc/img/eventTips/xz_mr_0" + (i + 1) + ".png"
            }
        }
        $(this).attr("src", "ipc/img/eventTips/xz_xz_0" + (imgindex - 2) + ".png");
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            PolygonConfigFautil(8, 3, imgindex);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
            PolygonProtectionControl(5, 1, ""); //清除
            PolygonProtectionControl(2, imgindex, "");
        } else {
            if (imgindex == 4) {
                for (var i = 0; i < trgleFour.length; i++) {
                    trgleFour[i].x = Math.floor(trgleFour[i].x * 100 / getRatio())
                    trgleFour[i].y = Math.floor(trgleFour[i].y * 100 / getRatio())
                }
                createdPitch(trgleFour, "myCanvas")
            } else if (imgindex == 3) {
                createdPitch(trgle, "myCanvas")
            } else if (imgindex == 5) {
                for (var i = 0; i < trgleFive.length; i++) {
                    trgleFive[i].x = Math.floor(trgleFive[i].x * 100 / getRatio())
                    trgleFive[i].y = Math.floor(trgleFive[i].y * 100 / getRatio())
                }
                createdPitch(trgleFive, "myCanvas")
            } else if (imgindex == 6) {
                for (var i = 0; i < trgleSex.length; i++) {
                    trgleSex[i].x = Math.floor(trgleSex[i].x * 100 / getRatio())
                    trgleSex[i].y = Math.floor(trgleSex[i].y * 100 / getRatio())
                }
                createdPitch(trgleSex, "myCanvas")
            } else if (imgindex == 7) {
                for (var i = 0; i < trgleSeven.length; i++) {
                    trgleSeven[i].x = Math.floor(trgleSeven[i].x * 100 / getRatio())
                    trgleSeven[i].y = Math.floor(trgleSeven[i].y * 100 / getRatio())
                }
                createdPitch(trgleSeven, "myCanvas")
            } else {
                for (var i = 0; i < trgleEight.length; i++) {
                    trgleEight[i].x = Math.floor(trgleEight[i].x * 100 / getRatio())
                    trgleEight[i].y = Math.floor(trgleEight[i].y * 100 / getRatio())
                }
                createdPitch(trgleEight, "myCanvas")
            }
        }
    });
    // 点击清除
    $("#facezrevo").click(function() { //清除区域
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            PolygonConfigFautil(8, 2, imgindex);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
            PolygonProtectionControl(5, 0, ""); //清除现有多边形
            PolygonProtectionControl(2, imgindex, ""); //重新设置多边形
        } else {
            var c = document.getElementById("myCanvas");
            c.width = c.width
        }
    });

    // 点击人脸保存
    $("#FCsave,#kousave").click(function() {
        var that = this;
        if ("admin" == config.user || "super_admin" == config.user) {
            // var timeArrp = takeZero(timespal.getvalue()); //普通布防
            // var timeArr = takeZero(timespald.getvalue()); //声音布防
            // var koutimeArr = takeZero(koutimespald.getvalue()); //口罩检测声音布防
            // setfacetronic(timeArrp, timeArr)
            // setbreathMaskitem(koutimeArr)
            if ($("#Capturemode").val() == "custom") { //针对老设备做兼容否则无法保存
                var intRegex = /^(?:[1-4]\d{0,2}|500)$/;
                var isValid = intRegex.test($('#sizeMinimum').val());
                if (isValid) {
                    IsNeedReboot = false;
                    if ($("#isshowFCz").is(':checked') && config.deviceCap[number].FaceSnapshotFlag == "true") {
                        rebootObj = needReboot(6);
                        IsNeedReboot = rebootObj.isReBoot;
                        if (rebootObj.isReBoot == 'true') {
                            var isUpplementary = rebootObj.hasOwnProperty('isUpplementary') ? rebootObj.isUpplementary : 0;
                            $.RestartModel.mask(function() { FCsaveAndkousave(that) }, isUpplementary);
                            return;
                        }
                    }
                    FCsaveAndkousave(that);
                } else {
                    $.optionBootoast($.i18n.prop('i18n-timesmore-tipxs'), "danger")
                }

            } else {
                IsNeedReboot = false;
                if ($("#isshowFCz").is(':checked') && config.deviceCap[number].FaceSnapshotFlag == "true") {
                    rebootObj = needReboot(6);
                    IsNeedReboot = rebootObj.isReBoot;
                    if (rebootObj.isReBoot == 'true') {
                        var isUpplementary = rebootObj.hasOwnProperty('isUpplementary') ? rebootObj.isUpplementary : 0;
                        $.RestartModel.mask(function() { FCsaveAndkousave(that) }, isUpplementary);
                        return;
                    }
                }
                FCsaveAndkousave(that);
            }
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
        }
    });

    function FCsaveAndkousave(that) {
        var timeArrp = takeZero(timespal.getvalue()); //普通布防
        var timeArr = takeZero(timespald.getvalue()); //声音布防
        var koutimeArr = takeZero(koutimespald.getvalue()); //口罩检测声音布防
        setfacetronic(timeArrp, timeArr)
        setbreathMaskitem(koutimeArr);
        console.log($(that).attr('id'));
        if ($(that).attr('id') == 'FCsave') {
            setLightAlarm('#FCLightalarm', '#lglightmode', '#lgdelaytime');
        } else {
            setLightAlarm('#KOULightalarm', '#lglightmode1', '#lgdelaytime1');
        }

    }
    var g_bIsIE = !(/(msie\s|trident.*rv:)([\w.]+)/.exec(navigator.userAgent.toLowerCase()) == null);
    if (g_bIsIE && !config.forceEV) {
        if (sessionStorage.getItem("playstyle") == "ActiveX") {
            $("#playCanvas").hide();
            $("#myCanvas").hide();
            $("#axdiv").show();
            clearInterval(config.gs_interval);
        } else if (sessionStorage.getItem("playstyle") == "MJPEG") {
            $("#playCanvas").hide();
            $("#axdiv").show();
            $("#axdiv").empty();
            clearInterval(config.gs_interval)
        }
        getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true);
        SetActiveXMode(1);
        setTimeout(function() {
            getfacetime(timespal, timespald);
        }, 200);

    } else {
        if (sessionStorage.getItem("xystyle") == "p6s" || sessionStorage.getItem("xystyle") == "p2p") {
            config.refreshplayvideo = true;
            $("#playCanvas").hide();
            $("#myCanvas").hide();
            $("#axdiv").show();
            var obj = {};
            obj.a = timespal;
            obj.b = timespald;
            getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 9, obj, true);
            // getfacetime(timespal, timespald);
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                $("#playCanvas").hide();
                $("#myCanvas").hide();
                $("#axdiv").show();
            } else if (sessionStorage.getItem("playstyle") == "WebPlayer") {
                $("#playCanvas").show();
                $("#axdiv").hide();
                if (self.player) {
                    if (sessionStorage.getItem("stream") == "codestream1") {
                        self.player.stop("sub1");
                    } else {
                        self.player.stop("sub2");
                    }
                }
            } else if (sessionStorage.getItem("playstyle") == "MJPEG") {
                $("#playCanvas").hide();
                $("#axdiv").show();
                $("#axdiv").empty();
                clearInterval(config.gs_interval)
            }
            if (config.refreshplayvideo) {
                var obj = {};
                obj.a = timespal;
                obj.b = timespald;
                getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 9, obj, true);
                if (sessionStorage.getItem("playstyle") != "EasyVideo") {
                    getfacetime(timespal, timespald);
                }
            } else {
                if (sessionStorage.getItem("playstyle") == "WebPlayer") {
                    $("#downloadeasyplay").hide();
                    if (config.playMode.indexOf("WebPlayer") !== -1) {
                        $.getScript("js/webPlayer/player.js", function() { //请求成功后的回调函数
                            $.getScript("js/webPlayer/webgl.js", function() { //请求成功后的回调函数
                                $.getScript("js/webPlayer/pcm-player.js", function() {
                                    getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true);
                                    getfacetime(timespal, timespald);
                                });
                            });
                        });
                    }
                } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    refershPlayer("faceCap", timespal, timespald)
                } else if (sessionStorage.getItem("playstyle") == "MJPEG") {
                    getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true);
                    getfacetime(timespal, timespald);

                }

            }
        }
    }
    getbreathMaskitme(koutimespald);
    // 监听滚动条滚动改变easyvideo位置
    $(".facezgun").scroll(function() {
        if (sessionStorage.getItem("xystyle") == "p6s" || sessionStorage.getItem("xystyle") == "p2p") {
            if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash.indexOf("#ipc/pages/events/FaceCapture.html") !== -1 && sessionStorage.getItem('dpiRadio') != null) {
                if (faceState) {
                    var pt = GetAbsoluteLocationEx($("#axdiv")[0]);
                    if (pt.Top > 127 && pt.Left > 250 * getRatio() / 100) {
                        preHiddenDisplaywindow(5);
                        preWindowfollowing(true);
                    } else {
                        preHiddenDisplaywindow(4);
                    }
                }
            }
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash == "#ipc/pages/events/FaceCapture.html") {
                if (faceState) {
                    var pt = GetAbsoluteLocationEx($("#axdiv")[0]);
                    if (pt.Top > 127 && pt.Left > 250 * getRatio() / 100) {
                        preHiddenDisplaywindow(5);
                        preWindowfollowing(true);
                    } else {
                        preHiddenDisplaywindow(4);
                    }
                }
            }
        }
    });
});
// 识别start**************************************************
// 栏目识别栏目
function changeTabFacerecognition() {
    config.dzld = false
    var lk = document.getElementById('facesmanagement');
    var ry = document.getElementById('personrecord');
    var de = document.getElementById('persondefence');
    lk.classList.add('qutable')
    ry.classList.remove('qutable')
    de.classList.remove('qutable')
    $("#facesManagement").show();
    $("#personrecords").hide();
    $(".person-defence").hide();
    getFaceRecoBaseConfig();
}

function initConfig() {
    $(".email").toggle(config.deviceCap[number].motionEmail == "true");
    $(".isChuTriggerpush").toggle(config.isPush);
    $(".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");
    $(".lightAlarm").toggle(config.deviceCap[number].LightAlarm == "true");
    soundType('eleSoundType', config.deviceAiCap[number].AudioType);
    $("#eleFrequencyBroadcast,#FrequencyDelay").empty();
    var bc = $.i18n.prop("i18n-broadcast").split(",");
    for (var i = 0; i < bc.length; i++) {
        $("<option value='" + bcs[i] + "'>" + bc[i] + "</option>").appendTo("#eleFrequencyBroadcast");
    }
    // 延长时间
    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 getAlarmLink() {
    $.ajax({
            url: window.config.baseUrl + "/FaceReco/1/RecoRuleList",
            type: "GET",
            async: false,
            timeout: 15000,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            success: function(xmlDoc, textStatus, xhr) {
                xmlAlarmLink = xmlDoc;
                $("#control-person").select2('val', $(xmlDoc).find("RecoRuleList").find("RecoRule").find("FaceGroupList").find("ControlPersonnelType").text()).trigger('change');
                $("#schedule-time").select2('val', $(xmlDoc).find("RecoRuleList").find("RecoRule").find("Schedule").find("AllDay").text()).trigger('change');
                var week = []
                for (var i = 0; i < 7; i++) {
                    week[i] = $(xmlDoc).find('Schedule').eq(0).find('TimeBlockList').eq(0).find('TimeBlock_' + i).eq(0).text();
                }
                var timeArr = [];
                var time = [];
                for (var i = 0; i < 7; i++) {
                    timeArr[i] = $(xmlDoc).find('TimeBlock_' + i).eq(0).text();
                    for (var o = 0; o < 24; o++) {
                        if (timeArr[i].charAt(2 * o) == 1) {
                            time.push(1);
                        } else if (timeArr[i].charAt(2 * o) == 2) {
                            time.push(2);
                        } else if (timeArr[i].charAt(2 * o) == 4) {
                            time.push(3);
                        } else {
                            time.push(0);
                        }
                    }
                }
                react1.setValue(changetimeFool(group(time, 24)));
                //联动
                $("#chuBeepAlert").prop('checked', JSON.parse($(xmlDoc).find("BeepAlert").find("Enable").text())).trigger('change');
                $("#chuTriggerpush").prop('checked', JSON.parse($(xmlDoc).find("Push").find("Enable").text())); //触发推送
                $("#chuAlarmOut").prop('checked', JSON.parse($(xmlDoc).find("AlarmOut").find("Enable").text()));
                $("#chuemail").prop('checked', JSON.parse($(xmlDoc).find("Mail").find("Enable").text()));
                $("#chuftp").prop('checked', JSON.parse($(xmlDoc).find("Ftp").find("Enable").text()));
                $("#chudpick").prop('checked', JSON.parse($(xmlDoc).find("Snapshot").find("Enable").text()));
                $("#chudvdeo").prop('checked', JSON.parse($(xmlDoc).find("Record").find("Enable").text()));
                $("#FCLightalarm").prop('checked', JSON.parse($(xmlDoc).find("LightAlarm").find("Enable").text())).trigger('change');


            },
            error: function(xhr, textStatus, errorThrown) {}
        })
        //声音报警
    $.ajax({
        url: window.config.baseUrl + "/FaceReco/1/RecoRuleListVoiceAlarm",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            $("#eleSoundType").select2('val', $(xmlDoc).find('RecoRuleListVoiceAlarm').eq(0).find('VoiceType').eq(0).text()).trigger('change');
            $("#eleFrequencyBroadcast").select2('val', $(xmlDoc).find('RecoRuleListVoiceAlarm').eq(0).find('BroadcastCount').eq(0).text()).trigger('change');
            $("#activeBrightness").val($(xmlDoc).find('RecoRuleListVoiceAlarm').eq(0).find('BroadcastVolume').eq(0).text());
            $("#activeBrightnessValue").text($(xmlDoc).find('RecoRuleListVoiceAlarm').eq(0).find('BroadcastVolume').eq(0).text());
            showVoice();
            var status = $(xmlDoc).find("RecoRuleListVoiceAlarm").find("VoiceAlarmSchedule").find("DayMode").text()
            if (status == "disable") {
                $("#eledeploymentTime").select2('val', $(xmlDoc).find("RecoRuleListVoiceAlarm").find("VoiceAlarmSchedule").find("AllDay").text()).trigger('change');
            } else {
                $("#eledeploymentTime").select2('val', status).trigger('change')
            }

            var week = []
            for (var i = 0; i < 7; i++) {
                week[i] = $(xmlDoc).find('Schedule').eq(0).find('TimeBlockList').eq(0).find('TimeBlock_' + i).eq(0).text();
            }
            var timeArr = [];
            var time = [];
            for (var i = 0; i < 7; i++) {
                timeArr[i] = $(xmlDoc).find('TimeBlock_' + i).eq(0).text();
                for (var o = 0; o < 24; o++) {
                    if (timeArr[i].charAt(2 * o) == 1) {
                        time.push(1);
                    } else if (timeArr[i].charAt(2 * o) == 2) {
                        time.push(2);
                    } else if (timeArr[i].charAt(2 * o) == 4) {
                        time.push(3);
                    } else {
                        time.push(0);
                    }
                }
            }
            react.setValue(changetimeFool(group(time, 24)));
            // 判断声音报警 布防的显示隐藏
            if ($("#eledeploymentTime").select2('val') == 'false') {
                $('#eleBroadcast').show()
            } else {
                $('#eleBroadcast').hide()
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    })
    $.ajax({
        url: window.config.baseUrl + "/Alarm/1/LightWarning",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            $("#lglightmode").select2('val', $(xmlDoc).find('LightWarning').eq(0).find('LightMode').eq(0).text());
            $("#lgdelaytime").val($(xmlDoc).find('LightWarning').eq(0).find('DelayTime').eq(0).text());
        },
        error: function(xhr, textStatus, errorThrown) {}
    })
}

function faceLightWarning() {

}

function initTreeData() {
    c();
    dd = new dTree('dd');
    dd.add(0, -1, $.i18n.prop('i18n-os'));
    for (var i = 0; i < persionData.length; i++) {
        var names = persionData[i].OrganizationName;
        if (names == 'WhiteList') {
            names = $.i18n.prop('i18n-face2');
        } else if (names == 'BlackList') {
            names = $.i18n.prop('i18n-face3');
        } else if (names == 'VisitorList') {
            names = $.i18n.prop('i18n-face4');
        }
        var checkedAttribute = persionData[i].Selected.charAt(0) == '1' ? 'checked' : '' // 是否选中
        if (persionData[i].ParentLayerID == "0") { //第二层
            dd.add(persionData[i].LayerID, 0, '<input type="checkbox" data-index=' + (i + 1) + ' name="check" value="' + persionData[i].LayerID + '" id="0" ' + checkedAttribute + ' onClick="checkStatus(' + persionData[i].LayerID + ', this)">' + names);
        } else {
            dd.add(persionData[i].LayerID, persionData[i].ParentLayerID, '<input type="checkbox"  name="check" value="' + persionData[i].LayerID + '" id="' + persionData[i].ParentLayerID + '"  ' + checkedAttribute + ' onClick="checkStatus(' + persionData[i].LayerID + ', this)">' + names);
        }
        //input里面的------id为父元素id，即ParentLayerID， value为LayerID     onclick（ParentLayerID，this）
    }
    document.getElementById("tree-content").innerHTML = dd;

}

function saveTreeData() {
    //找出没有子节点的数据组成一个新数组 如果当前数据的ParentLayerID等于persionData数组内LayerID的值代表有子节点，
    //如果没有等于代表没有子节点，则把这条数据放进NodeNum内
    //顶级节点 不管是不是子节点 都要下发  ParentLayerID为“0”
    var NodeNum = persionData; //该需求了  下发所有节点了......
    // for (var i = 0; i < persionData.length; i++) {
    //     var hasChild = false;
    //     if (persionData[i].ParentLayerID == '0') {
    //         hasChild = false;
    //     } else { 
    //         for (var j = 0; j < persionData.length; j++) {
    //             if (persionData[j].ParentLayerID == persionData[i].LayerID) {
    //                 hasChild = true;
    //                 break;
    //             }
    //         }
    //     }
    //     if (!hasChild) { // 只保留没有子元素的节点
    //         NodeNum.push(persionData[i]);
    //     }
    // }
    NodeNum = isSelected(NodeNum);
    //找出没有子节点的父元素及以上
    for (var index = 0; index < NodeNum.length; index++) {
        if (NodeNum[index].ParentLayerID == '0') { //那么她的lanyid就是自己的OrganizationID OrganizationName也是自己
            NodeNum[index].parentNode = [NodeNum[index]];
        } else { //找出当前LayerID为的父节点以及祖先节点 以NodeNum[index].ParentLayerID开始找
            var ancestors = findAncestorsById(persionData, NodeNum[index].ParentLayerID);
            NodeNum[index].parentNode = ancestors;
        }

    }
    var xml = '<OrganizationMember><NodeNum>' + NodeNum.length + '</NodeNum>';
    for (var g = 0; g < NodeNum.length; g++) {
        var parentNode = NodeNum[g].parentNode;
        var LayerIDs = '';
        var OrganizationName = '';
        for (var k = 0; k < parentNode.length; k++) {
            LayerIDs += '<Layer' + (k + 1) + 'ID>' + parentNode[k].OrganizationID + '</Layer' + (k + 1) + 'ID>'
            OrganizationName += parentNode[k].OrganizationName;
            if (k !== parentNode.length - 1) {
                OrganizationName += '-';
            }
        }
        if (OrganizationName != NodeNum[g].OrganizationName) {
            OrganizationName = OrganizationName + '-' + NodeNum[g].OrganizationName;
        }
        xml += '<OrganizationStructureNode>' +
            '<Selected>' + (NodeNum[g].Selected == 1 ? '10000000' : '00000000') + '</Selected>' +
            '<OrganizationID>' + NodeNum[g].OrganizationID + '</OrganizationID>' + LayerIDs +
            '<OrganizationName>' + OrganizationName + '</OrganizationName>' +
            '<OrganizationMemo/><Reversion/>' +
            '</OrganizationStructureNode>'

    }
    xml += '</OrganizationMember>'
    var cyURL = window.config.baseUrl + "/FaceGroup/OrganizationMemberSelect";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: xml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            // SaveState(xhr);
        }
    });
}

function saveAlarmLink() {
    var data = takeZero(react.getvalue());
    var status = "";
    var statusd = "";
    if ($("#eledeploymentTime").val() == "true") {
        status = "true";
        statusd = "disable";
    } else if ($("#eledeploymentTime").val() == "false") {
        status = "false";
        statusd = "disable";

    } else if ($("#eledeploymentTime").val() == "evening") {
        status = "true";
        statusd = "evening";
    } else if ($("#eledeploymentTime").val() == "day") {
        status = "true";
        statusd = "day"
    }
    var xmlDocelecs = '<?xml version="1.0" encoding="UTF-8" ?>' +
        "<RecoRuleListVoiceAlarm>" +
        "<Enable>" + $("#chuBeepAlert").is(':checked') + "</Enable>" +
        "<VoiceType>" + $("#eleSoundType").select2('val') + "</VoiceType> " +
        "<BroadcastCount>" + $("#eleFrequencyBroadcast").select2('val') + "</BroadcastCount>" +
        "<BroadcastVolume>" + $("#activeBrightness").val() + "</BroadcastVolume>" +
        '<VoiceAlarmSchedule Version="1.0">' +
        "<AllDay>" + status + "</AllDay>" +
        '<DayMode>' + statusd + '</DayMode>' +
        '<TimeBlockList Version="1.0">' +
        "<TimeBlock_0>" + data[6] + "</TimeBlock_0>" +
        "<TimeBlock_1>" + data[0] + "</TimeBlock_1>" +
        "<TimeBlock_2>" + data[1] + "</TimeBlock_2>" +
        "<TimeBlock_3>" + data[2] + "</TimeBlock_3>" +
        "<TimeBlock_4>" + data[3] + "</TimeBlock_4>" +
        "<TimeBlock_5>" + data[4] + "</TimeBlock_5>" +
        "<TimeBlock_6>" + data[5] + "</TimeBlock_6>" +
        "</TimeBlockList></VoiceAlarmSchedule>" +
        "</RecoRuleListVoiceAlarm>";
    var cyURL = window.config.baseUrl + "/FaceReco/1/RecoRuleListVoiceAlarm";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: xmlDocelecs,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            // getalarmVoiceConfig(DZtimeVoice);
            // xhrState = xhr
        }
    });
}

function saveLightAlarm() {
    var r = /^([1-9]|[1-5][0-9]|60)$/;
    if (!r.test($("#lgdelaytime").val())) {
        bootoast({
            message: $.i18n.prop('18n-delay-tip'),
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
        return;
    }
    var xmlDocelecs = "<?xml version='1.0' encoding='UTF-8' ?><LightWarning><Enable>" + $("#FCLightalarm").is(':checked') + "</Enable><LightMode>" + $("#lglightmode").select2('val') + "</LightMode><DelayTime>" + $("#lgdelaytime").val() + "</DelayTime></LightWarning>"
    var cyURL = window.config.baseUrl + "/Alarm/1/LightWarning";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: xmlDocelecs,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            // getalarmVoiceConfig(DZtimeVoice);
            // xhrState = xhr
        }
    });
}

function saveAlarmContronl() {
    $(xmlAlarmLink).find('ControlPersonnelType').eq(0).text($("#control-person").select2('val'));
    $(xmlAlarmLink).find('Schedule').find('AllDay').eq(0).text($("#schedule-time").select2('val'));
    var data = takeZero(react1.getvalue());
    $(xmlAlarmLink).find('Schedule').find('TimeBlockList').eq(0).find('TimeBlock_0').eq(0).text(data[6]);
    $(xmlAlarmLink).find('Schedule').find('TimeBlockList').eq(0).find('TimeBlock_1').eq(0).text(data[0]);
    $(xmlAlarmLink).find('Schedule').find('TimeBlockList').eq(0).find('TimeBlock_2').eq(0).text(data[1]);
    $(xmlAlarmLink).find('Schedule').find('TimeBlockList').eq(0).find('TimeBlock_3').eq(0).text(data[2]);
    $(xmlAlarmLink).find('Schedule').find('TimeBlockList').eq(0).find('TimeBlock_4').eq(0).text(data[3]);
    $(xmlAlarmLink).find('Schedule').find('TimeBlockList').eq(0).find('TimeBlock_5').eq(0).text(data[4]);
    $(xmlAlarmLink).find('Schedule').find('TimeBlockList').eq(0).find('TimeBlock_6').eq(0).text(data[5]);
    //联动
    $(xmlAlarmLink).find('Trigger').find('BeepAlert').eq(0).find('Enable').eq(0).text($("#chuBeepAlert").is(':checked'));
    $(xmlAlarmLink).find('Trigger').find('Push').eq(0).find('Enable').eq(0).text($("#chuTriggerpush").is(':checked'));
    $(xmlAlarmLink).find('Trigger').find('AlarmOut').eq(0).find('Enable').eq(0).text($("#chuAlarmOut").is(':checked'));
    $(xmlAlarmLink).find('Trigger').find('Mail').eq(0).find('Enable').eq(0).text($("#chuemail").is(':checked'));
    $(xmlAlarmLink).find('Trigger').find('Ftp').eq(0).find('Enable').eq(0).text($("#chuftp").is(':checked'));
    $(xmlAlarmLink).find('Trigger').find('Snapshot').eq(0).find('Enable').eq(0).text($("#chudpick").is(':checked'));
    $(xmlAlarmLink).find('Trigger').find('Record').eq(0).find('Enable').eq(0).text($("#chudvdeo").is(':checked'));
    $(xmlAlarmLink).find('Trigger').find('LightAlarm').eq(0).find('Enable').eq(0).text($("#FCLightalarm").is(':checked'));
    var cyURL = window.config.baseUrl + "/FaceReco/1/RecoRuleList";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: xmlAlarmLink,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr)
        }
    });
}

function findAncestorsById(data, parentlayerId) {
    // var currentNode = data.find(item => item.LayerID == parentlayerId);
    var currentNode = null;
    for (var i = 0; i < data.length; i++) {
        if (data[i].LayerID == parentlayerId) {
            currentNode = data[i];
            break;
        }
    }
    var ancestors = [];
    while (currentNode) {
        ancestors.unshift(currentNode);
        // currentNode = data.find(item => item.LayerID.toString() == currentNode.ParentLayerID);
        var currentNodeID = currentNode.ParentLayerID.toString();
        var currentNode = null;
        for (var i = 0; i < data.length; i++) {
            if (data[i].LayerID.toString() == currentNodeID) {
                currentNode = data[i];
                break;
            }
        }
    }
    return ancestors;
}

function isSelected(NodeNumArray) {
    //for循环chks,找到vaule值跟NodeNum里面LayerID一样的值，
    //找到后查看这个input是否选中 如果选中就把当前NodeNum这条数据的Selected给true
    var chks = document.querySelectorAll('input[name=check]');
    for (var i = 0; i < NodeNumArray.length; i++) {
        var NodeNum = NodeNumArray[i];
        for (var j = 0; j < chks.length; j++) {
            if (chks[j].value == NodeNum.LayerID) {
                if (chks[j].checked) {
                    NodeNum.Selected = true;
                } else {
                    NodeNum.Selected = false;
                }
                break;
            }
        }
    }
    return NodeNumArray;
}

function checkStatus(no, chkBox) {
    // no 代表LayerID input的value为LayerID id为ParentLayerID
    parentCheckbyChild(no, chkBox);
    //互斥 如访客选中了，再去操作白名单节点或者子节点，如果白名单及以下有一个选中的那就把访客取消
    var NodeNum = getNodeNum();
    if ($(chkBox).is(':checked')) {
        var curenttopParentNode = 0;
        for (let j = 0; j < NodeNum.length; j++) {
            if (no == NodeNum[j].LayerID) {
                //获取当前点击元素的顶级节点
                curenttopParentNode = NodeNum[j].parentNode[0].LayerID;
                break;
            }
        }
        var b = spliceele(curenttopParentNode);
        var inputs = document.querySelectorAll("input[data-index]");
        for (var i = 0; i < inputs.length; i++) {
            var input = inputs[i];
            if (input.getAttribute("data-index") != curenttopParentNode) {
                input.checked = false;
                // for (var k = 0; k < b.length; k++) { //遍历其他顶级节点 然后全给false
                //     parentbyChild1(b[k],inputs[i]);
                // }
                parentbyChild1(inputs[i].getAttribute("data-index"), inputs[i])
            }
        }
    }
}

function parentbyChild1(LayerID, ele) {
    var chks = document.querySelectorAll('input[name="check"]');
    for (var i = 0; i < chks.length; i++) {
        if (chks[i].id == LayerID) {
            chks[i].checked = false
            parentbyChild1(chks[i].value, chks[i]);
        }
    }
}

function spliceele(currentNode) {
    var a = [1, 2, 3];
    for (var i = a.length - 1; i >= 0; i--) {
        if (a[i] == currentNode) {
            a.splice(i, 1);
        }
    }
    return a;
}

function getNodeNum() {
    var NodeNum = [];
    var NodeNum = persionData;
    NodeNum = isSelected(NodeNum);
    //找出没有子节点的父元素及以上
    for (var index = 0; index < NodeNum.length; index++) {
        if (NodeNum[index].ParentLayerID == '0') { //那么她的lanyid就是自己的OrganizationID OrganizationName也是自己
            NodeNum[index].parentNode = [NodeNum[index]];
        } else { //找出当前LayerID为的父节点以及祖先节点 以NodeNum[index].ParentLayerID开始找
            var ancestors = findAncestorsById(persionData, NodeNum[index].ParentLayerID);
            NodeNum[index].parentNode = ancestors;
        }
    }
    return NodeNum;
}

function parentCheckbyChild(no, chkBox) {
    var chks = document.querySelectorAll('input[name="check"]');
    for (var i = 0; i < chks.length; i++) {
        if (chks[i].id == no) { //chks[i].id == no说明当前点击元素有子节点 递归选中或者取消所有节点 父节点选中取消，所有子节点同步
            chks[i].checked = chkBox.checked;
            parentCheckbyChild(chks[i].value, chks[i]);
        } else { //没有子节点则获取父节点 然后变量里面所有子节点是不是都取消了 里面子元素全部取消 父元素也取消

        }
    }
}

function showVoice() {
    // 渲染进度条
    $('#activeBrightness').jRange({
        from: 0,
        to: 100,
        // step: 1,
        scale: 1,
        format: '%s',
        width: 360,
        showLabels: false,
        showScale: false,
        onstatechange: function() {
            $("#activeBrightnessValue").text($("#activeBrightness").val());
        },
        onSetPosition: function() {
            $("#activeBrightnessValue").text($("#activeBrightness").val());
        },
        onMouseDown: function() {},
        onMouseUp: function() {}
    });
}
var FaceRecoBaseConfigXml;

function getFaceRecoBaseConfig() {
    $.ajax({
        url: config.baseUrl + "/FaceReco/1/BaseConfig",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            FaceRecoBaseConfigXml = xmlDoc;
            $('#isShowFaces').prop('checked', JSON.parse($(xmlDoc).find('FaceBaseConfig').eq(0).find('EnableRecognition').text()));
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}

function setFaceRecoBaseConfig() {
    $(FaceRecoBaseConfigXml).find('FaceBaseConfig').eq(0).find('EnableRecognition').text($('#isShowFaces').is(':checked'));
    var cyURL = config.baseUrl + "/FaceReco/1/BaseConfig";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: FaceRecoBaseConfigXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            // getpassengerFlow(KLtime, KLtimeVoice)
            SaveState(xhr);
            if (IsNeedReboot == 'true') {
                IsNeedReboot = false;
                if (rebootObj.isUpplementary != '3') {
                    $.optionBootoast($.i18n.prop('i18n-enevt-tip1'), "success");
                }
            }
        }
    });
}
// 人员表格
function dataTableDraw(tableId) {
    var aoColumns = [{
            "mDataProp": "id", //mDataProp
            "sWidth": "30%" //设置列宽
        },
        {
            "mDataProp": "Name",
            "sWidth": "35%" //设置列宽
        },
        {
            "mDataProp": "ModelState",
            "sWidth": "35%",
            "mRender": function(data) { // 返回自定义内容
                if (data == "success") {
                    return '<span><img src="img/face/jianm_cg.png">' + $.i18n.prop('i18n-creaty-success') + '</span>';
                } else {
                    return '<span><img src="img/face/jianm_sb.png">' + $.i18n.prop('i18n-creaty-faild') + '</span>';
                }

            }, //设置列宽
        },
    ];
    // $(tableId).dataTable({
    //         data: setData,
    //         destroy: true,
    //         searching: true,
    //         paging: true, //表格分页
    //         aoColumns: aoColumns,
    //     })
    _table = $(tableId).dataTable({
        "language": {
            "lengthMenu": $.i18n.prop('i18n-pageshow') + "_MENU_" + $.i18n.prop('i18n-pagesize'),
            "processing": $.i18n.prop("i18n-page-load"),
            // "info": "第 _START_ 到第 _END_ 条数据，总共有 _TOTAL_ 条记录",
            "sZeroRecords": $.i18n.prop('i18n-sZeroRecords'),
            // "infoFiltered" : "（从 _MAX_ 条数据中过滤得到）",
            "paginate": {
                "first": $.i18n.prop("i18n-sInfo9"),
                "last": $.i18n.prop("i18n-sInfo8"),
                "next": $.i18n.prop("i18n-sNext"),
                "previous": $.i18n.prop("i18n-sPrevious"),
            },
        },
        "retrieve": true, //可能是表格重复使用时受到影响 必须加上
        "processing": true,
        "paging": true,
        "bPaginate": true, //翻页功能
        // "sPaginationType": "bootstrap", //翻页风格
        "bLengthChange": true, //每页显示的记录数
        "bFilter": false, //过滤功能
        "bSort": false, //排序功能
        "bInfo": true, //页脚信息
        "bAutoWidth": false, //自动宽度
        "bServerSide": true, //启用服务器分页
        "bDestroy": false, //解决重新渲染问题
        "iDisplayLength": 10, //每页显示数量
        "aoColumns": aoColumns,
        "dom": '<t><lfip>',
        "infoCallback": function(settings, start, end, max, total, pre) { //自定义总数
            if (total > 0) {
                return $.i18n.prop("i18n-page-tip") + " " + total + " " + $.i18n.prop("i18n-page-tips");
            } else {
                return $.i18n.prop("i18n-page-tip") + " " + 0 + " " + $.i18n.prop("i18n-page-tips");
            }

        },
        // 当表格重绘就会调用这个回调
        fnDrawCallback: function(data) {},
        fnServerData: retrieveData
    });
}
// --------------------------------------------------------------树
function retrieveData(sSource, aoData, fnCallback) {
    // 获取pageSize
    var pageSize = aoData[4].value;
    //获取page
    var start = aoData[3].value;
    var page = Math.ceil(start / pageSize) + 1;
    // $(currentfaceXmld).find("Pagesize").text(pageSize)
    // $(currentfaceXmld).find("Pagenum").text(page)
    // b(currentfaceXmld, currentsXmld, fnCallback)
    // 查询条件
    xml = "<?xml version='1.0' encoding='UTF-8' ?>" +
        "<PersonInfoFilter>" +
        "<GroupID></GroupID>" +
        "<Name>" + $("#face-name").val() + "</Name>" +
        "<Sex></Sex>" +
        "<CertificateType></CertificateType>" +
        "<CertificateID></CertificateID>" +
        "<Country></Country>" +
        "<Address></Address>" +
        "<StartBirthday></StartBirthday>" +
        "<StopBirthday></StopBirthday>" +
        "<ModelState>" + $("#JZZD").val() + "</ModelState>" +
        "<OrginationID>" + oldvalue + "</OrginationID>" +
        "</PersonInfoFilter>"
    var ae = window.config.baseUrl + "/FaceGroup/QueryPersonInfoListCount";
    $.ajax({
        type: "PUT",
        url: ae,
        dataType: 'XML',
        contentType: "application/xml",
        data: xml,
        timeout: 15000,
        beforeSend: function(ak) {
            ak.setRequestHeader("If-Modified-Since", "0");
            if (window.localStorage.getItem("Token") != "default") {
                ak.setRequestHeader("TOKEN", window.localStorage.getItem("Token"))
            }
        },
        success: function(ak, an, am) {
            if (sessionStorage.getItem("xystyle") == "p2p") {
                var al = ak.responseXML;
            } else {
                if (typeof(ak) == "string") {
                    var al = parseXmlFromStr(ak)
                } else {
                    var al = ak
                }
            }
            var statucode = $(al).find("ResponseStatus").eq(0).find("statusCode").eq(0).text();
            if ("401" == statucode) {
                top.location.href = "/";
            }
            var personCount = $(al).find("PersonInfoList ").eq(0).find("PersonCount").text()
                // if (personCount == "0") {
                //     $.optionBootoast($.i18n.prop('i18n-t5facelib-tips'), "danger");
                // }
            getList(pageSize, page, fnCallback, personCount);
        },
        error: function(af, ag, ae) {
            if ("401" == af.status) {
                top.location.href = "/";
            }
        }
    })


}

function getList(pageSize, page, fnCallback, total) {
    var xml = "<PersonInfoFilter>" +
        "<GroupID></GroupID>" +
        "<Name>" + $("#face-name").val() + "</Name>" +
        "<Sex></Sex>" +
        "<CertificateType></CertificateType>" +
        "<CertificateID></CertificateID>" +
        "<Country></Country>" +
        "<Address></Address>" +
        "<StartBirthday></StartBirthday>" +
        "<StopBirthday></StopBirthday>" +
        "<Pagesize>" + pageSize + "</Pagesize>" +
        "<Pagenum>" + page + "</Pagenum>" +
        "<ModelState>" + $("#JZZD").val() + "</ModelState>" +
        "<OrginationID>" + oldvalue + "</OrginationID>" +
        "</PersonInfoFilter>"
    var ae = window.config.baseUrl + "/FaceGroup/QueryPersonInfoList";
    $.ajax({
        type: "PUT",
        url: ae,
        dataType: 'XML',
        contentType: "application/xml",
        data: xml,
        beforeSend: function(ah) {
            ah.setRequestHeader("If-Modified-Since", "0");
            if (window.localStorage.getItem("Token") != "default") {
                ah.setRequestHeader("TOKEN", window.localStorage.getItem("Token"))
            }
        },
        success: function(res) {
            if (sessionStorage.getItem("xystyle") == "p2p") {
                var resulXML = res.responseXML;
            } else {
                var resulXML = res
            }
            var length = $(resulXML).find('PersonInfoList').find('PersonInfo').length;
            var list = [];
            for (var index = 0; index < length; index++) {
                var itme = {};
                itme.id = index + 1
                itme.Name = $(resulXML).find('PersonInfoList').find('PersonInfo').eq(index).find('Name').text();
                itme.ModelState = $(resulXML).find('PersonInfoList').find('PersonInfo').eq(index).find('ModelState').text();
                list.push(itme);
            }
            //iTotalRecords和iTotalDisplayRecords数据别搞错了
            //iTotalRecords 当前页显示多少条，iTotalDisplayRecords为总条数
            var result = {
                "iTotalRecords": pageSize,
                "iTotalDisplayRecords": total,
                "aaData": list
            };
            fnCallback(result);
        },
        error: function(af, ag, ae) {
            if ("401" == af.status) {
                top.location.href = "/";
            }
        }
    })
}
var arr = [];
// id映射转换主方法
function changeIds(a) {
    var pids = [] //所有的id集合包含重复的
    var fpids = [] //顶层集合
    for (var i = 0; i < a.length; i++) {
        if (a[i].ParentLayerID != 0) { //子集
            pids.push(a[i].LayerID)
            pids.push(a[i].ParentLayerID)
        } else {
            pids.push(a[i].LayerID)
        }
    }
    var newPids = unique(pids) //去重之后的所有id
    var lastPids = putIds(newPids) //映射之后的id集合和对应关系
    arr = lastPids
    var newValue = rebuildList(a, lastPids)
    return newValue
}
// 去重
function unique(arr) {
    for (var i = 0; i < arr.length; i++) {
        for (var j = i + 1; j < arr.length; j++) {
            if (arr[i] == arr[j]) { //第一个等同于第二个，splice方法删除第二个
                arr.splice(j, 1);
                j--;
            }
        }
    }
    return arr;
}
// 给每个id做映射变成数字id
function putIds(a) {
    var idObjList = []
    for (var k = 0; k < a.length; k++) {
        var idObj = {} //映射之后的储存
        idObj.id = k + 1
        idObj.value = a[k]
        idObjList.push(idObj)
    }
    return idObjList
}
// 重组原数组的id
function rebuildList(v, d) {
    for (var j = 0; j < v.length; j++) {
        for (var q = 0; q < d.length; q++) {
            if (v[j].LayerID == d[q].value) {
                v[j].LayerID = d[q].id
            }
            if (v[j].ParentLayerID == d[q].value && v[j].ParentLayerID != "0") {
                v[j].ParentLayerID = d[q].id
            }
        }
    }
    return v
}
// 比对数据库id
function checkoUt(d) {
    var nowid = d
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].id == nowid) {
            nowid = arr[i].value
            break
        }
    }
    oldvalue = nowid
    if (!_table) { //实例不存在就渲染
        dataTableDraw("#personMange");
    } else {
        $('#personMange').dataTable().fnDraw();
    }
    // b(currentfaceXmld, currentsXmld);

}

function c() {
    var ae = window.config.baseUrl + "/FaceGroup/OrganizationStructureTree";
    $.ajax({
        type: "get",
        url: ae,
        async: false,
        processData: false,
        timeout: 15000,
        beforeSend: function(af) {
            af.setRequestHeader("If-Modified-Since", "0");
            if (window.localStorage.getItem("Token") != "default") {
                af.setRequestHeader("TOKEN", window.localStorage.getItem("Token"))
            }
        },
        success: function(ai, al, ak) {
            persionData = [];
            var aj = ai;
            var statuscode = $(aj).find("ResponseStatus").eq(0).find("statusCode")
                .eq(0).text();
            if ("401" == statuscode) {
                top.location.href = "/";
            }
            var af = $(aj).find("OrganizationStructureTree").eq(0).find("Layer")
                .length;
            for (var ag = 0; ag < af; ag++) {
                var ah = {};
                ah.LayerID = $(aj)
                    .find("OrganizationStructureTree")
                    .eq(0)
                    .find("Layer")
                    .eq(ag)
                    .find("OrganizationID")
                    .text(); //id
                ah.OrganizationID = $(aj)
                    .find("OrganizationStructureTree")
                    .eq(0)
                    .find("Layer")
                    .eq(ag)
                    .find("OrganizationID")
                    .text(); //OrganizationID
                ah.ParentLayerID = $(aj)
                    .find("OrganizationStructureTree")
                    .eq(0)
                    .find("Layer")
                    .eq(ag)
                    .find("ParentLayerID")
                    .text(); //父id
                ah.GroupID = $(aj)
                    .find("OrganizationStructureTree")
                    .eq(0)
                    .find("Layer")
                    .eq(ag)
                    .find("GroupID")
                    .text(); //组id
                ah.OrganizationName = $(aj)
                    .find("OrganizationStructureTree")
                    .eq(0)
                    .find("Layer")
                    .eq(ag)
                    .find("OrganizationName")
                    .text(); //组织名称
                ah.OrganizationMemo = $(aj)
                    .find("OrganizationStructureTree")
                    .eq(0)
                    .find("Layer")
                    .eq(ag)
                    .find("OrganizationMemo")
                    .text(); // 备注信息
                ah.Reversion = $(aj)
                    .find("OrganizationStructureTree")
                    .eq(0)
                    .find("Layer")
                    .eq(ag)
                    .find("Reversion")
                    .text(); // 文档上写的全局唯一
                ah.Selected = $(aj)
                    .find("OrganizationStructureTree")
                    .eq(0)
                    .find("Layer")
                    .eq(ag)
                    .find("Selected")
                    .text() || '00000000'
                    //该节点是否选中
                persionData.push(ah);
            }
            var checkList = changeIds(persionData)
            persionData = checkList

        },
        error: function(af, ag, ae) {
            if ("401" == af.status) {
                top.location.href = "/";
            }
        }
    })
}
// 获取总条数
function M(ai) {
    var ae = window.config.baseUrl + "/FaceGroup/QueryPersonInfoListCount";
    $.ajax({
        type: "PUT",
        url: ae,
        async: false,
        processData: false,
        data: ai,
        timeout: 15000,
        beforeSend: function(ak) {
            ak.setRequestHeader("If-Modified-Since", "0");
            if (window.localStorage.getItem("Token") != "default") {
                ak.setRequestHeader("TOKEN", window.localStorage.getItem("Token"))
            }
        },
        success: function(ak, an, am) {
            if (sessionStorage.getItem("xystyle") == "p2p") {
                var al = ak.responseXML;
            } else {
                if (typeof(ak) == "string") {
                    var al = parseXmlFromStr(ak)
                } else {
                    var al = ak
                }
            }
            var statucode = $(al).find("ResponseStatus").eq(0).find("statusCode").eq(0).text();
            if ("401" == statucode) {
                top.location.href = "/";
            }

            personCount = $(al).find("PersonInfoList ").eq(0).find("PersonCount").text()
            if (personCount == "0") {
                $.optionBootoast($.i18n.prop('i18n-t5facelib-tips'), "danger");
            }
        },
        error: function(af, ag, ae) {
            if ("401" == af.status) {
                top.location.href = "/";
            }
        }
    })
}
// 获取列表数据
function b(af, ag, callback) {
    M(ag);
    var ae = window.config.baseUrl + "/FaceGroup/QueryPersonInfoList";
    $.ajax({
        type: "PUT",
        url: ae,
        async: true,
        processData: false,
        data: af,
        beforeSend: function(ah) {
            ah.setRequestHeader("If-Modified-Since", "0");
            if (window.localStorage.getItem("Token") != "default") {
                ah.setRequestHeader("TOKEN", window.localStorage.getItem("Token"))
            }
        },
        success: function(ap, ah, ao) {
            PersonFaceInfoData = [];
            if (typeof(ap) == "string") {
                var al = parseXmlFromStr(ap)
            } else {
                var al = ap
            }
            var statucode = $(al).find("ResponseStatus").eq(0).find("statusCode").eq(0).text();
            if ("401" == statucode) {
                top.location.href = "/";
            }
            var ai = $(al).find("PersonInfoList").eq(0).find("PersonInfo").length;
            var am = ai + 1;
            if (ai == 0) {
                $.optionBootoast($.i18n.prop('i18n-t5facelib-tips'), "danger");
            } else {
                if (parseInt(personCount) < parseInt(pagesize)) {
                    currentpagenumber = 1
                }
                for (var aj = 0; aj < parseInt(pagesize) * (parseInt(currentpagenumber) - 1); aj++) {
                    var an = {};
                    an.PersonID = "";
                    an.GroupID = "";
                    an.Name = "";
                    an.Sex = "";
                    an.CertificateType = "";
                    an.CertificateID = "";
                    an.Country = "";
                    an.Address = "";
                    an.FaceImageID = "";
                    an.Birthday = "";
                    an.UniqueID = "";
                    an.CardID = "";
                    an.ValidPeriod = "";
                    // an.PassPermissionEnable = "";
                    an.Password = "";
                    PersonFaceInfoData.push(an)
                }
                if (ai < pagesize) {
                    for (var ak = 0; ak < ai; ak++) {
                        var an = {};
                        an.PersonID = $(al).find("PersonInfoList").eq(0).find("PersonInfo").eq(ak).find("PersonID").text();
                        an.GroupID = $(al).find("PersonInfoList").eq(0).find("PersonInfo").eq(ak).find("GroupID").text();
                        an.Name = $(al).find("PersonInfoList").eq(0).find("PersonInfo").eq(ak).find("Name").text();
                        an.ModelState = $(al).find("PersonInfoList").eq(0).find("PersonInfo").eq(ak).find("ModelState").text();
                        an.CertificateID = $(al).find("PersonInfoList").eq(0).find("PersonInfo").eq(ak).find("CertificateID").text();
                        PersonFaceInfoData.push(an)
                    }
                } else {
                    for (var ak = 0; ak < am; ak++) {
                        var an = {};
                        an.PersonID = $(al).find("PersonInfoList").eq(0).find("PersonInfo").eq(ak).find("PersonID").text();
                        an.GroupID = $(al).find("PersonInfoList").eq(0).find("PersonInfo").eq(ak).find("GroupID").text();
                        an.Name = $(al).find("PersonInfoList").eq(0).find("PersonInfo").eq(ak).find("Name").text();
                        an.ModelState = $(al).find("PersonInfoList").eq(0).find("PersonInfo").eq(ak).find("ModelState").text();
                        an.CertificateID = $(al).find("PersonInfoList").eq(0).find("PersonInfo").eq(ak).find("CertificateID").text();
                        PersonFaceInfoData.push(an)
                    }
                }
            }
        },
        error: function(af, ag, ae) {
            if ("401" == af.status) {
                top.location.href = "/";
            }
        }
    })
}
// ---------------------------------------------------------------树
function initDatetimepicker() {
    $(".time-input").datetimepicker({
        format: "hh:ii",
        autoclose: true, // 选择日期后关闭
        language: 'zh-cn', //显示语言为中文
        minuteStep: 1, //分钟步调
        startView: 1, //日期时间选择器打开之后首先显示的视图
    });
    $(".start_time").val("00:00");
    $(".end_time").val("23:59");
    $(".start_time").datetimepicker().on('changeDate', function(e) {
        $(this).siblings(".end_time").datetimepicker('setStartDate', e.date);
        // $(".end_time").datetimepicker('setStartDate', e.date);

    });
    $(".time-box .end_time").datetimepicker().on('changeDate', function(e) {
        $(this).siblings(".start_time").datetimepicker('setEndDate', e.date);
        // $(".start_time").datetimepicker('setEndDate', e.date);

    });
}

// function redirectFace(name) {
//     Router.open("ipc/pages/events/faceList.html?name=" + name);
// }

$("#faceTable tbody").on("click", "span#faceck", function() {
    var data = _table.oTable.fnGetData($(this).parents('tr')[0]);
    var id = data.GroupID;
    Router.open("ipc/pages/events/faceList.html?id=" + id);
});



// 栏目切换
function changeTab() {
    config.dzld = false
    var lk = document.getElementById('facesmanagement');
    var ry = document.getElementById('personrecord');
    lk.classList.add('qutable')
    ry.classList.remove('qutable')
    $("#facesManagement").show();
    $("#personrecords").hide();
    getFaceRecoBaseConfig();
}


function setfacelinkopendoor() {
    var cyXml = "<?xml version='1.0' encoding='UTF-8' ?>" +
        "<FaceBaseConfig>" +
        "<EnableRecognition>" + $("#isShowFaces").is(':checked') + "</EnableRecognition>" +
        "<OpenDoorMode>" + OpenDoorMode + "</OpenDoorMode>" +
        "<OverlayHumanBox>" + linkOverlayHumanBox + "</OverlayHumanBox>" +
        "<SyncPictureOpt>" + openstake + "</SyncPictureOpt>" +
        "<EnableForceOutCardNumber>" + mustdon + "</EnableForceOutCardNumber>" +
        "</FaceBaseConfig>";
    var cyURL = window.config.baseUrl + "/FaceReco/1/BaseConfig";
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
            if (window.localStorage.getItem("Token") != "default") {
                xhr.setRequestHeader("TOKEN", window.localStorage.getItem("Token"))
            }
        },
        complete: function(xhr, textStatus) {
            var xmlDoc = xhr.responseXML;
            var state = $(xmlDoc).find('statusCode').eq(0).text();
            if ("401" == state) {
                top.location.href = "/";
            }
            // SaveState(xhr);
        },
        error: function(xhr, textStatus, errorThrown) {
            if ("401" == xhr.status) {
                top.location.href = "/";
            }
        }
    });
}

//查询所有脸库作为查询条件之一
function faceGroupsQueryAll() {
    var cyURL = window.config.baseUrl + "/FaceGroups/QueryAll";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
            if (window.localStorage.getItem("Token") != "default") {
                xhr.setRequestHeader("TOKEN", window.localStorage.getItem("Token"))
            }
        },
        success: function(xmlDoc, textStatus, xhr) { //在这里获取所有人脸库的值并且渲染页面
            recordlistData = []; //数组重置
            if (sessionStorage.getItem("xystyle") == "p2p") {
                var xmlDocobj = xmlDoc.responseXML;
            } else {
                var xmlDocobj = parseXmlFromStr(xmlDoc);
            }
            var statusflg = $(xmlDocobj).find('ResponseStatus').eq(0).find('statusCode').eq(0).text();
            if ("401" == statusflg) {
                top.location.href = "/";
            }
            var sl = $(xmlDocobj).find('FaceGroups').eq(0).find('FaceGroup').length;
            for (var i = 0; i < sl; i++) {
                var faceGroupobj = {};
                faceGroupobj.xid = i + 1
                faceGroupobj.GroupName = $(xmlDocobj).find('FaceGroups').eq(0).find('FaceGroup').eq(i).find('GroupName').text();
                faceGroupobj.GroupID = $(xmlDocobj).find('FaceGroups').eq(0).find('FaceGroup').eq(i).find('GroupID').text();
                faceGroupobj.CreateTime = $(xmlDocobj).find('FaceGroups').eq(0).find('FaceGroup').eq(i).find('CreateTime').text();
                faceGroupobj.PersonInfoCount = $(xmlDocobj).find('FaceGroups').eq(0).find('FaceGroup').eq(i).find('PersonInfoCount').text();
                faceGroupobj.ValidPersonCount = $(xmlDocobj).find('FaceGroups').eq(0).find('FaceGroup').eq(i).find('ValidPersonCount').text();
                faceGroupobj.InvalidPersonCount = $(xmlDocobj).find('FaceGroups').eq(0).find('FaceGroup').eq(i).find('InvalidPersonCount').text();
                faceGroupobj.AvailableStatus = $(xmlDocobj).find('FaceGroups').eq(0).find('FaceGroup').eq(i).find('AvailableStatus').text();
                faceGroupobj.GroupThresholdValue = parseInt($(xmlDocobj).find("FaceGroups").eq(0).find("FaceGroup").eq(i).find("GroupThresholdValue").text()); //阈值
                recordlistData.push(faceGroupobj);
            }

        },
        error: function(xhr, textStatus, errorThrown) {
            if ("401" == xhr.status) {
                top.location.href = "/";
            }
        }
    });
}

function checkTime(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
};



// 识别end**************************************************




// 栏目切换
function changeTab() {
    config.dzld = false
    var qu = document.getElementById('facezplace')
    var ld = document.getElementById('facezliand')
    var de = document.getElementById('facedefence');
    var lds = document.getElementById('faceliand');
    qu.classList.add('qutable')
    ld.classList.remove('qutable')
    lds.classList.remove('qutable')
    de.classList.remove('qutable')
    $("#facezRegional").show()
    $("#facezLinkageMode").hide();
    $('.defence-config').hide();
    $("#facezLinkage").hide();
    getLightAlarm();
}
// 初始化下拉数据
function getselectValue() {
    // 人脸质量
    var st = $.i18n.prop("i18n-face-quality").split(",")
    for (var i = 0; i < st.length; i++) {
        $("<option value='" + qualityvl[i] + "'>" + st[i] + "</option>").appendTo("#Facequality");
    }
    // 声音类型
    var renlianVoicetype = $(config.deviceAiCap[number].forfaceVoicetype);
    var kouzhaoVoicetype = $(config.deviceAiCap[number].formaskVoicetype);
    var sylx = $.i18n.prop("i18n-str_voice_type").split(",");
    var hask = $.i18n.prop("i18n-HasFaceMask");
    var nohask = $.i18n.prop("i18n-NoFaceMask");
    for (var i = 0; i < 12; i++) {
        if (renlianVoicetype.find("Custom").text() == "true" && zdlx[i] == "custom") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#FCSoundType");
        } else if (renlianVoicetype.find("Alarm").text() == "true" && zdlx[i] == "alarm") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#FCSoundType");
        } else if (renlianVoicetype.find("dog").text() == "true" && zdlx[i] == "dog") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#FCSoundType");
        } else if (renlianVoicetype.find("warning").text() == "true" && zdlx[i] == "warning area") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#FCSoundType");
        } else if (renlianVoicetype.find("monitoring").text() == "true" && zdlx[i] == "monitoring area") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#FCSoundType");
        } else if (renlianVoicetype.find("welcome").text() == "true" && zdlx[i] == "welcome") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#FCSoundType");
        } else if (renlianVoicetype.find("DeepWater").text() == "true" && zdlx[i] == "Deep Water Warning") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#FCSoundType");
        } else if (renlianVoicetype.find("PrivateTerritory").text() == "true" && zdlx[i] == "Private territory") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#FCSoundType");
        } else if (renlianVoicetype.find("DangerZone").text() == "true" && zdlx[i] == "danger zone") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#FCSoundType");
        } else if (renlianVoicetype.find("ValuableObjects").text() == "true" && zdlx[i] == "Valuable objects") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#FCSoundType");
        } else if (renlianVoicetype.find("HighWarning").text() == "true" && zdlx[i] == "High Warning") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#FCSoundType");
        } else if (renlianVoicetype.find("PrivateParking").text() == "true" && zdlx[i] == "Private Parking") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#FCSoundType");
        };
    }
    for (var i = 0; i < 14; i++) {
        if (kouzhaoVoicetype.find("Custom").text() == "true" && zdlx[i] == "custom") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#kouSoundType");
        } else if (kouzhaoVoicetype.find("Alarm").text() == "true" && zdlx[i] == "alarm") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#kouSoundType");
        } else if (kouzhaoVoicetype.find("dog").text() == "true" && zdlx[i] == "dog") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#kouSoundType");
        } else if (kouzhaoVoicetype.find("warning").text() == "true" && zdlx[i] == "warning area") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#kouSoundType");
        } else if (kouzhaoVoicetype.find("monitoring").text() == "true" && zdlx[i] == "monitoring area") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#kouSoundType");
        } else if (kouzhaoVoicetype.find("welcome").text() == "true" && zdlx[i] == "welcome") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#kouSoundType");
        } else if (kouzhaoVoicetype.find("DeepWater").text() == "true" && zdlx[i] == "Deep Water Warning") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#kouSoundType");
        } else if (kouzhaoVoicetype.find("PrivateTerritory").text() == "true" && zdlx[i] == "Private territory") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#kouSoundType");
        } else if (kouzhaoVoicetype.find("DangerZone").text() == "true" && zdlx[i] == "danger zone") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#kouSoundType");
        } else if (kouzhaoVoicetype.find("ValuableObjects").text() == "true" && zdlx[i] == "Valuable objects") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#kouSoundType");
        } else if (kouzhaoVoicetype.find("HighWarning").text() == "true" && zdlx[i] == "High Warning") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#kouSoundType");
        } else if (kouzhaoVoicetype.find("PrivateParking").text() == "true" && zdlx[i] == "Private Parking") {
            $("<option value='" + zdlx[i] + "'>" + sylx[i] + "</option>").appendTo("#kouSoundType");
        } else if (kouzhaoVoicetype.find("HasFaceMask").text() == "true" && zdlx[i] == "HasFaceMask") {
            $("<option value='" + zdlx[i] + "'>" + hask + "</option>").appendTo("#kouSoundType");
        } else if (kouzhaoVoicetype.find("NoFaceMask").text() == "true" && zdlx[i] == "NoFaceMask") {
            $("<option value='" + zdlx[i] + "'>" + nohask + "</option>").appendTo("#kouSoundType");
        }

    }

    // 播报次数
    var cs = $.i18n.prop("i18n-broadcast").split(",")
    for (var i = 0; i < cs.length; i++) {
        $("<option value='" + bbcs[i] + "'>" + cs[i] + "</option>").appendTo("#FCFrequencyBroadcast");
    }
    for (var i = 0; i < cs.length; i++) {
        $("<option value='" + bbcs[i] + "'>" + cs[i] + "</option>").appendTo("#kouFrequencyBroadcast");
    }

}
// 试听声音报警
function setTryvoice(d) {
    if (d == 'FaceCapture') {
        voiceXmldoc = '<?xml version="1.0" encoding="UTF-8" ?>' +
            "<AudioAlarmConfig><ChannelID>1</ChannelID>" +
            "<PeopleAudio></PeopleAudio><CarAudio></CarAudio>" +
            "<FireAudioType></FireAudioType><AudioOutputDelay></AudioOutputDelay>" +
            "<AudioVolume></AudioVolume>" +
            "<TryListenType>" + d + "</TryListenType>" +
            "<AlarmInExAudioType></AlarmInExAudioType>" +
            "<VideoShelterAudioType></VideoShelterAudioType>" +
            "<MotionAudioType></MotionAudioType>" +
            "<ElectronicDenceAudioType></ElectronicDenceAudioType>" +
            "<CrossBorderDetectAudioType></CrossBorderDetectAudioType>" +
            "<OffDutyDetectAudioType></OffDutyDetectAudioType>" +
            "<FaceCaptureAudioType>" + $("#FCSoundType").val() + "</FaceCaptureAudioType>" +
            "<MaskDetectionAudioType></MaskDetectionAudioType>" +
            "</AudioAlarmConfig>"

    } else {
        voiceXmldoc = '<?xml version="1.0" encoding="UTF-8" ?>' +
            "<AudioAlarmConfig><ChannelID>1</ChannelID>" +
            "<PeopleAudio></PeopleAudio><CarAudio></CarAudio>" +
            "<FireAudioType></FireAudioType><AudioOutputDelay></AudioOutputDelay>" +
            "<AudioVolume></AudioVolume>" +
            "<TryListenType>" + d + "</TryListenType>" +
            "<AlarmInExAudioType></AlarmInExAudioType>" +
            "<VideoShelterAudioType></VideoShelterAudioType>" +
            "<MotionAudioType></MotionAudioType>" +
            "<ElectronicDenceAudioType></ElectronicDenceAudioType>" +
            "<CrossBorderDetectAudioType></CrossBorderDetectAudioType>" +
            "<OffDutyDetectAudioType></OffDutyDetectAudioType>" +
            "<FaceCaptureAudioType></FaceCaptureAudioType>" +
            "<MaskDetectionAudioType>" + $("#kouSoundType").val() + "</MaskDetectionAudioType>" +
            "</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 getfacetime(timespal, timespald) {
    $.ajax({
        url: window.config.baseUrl + "/AI/FaceSnapshotCfg",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            $("#isshowFCz").prop('checked', JSON.parse($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('Enable').eq(0).text())); //是否启用人脸抓拍
            var modeValue = $(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('SnapshotMode').eq(0).text()
            $("#Capturemode").val(modeValue).trigger('change'); //抓拍模式
            if (modeValue == "custom") {
                $(".isshowCustom").show()
            } else {
                $(".isshowCustom").hide()
            }
            $("#facedo").val($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('MaxPitchAngle').eq(0).text()); //最大俯仰角
            $("#doMaximum").val($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('MaxYawAngle').eq(0).text()); //最大偏航角
            $("#rollMaximum").val($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('MaxRollAngle').eq(0).text()); //最大滚转角
            $("#ambiguityMaximum").val($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('MaxAmbiguity').eq(0).text()); //最大模糊度
            $("#sizeMinimum").val($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('MinFaceSize').eq(0).text()); //最小人脸尺寸
            $("#timeScreening").val($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('MaxFilterDuration').eq(0).text()); //最大筛选时长
            $("#Facequality").val($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('FaceQuality').eq(0).text()).trigger('change'); //人脸质量
            $("#FCbackImag").prop('checked', JSON.parse($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('IsCaptureBackground').eq(0).text())); //背景图
            $("#FCfacekuan").prop('checked', JSON.parse($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('ShowFaceFrame').eq(0).text())); //显示人脸框
            $("#FCdefense").prop('checked', JSON.parse($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('ShowSchedFrame').eq(0).text())); //显示布防框
            $("#FCSoundType").val($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('VoiceAlarm').eq(0).find('VoiceType').text()).trigger('change'); //声音类型
            $("#FCFrequencyBroadcast").val($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('VoiceAlarm').eq(0).find('BroadcastCount').text()).trigger('change'); //播报次数
            $("#FCectiveBrightness").val($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('VoiceAlarm').eq(0).find('BroadcastVolume').text()); //音量
            showVoiceOut()
            $("#facezDefensePlan").val($(xmlDoc).find('AIFaceSnapshotCfg').eq(0).find('Schedule').eq(0).find('AllDay').text()).trigger('change'); //普通布防时间
            var status = $(xmlDoc).find("AIFaceSnapshotCfg").eq(0).find('VoiceAlarm').find("DayMode").text()
            if (status == "disable") {
                $("#FCdeploymentTime").val($(xmlDoc).find("AIFaceSnapshotCfg").eq(0).find('VoiceAlarm').find("AllDay").text()).trigger('change');
            } else {
                $("#FCdeploymentTime").val(status).trigger('change')
            }
            if ($("#facezDefensePlan").val() == "false") {
                $("#recordDiv").show()
            } else {
                $("#recordDiv").hide()
            }
            if ($("#FCdeploymentTime").val() == "false") {
                $("#FCvoicelrecordDiv").show()
            } else {
                $("#FCvoicelrecordDiv").hide()
            }
            //联动
            $("#FCAudiblealarm").prop('checked', JSON.parse($(xmlDoc).find("BeepAlert").find("Enable").text()));
            $("#FCLightalarm").prop('checked', JSON.parse($(xmlDoc).find("LightAlarm").find("Enable").text())).trigger('change');
            $("#FCTriggerpush").prop('checked', JSON.parse($(xmlDoc).find("Push").find("Enable").text()));
            $("#FCalarmoutput").prop('checked', JSON.parse($(xmlDoc).find("AlarmOut").find("Enable").text()));
            $("#FCTriggermail").prop('checked', JSON.parse($(xmlDoc).find("Mail").find("Enable").text()));
            $("#FCTriggerFTP").prop('checked', JSON.parse($(xmlDoc).find("Ftp").find("Enable").text()));
            $("#FCTriggerSDcapture").prop('checked', JSON.parse($(xmlDoc).find("Snapshot").find("Enable").text()));
            $("#FCTriggerSDrecording").prop('checked', JSON.parse($(xmlDoc).find("Record").find("Enable").text()));
            setScheduleX(xmlDoc, timespald, 0);
            setScheduleX(xmlDoc, timespal, 1);
            var pointnum = $(xmlDoc).find("Point").length;
            imgindex = pointnum;
            var urlImage = "ipc/img/eventTips/xz_xz_0" + (pointnum - 2) + ".png"
            $("#facezpolygonimg li img").each(function() {
                if ($(this).attr("imgindex") == pointnum) {
                    $(this).attr("src", urlImage);
                };
            });
            var str = "";
            for (i = 1; i <= pointnum; i++) {
                str += '<Point' + i + '_X>' + $(xmlDoc).find('Point').eq(i - 1).find('PosX').text() + '</Point' + i + '_X><Point' + i + '_Y>' + $(xmlDoc).find('Point').eq(i - 1).find('PosY').text() + '</Point' + i + '_Y>'
            }
            if (sessionStorage.getItem("playstyle") == "ActiveX") {
                var xml = '<?xml version="1.0" encoding="UTF-8"?><PolygonProtection>' +
                    '<PolygonCount>1</PolygonCount><Flags>0</Flags><PolygonList><Polygon1><EdgesCount>' + pointnum + '</EdgesCount>' +
                    '<Vertexes>' + str + '</Vertexes>' +
                    '</Polygon1>' +
                    '</PolygonList>' +
                    '</PolygonProtection>'
                PolygonProtectionControl(1, 0, xml);
            } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                var xArr = []
                var yArr = []
                for (var o = 0; o < pointnum; o++) {
                    xArr.push($(xmlDoc).find('Point').eq(o).find('PosX').text() - 0)
                    yArr.push($(xmlDoc).find('Point').eq(o).find('PosY').text() - 0)
                }
                PolygonConfig(8, pointnum, xArr, yArr);
            } else {
                var lineChse = [];
                for (var i = 0; i < pointnum; i++) {
                    var obj = {
                        x: "",
                        y: ""
                    }
                    var a = $(xmlDoc).find('Point').eq(i).find('PosX').text() - 0
                    var b = $(xmlDoc).find('Point').eq(i).find('PosY').text() - 0
                    obj.x = Math.floor((a / menbfrx) * 100 / getRatio())
                    obj.y = Math.floor((b / menbfry) * 100 / getRatio())
                    lineChse.push(obj)
                }
                createdPitch(lineChse, "myCanvas")
            }

        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}
// 下发人脸抓拍配置
function setfacetronic(timeArrp, timeArr) {
    ptonbuf = timeArrp
    yuyinbuf = timeArr
    var focusdex;
    $("#facezpolygonimg li img").each(function() {
        if ($(this).attr("src").indexOf('xz_xz') != -1) {
            focusdex = $(this).attr("imgindex");
        };
    });
    if (sessionStorage.getItem("playstyle") == "ActiveX") {
        var xml = PolygonProtectionControl(3, 0, "");
        var strxml = "";
        for (i = 0; i < focusdex; i++) {
            strxml += '<Point Version="1.0"><ID>' + i + '</ID><PosX>' + $(xml).find("Point" + (i + 1) + "_X").eq(0).text() + '</PosX><PosY>' + $(xml).find("Point" + (i + 1) + "_Y").eq(0).text() + '</PosY></Point>'
        };
    } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
        PolygonConfigBlack(8, focusdex);
    } else {
        var strxml = ""
        for (var k = 0; k < focusdex; k++) {
            strxml += '<Point Version="1.0"><ID>' + k + '</ID><PosX>' + Math.floor((newPointList[k].x * menbfrx) * 100 / getRatio()) + '</PosX><PosY>' + Math.floor((newPointList[k].y * menbfry) * 100 / getRatio()) + '</PosY></Point>'
        }
    }
    if (sessionStorage.getItem("playstyle") != "EasyVideo") {
        // 语音布防
        var status = ""
        var statusd = ""
        if ($("#FCdeploymentTime").val() == "true") {
            status = "true"
            statusd = "disable"
        } else if ($("#FCdeploymentTime").val() == "false") {
            status = "false"
            statusd = "disable"
        } else if ($("#FCdeploymentTime").val() == "evening") {
            status = "true"
            statusd = "evening"
        } else if ($("#FCdeploymentTime").val() == "day") {
            status = "true"
            statusd = "day"
        }
        var xmlDocelecs = '<?xml version="1.0" encoding="UTF-8"?>' +
            '<AIFaceSnapshotCfg Version="1.0"><Enable>' + $("#isshowFCz").is(':checked') + '</Enable>' +
            '<SnapshotMode>' + $("#Capturemode").val() + '</SnapshotMode>' +
            '<FaceQuality>' + $("#Facequality").val() + '</FaceQuality>' +
            '<ShowFaceFrame>' + $("#FCfacekuan").is(':checked') + '</ShowFaceFrame>' +
            '<ShowSchedFrame>' + $("#FCdefense").is(':checked') + '</ShowSchedFrame>' +
            '<IsCaptureBackground>' + $('#FCbackImag').is(':checked') + '</IsCaptureBackground>' +
            '<MaxPitchAngle>' + $("#facedo").val() + '</MaxPitchAngle>' +
            '<MaxYawAngle>' + $("#doMaximum").val() + '</MaxYawAngle>' +
            '<MaxRollAngle>' + $("#rollMaximum").val() + '</MaxRollAngle>' +
            '<MaxAmbiguity>' + $("#ambiguityMaximum").val() + '</MaxAmbiguity>' +
            '<MaxFilterDuration>' + $("#timeScreening").val() + '</MaxFilterDuration>' +
            '<MinFaceSize>' + $("#sizeMinimum").val() + '</MinFaceSize>' +
            '<Polygon>' + strxml + '</Polygon>' +
            '<VoiceAlarm>' +
            '<VoiceType>' + $('#FCSoundType').val() + '</VoiceType>' +
            '<BroadcastCount>' + $("#FCFrequencyBroadcast").val() + '</BroadcastCount>' +
            '<BroadcastVolume>' + $("#FCectiveBrightness").val() + '</BroadcastVolume>' +
            '<VoiceAlarmSchedule Version="1.0">' +
            '<AllDay>' + status + '</AllDay>' +
            '<DayMode>' + statusd + '</DayMode>' +
            '<TimeBlockList Version="1.0">' +
            '<TimeBlock_0>' + timeArr[6] + '</TimeBlock_0>' +
            '<TimeBlock_1>' + timeArr[0] + '</TimeBlock_1>' +
            '<TimeBlock_2>' + timeArr[1] + '</TimeBlock_2>' +
            '<TimeBlock_3>' + timeArr[2] + '</TimeBlock_3>' +
            '<TimeBlock_4>' + timeArr[3] + '</TimeBlock_4>' +
            '<TimeBlock_5>' + timeArr[4] + '</TimeBlock_5>' +
            '<TimeBlock_6>' + timeArr[5] + '</TimeBlock_6>' +
            '</TimeBlockList>' +
            '</VoiceAlarmSchedule>' +
            '</VoiceAlarm>' +
            '<Trigger Version="1.0">' +
            '<NotifyAMS Version="1.0">' +
            '<Enable>false</Enable>' +
            '</NotifyAMS>' +
            '<BeepAlert Version="1.0">' +
            '<Enable>' + $("#FCAudiblealarm").is(':checked') + '</Enable>' +
            '</BeepAlert>' +
            '<FullScreen Version="1.0">' +
            '<Enable>false</Enable>' +
            '</FullScreen>' +
            '<Mail Version="1.0">' +
            '<Enable>' + $("#FCTriggermail").is(':checked') + '</Enable>' +
            '</Mail>' +
            '<Ftp Version="1.0">' +
            '<Enable>' + $("#FCTriggerFTP").is(':checked') + '</Enable>' +
            '</Ftp>' +
            '<Push Version="1.0">' +
            '<Enable>' + $("#FCTriggerpush").is(':checked') + '</Enable>' +
            '</Push>' +
            '<AlarmOut Version="1.0">' +
            '<Enable>' + $("#FCalarmoutput").is(':checked') + '</Enable>' +
            '<AlarmOutMask>1</AlarmOutMask>' +
            '</AlarmOut>' +
            '<Snapshot Version="1.0">' +
            '<Enable>' + $("#FCTriggerSDcapture").is(':checked') + '</Enable>' +
            '<SnapshotMask>1</SnapshotMask>' +
            '</Snapshot>' +
            '<Record Version="1.0">' +
            '<Enable>' + $("#FCTriggerSDrecording").is(':checked') + '</Enable>' +
            '<RecordMask>1</RecordMask>' +
            '</Record>' +
            '<PTZ Version="1.0">' +
            '<Enable>false</Enable>' +
            '<PTZActionList Version="1.0" />' +
            '</PTZ>' +
            '<LightAlarm Version="1.0">' +
            '<Enable>' + $("#FCLightalarm").is(':checked') + '</Enable>' +
            '</LightAlarm>' +
            '</Trigger>' +
            '<Schedule Version="1.0">' +
            '<AllDay>' + $('#facezDefensePlan').val() + '</AllDay>' +
            '<TimeBlockList Version="1.0">' +
            '<TimeBlock_0>' + timeArrp[6] + '</TimeBlock_0>' +
            '<TimeBlock_1>' + timeArrp[0] + '</TimeBlock_1>' +
            '<TimeBlock_2>' + timeArrp[1] + '</TimeBlock_2>' +
            '<TimeBlock_3>' + timeArrp[2] + '</TimeBlock_3>' +
            '<TimeBlock_4>' + timeArrp[3] + '</TimeBlock_4>' +
            '<TimeBlock_5>' + timeArrp[4] + '</TimeBlock_5>' +
            '<TimeBlock_6>' + timeArrp[5] + '</TimeBlock_6>' +
            '</TimeBlockList>' +
            '</Schedule>' +
            '</AIFaceSnapshotCfg>'
        var cyURL = window.config.baseUrl + "/AI/FaceSnapshotCfg";
        $.ajax({
            type: "PUT",
            url: cyURL,
            async: false,
            processData: false,
            data: xmlDocelecs,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            complete: function(xhr, textStatus) {
                getfacetime(faceTime, faceTimeVoice)
                    // SaveStateTwo(xhrState, xhr)
            }
        });

    }
}

function getfacetricValue(data) {
    var strxml = ""
    for (var i = 0; i < data.faceSnapshot.edge; i++) {
        strxml += '<Point Version="1.0"><ID>' + i + '</ID><PosX>' + data.faceSnapshot.x[i] + '</PosX><PosY>' + data.faceSnapshot.y[i] + '</PosY></Point>'
    }
    // 语音布防
    var status = ""
    var statusd = ""
    if ($("#FCdeploymentTime").val() == "true") {
        status = "true"
        statusd = "disable"
    } else if ($("#FCdeploymentTime").val() == "false") {
        status = "false"
        statusd = "disable"
    } else if ($("#FCdeploymentTime").val() == "evening") {
        status = "true"
        statusd = "evening"
    } else if ($("#FCdeploymentTime").val() == "day") {
        status = "true"
        statusd = "day"
    }
    var xmlDocelecs = '<?xml version="1.0" encoding="UTF-8"?>' +
        '<AIFaceSnapshotCfg Version="1.0"><Enable>' + $("#isshowFCz").is(':checked') + '</Enable>' +
        '<SnapshotMode>' + $("#Capturemode").val() + '</SnapshotMode>' +
        '<FaceQuality>' + $("#Facequality").val() + '</FaceQuality>' +
        '<ShowFaceFrame>' + $("#FCfacekuan").is(':checked') + '</ShowFaceFrame>' +
        '<ShowSchedFrame>' + $("#FCdefense").is(':checked') + '</ShowSchedFrame>' +
        '<IsCaptureBackground>' + $('#FCbackImag').is(':checked') + '</IsCaptureBackground>' +
        '<MaxPitchAngle>' + $("#facedo").val() + '</MaxPitchAngle>' +
        '<MaxYawAngle>' + $("#doMaximum").val() + '</MaxYawAngle>' +
        '<MaxRollAngle>' + $("#rollMaximum").val() + '</MaxRollAngle>' +
        '<MaxAmbiguity>' + $("#ambiguityMaximum").val() + '</MaxAmbiguity>' +
        '<MaxFilterDuration>' + $("#timeScreening").val() + '</MaxFilterDuration>' +
        '<MinFaceSize>' + $("#sizeMinimum").val() + '</MinFaceSize>' +
        '<Polygon>' + strxml + '</Polygon>' +
        '<VoiceAlarm>' +
        '<VoiceType>' + $('#FCSoundType').val() + '</VoiceType>' +
        '<BroadcastCount>' + $("#FCFrequencyBroadcast").val() + '</BroadcastCount>' +
        '<BroadcastVolume>' + $("#FCectiveBrightness").val() + '</BroadcastVolume>' +
        '<VoiceAlarmSchedule Version="1.0">' +
        '<AllDay>' + status + '</AllDay>' +
        '<DayMode>' + statusd + '</DayMode>' +
        '<TimeBlockList Version="1.0">' +
        '<TimeBlock_0>' + yuyinbuf[6] + '</TimeBlock_0>' +
        '<TimeBlock_1>' + yuyinbuf[0] + '</TimeBlock_1>' +
        '<TimeBlock_2>' + yuyinbuf[1] + '</TimeBlock_2>' +
        '<TimeBlock_3>' + yuyinbuf[2] + '</TimeBlock_3>' +
        '<TimeBlock_4>' + yuyinbuf[3] + '</TimeBlock_4>' +
        '<TimeBlock_5>' + yuyinbuf[4] + '</TimeBlock_5>' +
        '<TimeBlock_6>' + yuyinbuf[5] + '</TimeBlock_6>' +
        '</TimeBlockList>' +
        '</VoiceAlarmSchedule>' +
        '</VoiceAlarm>' +
        '<Trigger Version="1.0">' +
        '<NotifyAMS Version="1.0">' +
        '<Enable>false</Enable>' +
        '</NotifyAMS>' +
        '<BeepAlert Version="1.0">' +
        '<Enable>' + $("#FCAudiblealarm").is(':checked') + '</Enable>' +
        '</BeepAlert>' +
        '<FullScreen Version="1.0">' +
        '<Enable>false</Enable>' +
        '</FullScreen>' +
        '<Mail Version="1.0">' +
        '<Enable>' + $("#FCTriggermail").is(':checked') + '</Enable>' +
        '</Mail>' +
        '<Ftp Version="1.0">' +
        '<Enable>' + $("#FCTriggerFTP").is(':checked') + '</Enable>' +
        '</Ftp>' +
        '<Push Version="1.0">' +
        '<Enable>' + $("#FCTriggerpush").is(':checked') + '</Enable>' +
        '</Push>' +
        '<AlarmOut Version="1.0">' +
        '<Enable>' + $("#FCalarmoutput").is(':checked') + '</Enable>' +
        '<AlarmOutMask>1</AlarmOutMask>' +
        '</AlarmOut>' +
        '<Snapshot Version="1.0">' +
        '<Enable>' + $("#FCTriggerSDcapture").is(':checked') + '</Enable>' +
        '<SnapshotMask>1</SnapshotMask>' +
        '</Snapshot>' +
        '<Record Version="1.0">' +
        '<Enable>' + $("#FCTriggerSDrecording").is(':checked') + '</Enable>' +
        '<RecordMask>1</RecordMask>' +
        '</Record>' +
        '<PTZ Version="1.0">' +
        '<Enable>false</Enable>' +
        '<PTZActionList Version="1.0" />' +
        '</PTZ>' +
        '<LightAlarm Version="1.0">' +
        '<Enable>' + $("#FCLightalarm").is(':checked') + '</Enable>' +
        '</LightAlarm>' +
        '</Trigger>' +
        '<Schedule Version="1.0">' +
        '<AllDay>' + $('#facezDefensePlan').val() + '</AllDay>' +
        '<TimeBlockList Version="1.0">' +
        '<TimeBlock_0>' + ptonbuf[6] + '</TimeBlock_0>' +
        '<TimeBlock_1>' + ptonbuf[0] + '</TimeBlock_1>' +
        '<TimeBlock_2>' + ptonbuf[1] + '</TimeBlock_2>' +
        '<TimeBlock_3>' + ptonbuf[2] + '</TimeBlock_3>' +
        '<TimeBlock_4>' + ptonbuf[3] + '</TimeBlock_4>' +
        '<TimeBlock_5>' + ptonbuf[4] + '</TimeBlock_5>' +
        '<TimeBlock_6>' + ptonbuf[5] + '</TimeBlock_6>' +
        '</TimeBlockList>' +
        '</Schedule>' +
        '</AIFaceSnapshotCfg>'
    var cyURL = window.config.baseUrl + "/AI/FaceSnapshotCfg";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: xmlDocelecs,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            getfacetime(faceTime, faceTimeVoice);
            // SaveStateTwo(xhrState, xhr);
        }
    });

}
// 获取口罩检测配置
function getbreathMaskitme(koutimespald) {
    $.ajax({
        url: window.config.baseUrl + "/AI/BreathMaskDetectCfg",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            xmlDocelec = xmlDoc;
            $("#isShowkou").prop('checked', JSON.parse($(xmlDoc).find('AIBreathMaskDetectCfg').eq(0).find('Enable').eq(0).text())); //是否启用口罩检测
            $("#kouAlarmtype").val($(xmlDoc).find('AIBreathMaskDetectCfg').eq(0).find('MaskDetectAlarmType').eq(0).text()).trigger('change'); //口罩报警类型
            $("#kouFrequencyBroadcast").val($(xmlDoc).find('AIBreathMaskDetectCfg').eq(0).find('VoiceAlarm').eq(0).find('BroadcastCount').text()).trigger('change'); //播报次数
            var status = $(xmlDoc).find("AIBreathMaskDetectCfg").eq(0).find('VoiceAlarm').find("DayMode").text()
            if (status == "disable") {
                $("#koudeploymentTime").val($(xmlDoc).find("AIBreathMaskDetectCfg").eq(0).find('VoiceAlarmSchedule').find("AllDay").text()).trigger('change');
            } else {
                $("#koudeploymentTime").val(status).trigger('change');
            }
            if ($("#koudeploymentTime").val() == "false") {
                $("#kouBroadcast").show()
            } else {
                $("#kouBroadcast").hide()
            }

            $("#kouectiveBrightness").val($(xmlDoc).find('AIBreathMaskDetectCfg').eq(0).find('VoiceAlarm').eq(0).find('BroadcastVolume').text()); //音量
            showKouVoiceOut();
            $("#kouSoundType").val($(xmlDoc).find('AIBreathMaskDetectCfg').eq(0).find('VoiceAlarm').eq(0).find('VoiceType').text()).trigger('change'); //声音类型
            //联动
            $("#KOUAudiblealarm").prop('checked', JSON.parse($(xmlDoc).find("BeepAlert").find("Enable").text()));
            $("#KOULightalarm").prop('checked', JSON.parse($(xmlDoc).find("LightAlarm").find("Enable").text())).trigger('change');
            $("#KOUTriggerpush").prop('checked', JSON.parse($(xmlDoc).find("Push").find("Enable").text()));
            $("#KOUalarmoutput").prop('checked', JSON.parse($(xmlDoc).find("AlarmOut").find("Enable").text()));
            $("#KOUTriggermail").prop('checked', JSON.parse($(xmlDoc).find("Mail").find("Enable").text()));
            $("#KOUTriggerFTP").prop('checked', JSON.parse($(xmlDoc).find("Ftp").find("Enable").text()));
            $("#KOUTriggerSDcapture").prop('checked', JSON.parse($(xmlDoc).find("Snapshot").find("Enable").text()));
            $("#KOUTriggerSDrecording").prop('checked', JSON.parse($(xmlDoc).find("Record").find("Enable").text()));
            setScheduleX(xmlDoc, koutimespald, 0);


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

function getLightAlarm() {
    $.ajax({
        url: window.config.baseUrl + "/Alarm/1/LightWarning",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            $("#lglightmode").select2('val', $(xmlDoc).find('LightWarning').eq(0).find('LightMode').eq(0).text());
            $("#lgdelaytime").val($(xmlDoc).find('LightWarning').eq(0).find('DelayTime').eq(0).text());
            $("#lglightmode1").select2('val', $(xmlDoc).find('LightWarning').eq(0).find('LightMode').eq(0).text());
            $("#lgdelaytime1").val($(xmlDoc).find('LightWarning').eq(0).find('DelayTime').eq(0).text());
        },
        error: function(xhr, textStatus, errorThrown) {}
    })
}
// 下发口罩检测配置
function setbreathMaskitem(d) {
    // 语音布防
    var status = "";
    var statusd = "";
    if ($("#koudeploymentTime").val() == "true") {
        status = "true";
        statusd = "disable"
    } else if ($("#koudeploymentTime").val() == "false") {
        status = "false";
        statusd = "disable"

    } else if ($("#koudeploymentTime").val() == "evening") {
        status = "true";
        statusd = "evening"
    } else if ($("#koudeploymentTime").val() == "day") {
        status = "true";
        statusd = "day"
    }
    var xmlDocelecs = '<?xml version="1.0" encoding="UTF-8"?>' +
        '<AIBreathMaskDetectCfg Version="1.0">' +
        '<Enable>' + $("#isShowkou").is(':checked') + '</Enable>' +
        '<MaskDetectAlarmType>' + $("#kouAlarmtype").val() + '</MaskDetectAlarmType>' +
        '<VoiceAlarm Version="1.0">' +
        '<VoiceType>' + $("#kouSoundType").val() + '</VoiceType>' +
        '<BroadcastCount>' + $("#kouFrequencyBroadcast").val() + '</BroadcastCount>' +
        '<BroadcastVolume>' + $("#kouectiveBrightness").val() + '</BroadcastVolume>' +
        '<VoiceAlarmSchedule Version="1.0">' +
        '<AllDay>' + status + '</AllDay>' +
        '<DayMode>' + statusd + '</DayMode>' +
        '<TimeBlockList Version="1.0">' +
        '<TimeBlock_0>' + d[6] + '</TimeBlock_0>' +
        '<TimeBlock_1>' + d[0] + '</TimeBlock_1>' +
        '<TimeBlock_2>' + d[1] + '</TimeBlock_2>' +
        '<TimeBlock_3>' + d[2] + '</TimeBlock_3>' +
        '<TimeBlock_4>' + d[3] + '</TimeBlock_4>' +
        '<TimeBlock_5>' + d[4] + '</TimeBlock_5>' +
        '<TimeBlock_6>' + d[5] + '</TimeBlock_6>' +
        '</TimeBlockList>' +
        '</VoiceAlarmSchedule>' +
        '</VoiceAlarm>' +
        '<Trigger Version="1.0">' +
        '<NotifyAMS Version="1.0">' +
        '<Enable>false</Enable>' +
        '</NotifyAMS>' +
        '<BeepAlert Version="1.0">' +
        '<Enable>' + $("#KOUAudiblealarm").is(':checked') + '</Enable>' +
        '</BeepAlert>' +
        '<FullScreen Version="1.0">' +
        '<Enable>false</Enable>' +
        '</FullScreen>' +
        '<Mail Version="1.0">' +
        '<Enable>' + $("#KOUTriggermail").is(':checked') + '</Enable>' +
        '</Mail>' +
        '<Ftp Version="1.0">' +
        '<Enable>' + $("#KOUTriggerFTP").is(':checked') + '</Enable>' +
        '</Ftp>' +
        '<Push Version="1.0">' +
        '<Enable>' + $("#KOUTriggerpush").is(':checked') + '</Enable>' +
        '</Push>' +
        '<AlarmOut Version="1.0">' +
        '<Enable>' + $("#KOUalarmoutput").is(':checked') + '</Enable>' +
        '<AlarmOutMask>1</AlarmOutMask>' +
        '</AlarmOut>' +
        '<Snapshot Version="1.0">' +
        '<Enable>' + $("#KOUTriggerSDcapture").is(':checked') + '</Enable>' +
        '<SnapshotMask>1</SnapshotMask>' +
        '</Snapshot>' +
        '<Record Version="1.0">' +
        '<Enable>' + $("#KOUTriggerSDrecording").is(':checked') + '</Enable>' +
        '<RecordMask>1</RecordMask>' +
        '</Record>' +
        '<PTZ Version="1.0">' +
        '<Enable>false</Enable>' +
        '<PTZActionList Version="1.0"/>' +
        '</PTZ>' +
        '<LightAlarm Version="1.0">' +
        '<Enable>' + $("#KOULightalarm").is(':checked') + '</Enable>' +
        '</LightAlarm>' +
        '</Trigger></AIBreathMaskDetectCfg>'
    var cyURL = window.config.baseUrl + "/AI/BreathMaskDetectCfg";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: xmlDocelecs,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            getbreathMaskitme(kouBrathTime)
                // xhrState = xhr
            SaveState(xhr)
            if (IsNeedReboot == 'true') {
                IsNeedReboot = false;
                if (rebootObj.isUpplementary != '3') {
                    $.optionBootoast($.i18n.prop('i18n-enevt-tip1'), "success");
                }
            }
            $("#MaskLayout").hide()
            $("#persionFace").hide()


        }
    });
}

function setLightAlarm(e, s, i) {
    var r = /^([1-9]|[1-5][0-9]|60)$/;
    if (!r.test($("#lgdelaytime").val())) {
        bootoast({
            message: $.i18n.prop('18n-delay-tip'),
            type: 'danger',
            position: 'bottom-center',
            timeout: true,
            animationDuration: 3000,
            dismissable: true
        });
        return;
    }
    var xmlDocelecs = "<?xml version='1.0' encoding='UTF-8' ?><LightWarning><Enable>" + $(e).is(':checked') + "</Enable><LightMode>" + $(s).select2('val') + "</LightMode><DelayTime>" + $(i).val() + "</DelayTime></LightWarning>"
    var cyURL = window.config.baseUrl + "/Alarm/1/LightWarning";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: xmlDocelecs,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            // getalarmVoiceConfig(DZtimeVoice);
            // xhrState = xhr
        }
    });
}
// 设置声音报警布防区域
function setScheduleX(d, btimecaset, k) {
    // 转换xml中的时间
    var timeArr = [];
    var time = [];
    for (var i = 0; i < 7; i++) {
        timeArr[i] = $(d).find('TimeBlock_' + i).eq(k).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 showVoiceOut() {
    // 人脸抓拍渲染进度条
    $('#FCectiveBrightness').jRange({
        from: 0,
        to: 100,
        // step: 1,
        scale: 1,
        format: '%s',
        width: 260,
        showLabels: false,
        showScale: false,
        onstatechange: function() {
            $("#FCectiveBrightnessValue").text($("#FCectiveBrightness").val());
        },
        onSetPosition: function() {
            $("#FCectiveBrightnessValue").text($("#FCectiveBrightness").val());
        },
        onMouseDown: function() {},
        onMouseUp: function() {}
    });
}
// 渲染口罩检测音量
function showKouVoiceOut() {
    $('#kouectiveBrightness').jRange({
        from: 0,
        to: 100,
        // step: 1,
        scale: 1,
        format: '%s',
        width: 280,
        showLabels: false,
        showScale: false,
        onstatechange: function() {
            $("#kouectiveBrightnessValue").text($("#kouectiveBrightness").val());
        },
        onSetPosition: function() {
            $("#kouectiveBrightnessValue").text($("#kouectiveBrightness").val());
        },
        onMouseDown: function() {},
        onMouseUp: function() {

        }
    })

}