var lmd = ['high', 'middle', 'low'];
var newlmd = ["highest", "high", "middle", "low", "lowest"];
var sylx = ['custom', 'alarm', 'dog', 'warning area', 'monitoring area', 'welcome', 'Deep Water Warning', 'Private territory', 'danger zone', 'Valuable objects', 'High Warning', 'Private Parking']
var bcs = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
var bcm = ['5', '10', '20', '30'];
var imgindex, xmlMotionDetection, xmlDefensePlan, xmlAudioAlarmConfig, xmlDocPolygon;
var menbfrx = 9999;
var menbfry = 9999;
var newPointList;
var newLineList = [];
var newPersonList = [];
var pum; //保留边数
var humanState = true;
var timeplaned, timeplandvoice;
var xhrState;
var number = 0; //记录当前通道号
var hyStatus = false;
var ktrgleFour = [{
    x: 80,
    y: 80
}, {
    x: 250,
    y: 80
}, {
    x: 250,
    y: 200
}, {
    x: 80,
    y: 200
}]
var trgle = [{
    x: 30,
    y: 30
}, {
    x: 200,
    y: 30
}, {
    x: 30,
    y: 200
}]; //三角形默认位置
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 rebootObj = {};

$(document).ready(function() {
    if (!config.isPush) {
        config.isPush = enablePush(); //网络端口号
    }
    peopleLink();
    if (config.deviceCap[number].Email == "true") {
        $(".email").show()
    } else {
        $(".email").hide()
    }

    ScalePitch("box-border");
    ScalePitchImg('svgimgdef');
    // 监听滚动条滚动改变easyvideo位置
    $(".facezgun").scroll(function() {
        if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash == "#ipc/pages/events/fireDetect.html") {
            if (humanState) {
                var pt = GetAbsoluteLocationEx($("#axdiv")[0]);
                if (pt.Top > 127 && pt.Left > 250 * getRatio() / 100) {
                    preHiddenDisplaywindow(5);
                    preWindowfollowing(true);
                } else {
                    preHiddenDisplaywindow(4);
                }
            }
        }
    });
    // 初始化下拉框
    if (!$('.select2').hasClass('select2-offscreen')) {
        $(".select2").select2({
            minimumResultsForSearch: -1,
            width: 220,
        });
    }
    // 初始化时间选择
    var mq = $("#recordDiv").TimePlan({
        sectionNum: 6
    });
    var mh = $("#Broadcast").TimePlan({
        sectionNum: 6
    });

    timeplaned = mq;
    timeplandvoice = mh;
    $("#fireModel").click(function() {
        $("#myModal").modal('show');
        getFireTime(mh);
        $('#Broadcast').show();
    });
    selectvalue();
    // changeTab(); //进来默认点击
    gethyEnable()
        // 切换栏目
    $("#place").click(function() {
        humanState = true;
        config.dzld = false
        $(".hysty").show();
        $(".defence-config").hide();
        $("#LinkageMode").hide();
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(5)
        }
        changeTab()
    });
    $("#firedefence").click(function() {
        humanState = false;
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(4)
        }
        config.dzld = true
        var qu = document.getElementById('place')
        var ld = document.getElementById('liand')
        var de = document.getElementById('firedefence')
        de.classList.add('qutable')
        qu.classList.remove('qutable')
        ld.classList.remove('qutable')
        $("#LinkageMode").hide()
        $("#Regional").hide()
        $(".defence-config").show();
    });
    $("#liand").click(function() {
        humanState = false;
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            preHiddenDisplaywindow(4)
        }
        config.dzld = true
        var qu = document.getElementById('place')
        var ld = document.getElementById('liand')
        var de = document.getElementById('firedefence')
        ld.classList.add('qutable')
        de.classList.remove('qutable')
        qu.classList.remove('qutable')
        $("#LinkageMode").show()
        $("#Regional").hide()
        $(".defence-config").hide();
    });
    $("#SoundType").change(function() {
        console.log($(this).val());
        fireCustomVoice($(this).val())
    })
    // 使能切换
    $("#firedetectCheck").change(function() {
        if ($(this).is(":checked")) {
            $(".hysty").show();
            $("#shysave").hide();
            changeTab();
            if (hyStatus) {
                if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    preHiddenDisplaywindow(5)
                }
            } else {
                openVideo();
                hyStatus = true;
            }
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                preHiddenDisplaywindow(4)
            }
            $("#shysave").show();
            $(".hysty").hide();
            $(".defence-config").hide();
            $("#LinkageMode").hide();
        }
    });
    // 是否展示时间控件
    $('#DefensePlan').change(function(v) {
        if (v.val == 'false') {
            $('#recordDiv').show()
        } else {
            $('#recordDiv').hide()
        }
    });
    $('#FIdeploymentTime').change(function(v) {
        if (v.val == 'false') {
            $('#fireModel').show()
        } else {
            $('#fireModel').hide()
        }
    });
    $('#chuBeepAlert').change(function() {
        if ($(this).is(':checked') == false) {
            $(".lgelecheck").hide();
        } else {
            $(".lgelecheck").show();
        }
    });
    // 清除区域
    $("#clearbtn").click(function() { //清除区域
        if (sessionStorage.getItem("playstyle") == "EasyVideo") {
            PolygonConfigFautil(2, 2, imgindex);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
            PolygonProtectionControl(5, 0, ""); //清除现有多边形
            PolygonProtectionControl(2, 4, ""); //重新设置多边形
        } else {
            var c = document.getElementById("myCanvas");
            c.width = c.width
        }
    });
    if (config.devicelose) {
        addEventListener("resize", function(event) {});
    }
    $(window).resize(function() {
        if (sessionStorage.getItem("playstyle") == "EasyVideo" && window.location.hash == "#ipc/pages/events/humanFormDetection.html") {
            ScalePitch("box-border");
            if (humanState) {
                preWindowfollowing();
            }
        } else if (window.location.hash == "#ipc/pages/events/humanFormDetection.html" && sessionStorage.getItem("playstyle") == "MJPEG") {
            ScalePitch("box-border")
            getpeopleRegionCfg()
        } else if (window.location.hash == "#ipc/pages/events/humanFormDetection.html" && sessionStorage.getItem("playstyle") == "WebPlayer") {
            ScalePitch("box-border")
            getpeopleRegionCfg()
        }
    });

    //离岗灯光报警使能切换
    $('#FCLightalarm').change(function() {
        if ($(this).is(':checked') == false) {
            $(".lgelecheck1").hide();
        } else {
            $(".lgelecheck1").show();
        }
    });

    // 选择旁边的预定义区域
    $("#motionpolygonimg li img").click(function(e) {
        var imgindex = $(this).attr("imgindex");
        for (var i = 0; i < $("#motionpolygonimg li img").length; i++) {
            if (i + 3 == imgindex) {
                continue
            } else {
                $("#motionpolygonimg li img")[i].src = window.location.origin + "/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(2, 3, imgindex);
        } else if (sessionStorage.getItem("playstyle") == "ActiveX") {
            PolygonProtectionControl(5, 1, ""); //清除
            PolygonProtectionControl(2, imgindex, "");
        } else {
            var picarr = []
            if (imgindex == 4) {
                for (var i = 0; i < trgleFour.length; i++) {
                    var obj = {}
                    obj.x = Math.floor(trgleFour[i].x / 560 * $("#axdiv").width())
                    obj.y = Math.floor(trgleFour[i].y / 420 * $("#axdiv").height())
                    picarr.push(obj)
                }
                createdPitch(picarr, "myCanvas")
            } else if (imgindex == 3) {
                for (var i = 0; i < trgle.length; i++) {
                    var obj = {}
                    obj.x = Math.floor(trgle[i].x / 560 * $("#axdiv").width())
                    obj.y = Math.floor(trgle[i].y / 420 * $("#axdiv").height())
                    picarr.push(obj)
                }
                createdPitch(picarr, "myCanvas")
            } else if (imgindex == 5) {
                for (var i = 0; i < trgleFive.length; i++) {
                    var obj = {}
                    obj.x = Math.floor(trgleFive[i].x / 560 * $("#axdiv").width())
                    obj.y = Math.floor(trgleFive[i].y / 420 * $("#axdiv").height())
                    picarr.push(obj)
                }
                createdPitch(picarr, "myCanvas")
            } else if (imgindex == 6) {
                for (var i = 0; i < trgleSex.length; i++) {
                    var obj = {}
                    obj.x = Math.floor(trgleSex[i].x / 560 * $("#axdiv").width())
                    obj.y = Math.floor(trgleSex[i].y / 420 * $("#axdiv").height())
                    picarr.push(obj)
                }
                createdPitch(trgleSex, "myCanvas")
            } else if (imgindex == 7) {
                for (var i = 0; i < trgleSeven.length; i++) {
                    var obj = {}
                    obj.x = Math.floor(trgleSeven[i].x / 560 * $("#axdiv").width())
                    obj.y = Math.floor(trgleSeven[i].y / 420 * $("#axdiv").height())
                    picarr.push(obj)
                }
                createdPitch(trgleSeven, "myCanvas")
            } else {
                for (var i = 0; i < trgleEight.length; i++) {
                    var obj = {}
                    obj.x = Math.floor(trgleEight[i].x / 560 * $("#axdiv").width())
                    obj.y = Math.floor(trgleEight[i].y / 420 * $("#axdiv").height())
                    picarr.push(obj)
                }
                createdPitch(trgleEight, "myCanvas")
            }

        }
    });
    // 点击试听按钮
    $("#motionbtn").click(function() {
        setTryvoice('fire')
    });
    // 点击保存
    $("#chusave,#svhusave,#deSave,#shysave").click(function() {
            if ("admin" == config.user || "super_admin" == config.user) {
                if ($("#firedetectCheck").is(':checked') && config.deviceAiCap[number].Firedetectsupport == "true") {
                    rebootObj = needReboot(11);
                    if (rebootObj.isReBoot == 'true') {
                        var isUpplementary = rebootObj.hasOwnProperty('isUpplementary') ? rebootObj.isUpplementary : 0;
                        $.RestartModel.mask(function() {
                            setFireconfig();
                            setAudioAlarmConfig();
                            setlightmode();
                        }, isUpplementary);
                        return;
                    }
                }
                setFireconfig();
                setAudioAlarmConfig();
                setlightmode();
            } else {
                $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
            }
        })
        // 保存声音布防时间
    $("#voiceSave").click(function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            var isfor = true;
            setAudioAlarmConfig(isfor);
            $("#myModal").modal('hide');
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
        }
    })


});

function fireCustomVoice(val) {
    // config.assistCommand="3";//自定义语音的次命令
    if(val==="custom"&&config.deviceCap[number].enableG711U == "true"){//自定义
        if( document.getElementById('fireDefeVoice').childNodes.length > 0){//已经植入html，直接show
            $("#fireDefeVoice").show();
        }else{ //没有植入,获取一下再去show
            loadVoiceURL("ipc/pages/customSound.html",$("#fireDefeVoice"),"3")
        }
    }else{
        $("#fireDefeVoice").hide();  //非自定义声音直接隐藏
    }
}

function openVideo() {
    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();
            $("#axdiv").show();
            $("#display").hide();
            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() {
            getFireconfig(timeplaned, timeplandvoice);
        }, 100)
    } else {
        if (sessionStorage.getItem("xystyle") == "p6s" || sessionStorage.getItem("xystyle") == "p2p") {
            config.refreshplayvideo = true;
            $("#playCanvas").hide();
            $("#myCanvas").hide();
            $("#axdiv").show();
            var obj = {};
            obj.a = timeplaned;
            obj.b = timeplandvoice;
            getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 13, obj, true);
        } else {
            if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                $("#playCanvas").hide();
                $("#axdiv").show();
                $("#display").hide();
            } 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 = timeplaned;
                obj.b = timeplandvoice;
                getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true, 13, obj, true);
                if (sessionStorage.getItem("playstyle") != "EasyVideo") {
                    getFireconfig(timeplaned, timeplandvoice); //进来获取火焰配置
                }
            } 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);
                                    getFireconfig(timeplaned, timeplandvoice); //进来获取火焰配置
                                });
                            });
                        });
                    }
                } else if (sessionStorage.getItem("playstyle") == "EasyVideo") {
                    refershPlayer("fire", timeplaned, timeplandvoice)
                        // getFireconfig(mq, mh); //进来获取配置
                } else if (sessionStorage.getItem("playstyle") == "MJPEG") {
                    getVideoPlugin(sessionStorage.getItem("playstyle"), 1, "", true);
                    getFireconfig(timeplaned, timeplandvoice); //进来获取配置
                }

            }



        }

    }

}

// 渲染白光灯
function showVoiceOut() {
    // 渲染进度条
    $('#activeBrightness').jRange({
        from: 0,
        to: 100,
        // step: 1,
        scale: 1,
        format: '%s',
        width: 260,
        showLabels: false,
        showScale: false,
        onstatechange: function() {
            $("#activeBrightnessValue").text($("#activeBrightness").val());
        },
        onSetPosition: function() {
            $("#activeBrightnessValue").text($("#activeBrightness").val());
        },
        onMouseDown: function() {},
        onMouseUp: function() {}
    });
}
// 渲染声音报警音量
function showVoiceOuts() {
    // 渲染进度条
    $('#BroadcastBrightness').jRange({
        from: 0,
        to: 100,
        // step: 1,
        scale: 1,
        format: '%s',
        width: 260,
        showLabels: false,
        showScale: false,
        onstatechange: function() {
            $("#BroadcastBrightnessValue").text($("#BroadcastBrightness").val());
        },
        onSetPosition: function() {
            $("#BroadcastBrightnessValue").text($("#BroadcastBrightness").val());
        },
        onMouseDown: function() {},
        onMouseUp: function() {}
    });
}

function peopleLink() {
    $(".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");
}
// 栏目切换
function changeTab() {
    var qu = document.getElementById('place')
    var ld = document.getElementById('liand')
    var de = document.getElementById('firedefence')
    qu.classList.add('qutable')
    ld.classList.remove('qutable')
    de.classList.remove('qutable')
}
// 初始化下拉框数据
function selectvalue() {
    $("<option value='true'>" + $.i18n.prop("i18n-allday") + "</option>").appendTo("#DefensePlan");
    $("<option value='false'>" + $.i18n.prop("i18n-customize") + "</option>").appendTo("#DefensePlan");
    var ni = $.i18n.prop("i18n-sensitivity-value").split(",")
    for (var i = 0; i < ni.length; i++) {
        $("<option value='" + lmd[i] + "'>" + ni[i] + "</option>").appendTo("#sensitivity");
    }
    // 声音类型
    var st = $.i18n.prop("i18n-str_voice_type").split(",")
    var lgaudioVoicetype = $(config.deviceAiCap[number].FiredetectAudioType)
    console.log(lgaudioVoicetype);
    for (var i = 0; i < 12; i++) {
        if (lgaudioVoicetype.find("Custom").text() == "true" && sylx[i] == "custom") {
            $("<option value='" + sylx[i] + "'>" + st[i] + "</option>").appendTo("#SoundType");
        } else if (lgaudioVoicetype.find("Alarm").text() == "true" && sylx[i] == "alarm") {
            $("<option value='" + sylx[i] + "'>" + st[i] + "</option>").appendTo("#SoundType");
        } else if (lgaudioVoicetype.find("dog").text() == "true" && sylx[i] == "dog") {
            $("<option value='" + sylx[i] + "'>" + st[i] + "</option>").appendTo("#SoundType");
        } else if (lgaudioVoicetype.find("warning").text() == "true" && sylx[i] == "warning area") {
            $("<option value='" + sylx[i] + "'>" + st[i] + "</option>").appendTo("#SoundType");
        } else if (lgaudioVoicetype.find("monitoring").text() == "true" && sylx[i] == "monitoring area") {
            $("<option value='" + sylx[i] + "'>" + st[i] + "</option>").appendTo("#SoundType");
        } else if (lgaudioVoicetype.find("welcome").text() == "true" && sylx[i] == "welcome") {
            $("<option value='" + sylx[i] + "'>" + st[i] + "</option>").appendTo("#SoundType");
        } else if (lgaudioVoicetype.find("DeepWater").text() == "true" && sylx[i] == "Deep Water Warning") {
            $("<option value='" + sylx[i] + "'>" + st[i] + "</option>").appendTo("#SoundType");
        } else if (lgaudioVoicetype.find("PrivateTerritory").text() == "true" && sylx[i] == "Private territory") {
            $("<option value='" + sylx[i] + "'>" + st[i] + "</option>").appendTo("#SoundType");
        } else if (lgaudioVoicetype.find("DangerZone").text() == "true" && sylx[i] == "danger zone") {
            $("<option value='" + sylx[i] + "'>" + st[i] + "</option>").appendTo("#SoundType");
        } else if (lgaudioVoicetype.find("ValuableObjects").text() == "true" && sylx[i] == "Valuable objects") {
            $("<option value='" + sylx[i] + "'>" + st[i] + "</option>").appendTo("#SoundType");
        } else if (lgaudioVoicetype.find("HighWarning").text() == "true" && sylx[i] == "High Warning") {
            $("<option value='" + sylx[i] + "'>" + st[i] + "</option>").appendTo("#SoundType");
        } else if (lgaudioVoicetype.find("PrivateParking").text() == "true" && sylx[i] == "Private Parking") {
            $("<option value='" + sylx[i] + "'>" + st[i] + "</option>").appendTo("#SoundType");
        }
    }
    if (lgaudioVoicetype.find("FireAlarm").text() == "true") { //火警声
        $("<option value='FireAlarm'>" + $.i18n.prop("i18n-firedetect-voice") + "</option>").appendTo("#SoundType");
    }
    // 适配app逻辑，不存在能力时默认展示三个
    if ($("#SoundType").children().length == 0) {
        $("<option value='custom'>" + st[0] + "</option>").appendTo("#SoundType");
        $("<option value='alarm'>" + st[1] + "</option>").appendTo("#SoundType");
        $("<option value='dog'>" + st[2] + "</option>").appendTo("#SoundType");
    }
    // 播报次数
    var bc = $.i18n.prop("i18n-broadcast").split(",")
    for (var i = 0; i < bc.length; i++) {
        $("<option value='" + bcs[i] + "'>" + bc[i] + "</option>").appendTo("#FrequencyBroadcast");
    }

    // 延长时间
    var bm = $.i18n.prop("i18n-broadcast-miao").split(",")
    for (var i = 0; i < bm.length; i++) {
        $("<option value='" + bcm[i] + "'>" + bm[i] + "</option>").appendTo("#FrequencyDelay");
    }
}
//试听
function setTryvoice(v) {
    var voiceXmldoc = '<?xml version="1.0" encoding="UTF-8" ?>' +
        "<AudioAlarmConfig><ChannelID>1</ChannelID>" +
        "<PeopleAudioType></PeopleAudioType><CarAudio></CarAudio>" +
        "<FireAudioType>" + $("#SoundType").val() + "</FireAudioType><AudioOutputDelay></AudioOutputDelay>" +
        "<AudioVolume></AudioVolume>" +
        "<TryListenType>" + v + "</TryListenType>" +
        "<AlarmInExAudioType></AlarmInExAudioType>" +
        "<VideoShelterAudioType></VideoShelterAudioType>" +
        "<MotionAudioType></MotionAudioType>" +
        "<ElectronicDenceAudioType></ElectronicDenceAudioType>" +
        "<CrossBorderDetectAudioType></CrossBorderDetectAudioType>" +
        "<OffDutyDetectAudioType></OffDutyDetectAudioType>" +
        "</AudioAlarmConfig>"
    var cyURL = window.config.baseUrl + "/System/1/TryListenSelectedAlarmAudioV1";
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: voiceXmldoc,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr, 1);
        }
    });
}
// 获取火焰使能
function gethyEnable() {
    $.ajax({
        url: window.config.baseUrl + "/System/FireDetectCfgInfo",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            hyStatus = JSON.parse($(xmlDoc).find('FireDetectCfgInfo').eq(0).find('Enable').eq(0).text())
            $("#firedetectCheck").prop('checked', hyStatus); //使能
            if (hyStatus) {
                $(".hysty").show();
                changeTab();
                openVideo();
            } else {
                $(".hysty").hide()
                $("#shysave").show();
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });

}
// 获取火焰检测配置
function getFireconfig(mq, mh) {
    $.ajax({
        url: window.config.baseUrl + "/System/FireDetectCfgInfo",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            // xmlMotionDetection = xmlDoc;
            // $("#firedetectCheck").prop('checked', JSON.parse($(xmlDoc).find('FireDetectCfgInfo').eq(0).find('Enable').eq(0).text())); //使能
            $("#sensitivity").val($(xmlDoc).find('Sensitivity').text()).trigger('change'); //灵敏度
            $("#nightCheck").val($(xmlDoc).find('NightDetectEnable').text()).trigger('change'); //夜间检测开关
            $("#activeBrightness").val($(xmlDoc).find('WhiteLightBrightness').text()) //白光灯亮度
            $("#BackgroundImage").val($(xmlDoc).find('IsPushBackgroundPicture').text()).trigger('change'); //背景图
            showVoiceOut();
            $("#chudpick").prop('checked', JSON.parse($(xmlDoc).find("Snapshot").find("Enable").text())); //触发sd卡抓图
            $("#chudvdeo").prop('checked', JSON.parse($(xmlDoc).find("Record").find("Enable").text())); //触发sd卡录像
            $("#chuBeepAlert").prop('checked', JSON.parse($(xmlDoc).find('BeepAlert').eq(0).find('Enable').text())); //触发声音报警
            if ($("#chuBeepAlert").is(':checked') == false) {
                $(".lgelecheck").hide();
            } else {
                $(".lgelecheck").show();
            }
            $("#chuAlarmOut").prop('checked', JSON.parse($(xmlDoc).find('AlarmOut').eq(0).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())); //触发FTP
            $("#chuTriggerpush").prop('checked', JSON.parse($(xmlDoc).find("Push").find("Enable").text())); //触发推送
            $("#FCLightalarm").prop('checked', JSON.parse($(xmlDoc).find("LightAlarm").find("Enable").text())); //触发推送
            if ($("#FCLightalarm").is(':checked') == false) {
                $(".lgelecheck1").hide();
            } else {
                $(".lgelecheck1").show();
            }
            $("#DefensePlan").val($(xmlDoc).find('AllDay').text()).trigger('change'); //普通布防
            if ($("#DefensePlan").val() == 'false') {
                $("#recordDiv").show()
            } else {
                $("#recordDiv").hide()
            }
            // 画框
            var pointnum = $(xmlDoc).find("Point").length;
            imgindex = pointnum;
            var urlImage = window.location.origin + "/ipc/img/eventTips/xz_xz_0" + (pointnum - 2) + ".png"
            $("#motionpolygonimg li img").each(function() {
                if ($(this).attr("imgindex") == pointnum) {
                    $(this).attr("src", urlImage);
                };
            });
            var str = "";
            if (sessionStorage.getItem("playstyle") == "ActiveX") { //使用老插件画框
                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>'
                };
                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") { //使用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) * $("#axdiv").width());
                    obj.y = Math.floor((b / menbfry) * $("#axdiv").height());
                    lineChse.push(obj);
                }
                createdPitch(lineChse, "myCanvas");
            }
            setScheduleXp(xmlDoc, mq);
            getAudioAlarmConfig(mh);
            getlightmode();
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}
// 灯光报警
function getlightmode() {
    $.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("LightMode").text());
            $("#lgdelaytime").val($(xmlDoc).find("DelayTime").text());
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}
// 获取火焰拓展配置-布防时间
function getFireTime(mh) {
    $.ajax({
        url: window.config.baseUrl + "/System/FireDetectExCfg",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            setScheduleX(xmlDoc, mh)
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}
// 获取火焰拓展配置
function getAudioAlarmConfig(mh) {
    $.ajax({
        url: window.config.baseUrl + "/System/FireDetectExCfg",
        type: "GET",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            xmlAudioAlarmConfig = xmlDoc;
            // 声音报警
            $("#SoundType").val($(xmlDoc).find('VoiceType').eq(0).text()).trigger('change'); //声音报警类型
            $("#FrequencyBroadcast").val($(xmlDoc).find('BroadcastCount').eq(0).text() + '').trigger('change'); //播报次数
            $("#BroadcastBrightness").val($(xmlDoc).find('BroadcastCountVolume').text()) //音量
            showVoiceOuts();
            var status = $(xmlDoc).find("FireDetectExCfg").eq(0).find('Schedule').find("DayMode").text()
            if (status == "disable") {
                $("#FIdeploymentTime").val($(xmlDoc).find("FireDetectExCfg").eq(0).find('Schedule').find("AllDay").text()).trigger('change');
            } else {
                $("#FIdeploymentTime").val(status).trigger('change')
            }
            if ($("#FIdeploymentTime").val() == "false") {
                $("#fireModel").show()
            } else {
                $("#fireModel").hide()
            }
            setScheduleX(xmlDoc, mh)
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}
// 设置声音报警布防区域
function setScheduleX(d, btimecaset) {
    // 转换xml中的时间
    var timeArr = [];
    var time = [];
    for (var i = 0; i < 7; i++) {
        timeArr[i] = $(d).find('TimeBlock_' + i).eq(0).text()
        for (var o = 0; o < 24; o++) {
            if (timeArr[i].charAt(2 * o) == 1) {
                time.push(1)
            } else {
                time.push(0)
            }
        }
    }
    btimecaset.setValue(changetimeFool(group(time, 24)));
}
// 设置普通布防区域
function setScheduleXp(d, btimecasetp) {
    // 转换xml中的时间
    var timeArr = [];
    var time = [];
    for (var i = 0; i < 7; i++) {
        timeArr[i] = $(d).find('TimeBlock_' + i).eq(0).text()
        for (var o = 0; o < 24; o++) {
            if (timeArr[i].charAt(2 * o) == 1) {
                time.push(1)
            } else {
                time.push(0)
            }
        }
    }
    btimecasetp.setValue(changetimeFool(group(time, 24)));
}
// 保存火焰检测配置
function setFireconfig() {
    var timeArrp = takeZero(timeplaned.getvalue()); //普通布防
    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) / $("#axdiv").width()) + '</PosX><PosY>' + Math.floor((newPointList[k].y * menbfry) / $("#axdiv").height()) + '</PosY></Point>'
        }
    }
    if (sessionStorage.getItem("playstyle") != "EasyVideo") {
        var xmldocx = '<?xml version="1.0" encoding="UTF-8" ?>' +
            '<FireDetectCfgInfo Version="1.0">' +
            '<Enable>' + $("#firedetectCheck").is(':checked') + '</Enable><Sensitivity>' + $("#sensitivity").val() + '</Sensitivity>' +
            '<NightDetectEnable>false</NightDetectEnable>' +
            '<WhiteLightBrightness>0</WhiteLightBrightness>' +
            '<IsPushBackgroundPicture>' + $("#BackgroundImage").val() + '</IsPushBackgroundPicture>' +
            '<Trigger Version="1.0">' +
            '<NotifyAMS Version="1.0">' +
            '<Enable>false</Enable>' +
            '</NotifyAMS>' +
            '<BeepAlert Version="1.0">' +
            '<Enable>' + $("#chuBeepAlert").is(':checked') + '</Enable>' +
            '</BeepAlert>' +
            '<FullScreen Version="1.0">' +
            '<Enable>false</Enable>' +
            '</FullScreen>' +
            '<Mail Version="1.0">' +
            '<Enable>' + $("#chuemail").is(':checked') + '</Enable>' +
            '</Mail>' +
            '<Ftp Version="1.0">' +
            '<Enable>' + $("#chuftp").is(':checked') + '</Enable>' +
            '</Ftp>' +
            '<Push Version="1.0">' +
            '<Enable>' + $("#chuTriggerpush").is(':checked') + '</Enable>' +
            '</Push>' +
            '<AlarmOut Version="1.0">' +
            '<Enable>' + $("#chuAlarmOut").is(':checked') + '</Enable>' +
            '<AlarmOutMask>1</AlarmOutMask>' +
            '</AlarmOut>' +
            '<Snapshot Version="1.0">' +
            '<Enable>' + $("#chudpick").is(':checked') + '</Enable>' +
            '<SnapshotMask>1</SnapshotMask>' +
            '</Snapshot>' +
            '<Record Version="1.0">' +
            '<Enable>' + $("#chudvdeo").is(':checked') + '</Enable>' +
            '<RecordMask>1</RecordMask>' +
            '</Record>' +
            '<PTZ Version="1.0">' +
            '<Enable>false</Enable>' +
            '<PTZActionList Version="1.0">' +
            '<PTZAction Version="1.0">' +
            '<ChannelID>1</ChannelID>' +
            '<ActionName>none</ActionName>' +
            '<ActionNum>0</ActionNum>' +
            '</PTZAction>' +
            '</PTZActionList>' +
            '</PTZ>' +
            '<FaceMask Version="1.0">' +
            '<Enable>false</Enable>' +
            '</FaceMask>' +
            '<LightAlarm Version="1.0">' +
            '<Enable>' + $("#FCLightalarm").is(':checked') + '</Enable>' +
            '</LightAlarm>' +
            '</Trigger>' +
            '<Schedule Version = "1.0" ><AllDay>' + $("#DefensePlan").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>' +
            '<Polygon>' + strxml + '</Polygon></FireDetectCfgInfo>'
        var cyURL = window.config.baseUrl + "/System/FireDetectCfgInfo";
        $.ajax({
            type: "PUT",
            url: cyURL,
            async: false,
            processData: false,
            data: xmldocx,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            complete: function(xhr, textStatus) {
                xhrState = xhr
                SaveState(xhr);

            }
        });

    }
}
// easyvideo下保存坐标数据和配置
function getfiretricValue(data) {
    var timeArrp = takeZero(timeplaned.getvalue()); //普通布防
    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 xmldocx = '<?xml version="1.0" encoding="UTF-8" ?>' +
        '<FireDetectCfgInfo Version="1.0">' +
        '<Enable>' + $("#firedetectCheck").is(':checked') + '</Enable><Sensitivity>' + $("#sensitivity").val() + '</Sensitivity>' +
        '<NightDetectEnable>' + $("#nightCheck").val() + '</NightDetectEnable>' +
        '<WhiteLightBrightness>' + $("#activeBrightness").val() + '</WhiteLightBrightness>' +
        '<IsPushBackgroundPicture>' + $("#BackgroundImage").val() + '</IsPushBackgroundPicture>' +
        '<Trigger Version="1.0">' +
        '<NotifyAMS Version="1.0">' +
        '<Enable>false</Enable>' +
        '</NotifyAMS>' +
        '<BeepAlert Version="1.0">' +
        '<Enable>' + $("#chuBeepAlert").is(':checked') + '</Enable>' +
        '</BeepAlert>' +
        '<FullScreen Version="1.0">' +
        '<Enable>false</Enable>' +
        '</FullScreen>' +
        '<Mail Version="1.0">' +
        '<Enable>' + $("#chuemail").is(':checked') + '</Enable>' +
        '</Mail>' +
        '<Ftp Version="1.0">' +
        '<Enable>' + $("#chuftp").is(':checked') + '</Enable>' +
        '</Ftp>' +
        '<Push Version="1.0">' +
        '<Enable>' + $("#chuTriggerpush").is(':checked') + '</Enable>' +
        '</Push>' +
        '<AlarmOut Version="1.0">' +
        '<Enable>' + $("#chuAlarmOut").is(':checked') + '</Enable>' +
        '<AlarmOutMask>1</AlarmOutMask>' +
        '</AlarmOut>' +
        '<Snapshot Version="1.0">' +
        '<Enable>' + $("#chudpick").is(':checked') + '</Enable>' +
        '<SnapshotMask>1</SnapshotMask>' +
        '</Snapshot>' +
        '<Record Version="1.0">' +
        '<Enable>' + $("#chudvdeo").is(':checked') + '</Enable>' +
        '<RecordMask>1</RecordMask>' +
        '</Record>' +
        '<PTZ Version="1.0">' +
        '<Enable>false</Enable>' +
        '<PTZActionList Version="1.0">' +
        '<PTZAction Version="1.0">' +
        '<ChannelID>1</ChannelID>' +
        '<ActionName>none</ActionName>' +
        '<ActionNum>0</ActionNum>' +
        '</PTZAction>' +
        '</PTZActionList>' +
        '</PTZ>' +
        '<FaceMask Version="1.0">' +
        '<Enable>false</Enable>' +
        '</FaceMask>' +
        '<LightAlarm Version="1.0">' +
        '<Enable>' + $("#FCLightalarm").is(':checked') + '</Enable>' +
        '</LightAlarm>' +
        '</Trigger>' +
        '<Schedule Version = "1.0" ><AllDay>' + $("#DefensePlan").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>' +
        '<Polygon>' + strxml + '</Polygon></FireDetectCfgInfo>'
    var cyURL = window.config.baseUrl + "/System/FireDetectCfgInfo";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        processData: false,
        data: xmldocx,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            // getfacetime(faceTime, faceTimeVoice);
            SaveState(xhr);
        }
    });

}

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

}
// 设置火焰检测拓展配置
function setAudioAlarmConfig(d) {
    var timeArr = takeZero(timeplandvoice.getvalue()); //普通布防
    // 语音布防
    var status = ""
    var statusd = ""
    if ($("#FIdeploymentTime").val() == "true") {
        status = "true"
        statusd = "disable"
    } else if ($("#FIdeploymentTime").val() == "false") {
        status = "false"
        statusd = "disable"
    } else if ($("#FIdeploymentTime").val() == "evening") {
        status = "true"
        statusd = "evening"
    } else if ($("#FIdeploymentTime").val() == "day") {
        status = "true"
        statusd = "day"
    }
    var xmldocx = '<?xml version="1.0" encoding="UTF-8" ?>' +
        '<FireDetectExCfg>' +
        '<Enable>true</Enable>' +
        '<VoiceType>' + $("#SoundType").val() + '</VoiceType>' +
        '<BroadcastCount>' + $('#FrequencyBroadcast').val() + '</BroadcastCount>' +
        '<BroadcastCountVolume>' + $('#BroadcastBrightness').val() + '</BroadcastCountVolume>' +
        '<Schedule 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>' +
        '</Schedule>' +
        '</FireDetectExCfg>'
    $.ajax({
        url: window.config.baseUrl + "/System/FireDetectExCfg",
        type: "PUT",
        async: false,
        processData: false,
        data: xmldocx,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            if (d) {
                $.optionBootoast($.i18n.prop('i18n-savesuccess'), "success")
            }
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}
// 画点封装
function createdot(x, y, c) {
    c.beginPath()
    c.arc(x, y, 2, 0, 360)
    c.closePath()
    c.fillStyle = "red"
    c.fill()
}
// 连线
function creatdTriangle(trgle, c) {
    c.strokeStyle = '#33FF00' //设置线条颜色
    c.beginPath()
    if (trgle.length == 3) {
        c.moveTo(trgle[0].x, trgle[0].y) //起点
        for (var q = 1; q < trgle.length; q++) {
            c.lineTo(trgle[q].x, trgle[q].y)
        }
        c.closePath()
        c.stroke() //开始绘制直线
    } else if (trgle.length == 4) {
        c.moveTo(trgle[0].x, trgle[0].y) //起点
        for (var q = 1; q < trgle.length; q++) {
            c.lineTo(trgle[q].x, trgle[q].y)
        }
        c.closePath()
        c.stroke() //开始绘制直线
    } else if (trgle.length == 5) {
        c.moveTo(trgle[0].x, trgle[0].y) //起点
        for (var q = 1; q < trgle.length; q++) {
            c.lineTo(trgle[q].x, trgle[q].y)
        }
        c.closePath()
        c.stroke() //开始绘制直线
    } else if (trgle.length == 6) {
        c.moveTo(trgle[0].x, trgle[0].y) //起点
        for (var q = 1; q < trgle.length; q++) {
            c.lineTo(trgle[q].x, trgle[q].y)
        }
        c.closePath()
        c.stroke() //开始绘制直线
    } else if (trgle.length == 7) {
        c.moveTo(trgle[0].x, trgle[0].y) //起点
        for (var q = 1; q < trgle.length; q++) {
            c.lineTo(trgle[q].x, trgle[q].y)
        }
        c.closePath()
        c.stroke() //开始绘制直线
    } else {
        c.moveTo(trgle[0].x, trgle[0].y) //起点
        for (var q = 1; q < trgle.length; q++) {
            c.lineTo(trgle[q].x, trgle[q].y)
        }
        c.closePath()
        c.stroke() //开始绘制直线

    }
}
//多边形主方法
function createdPitch(trgle, ids) {
    newPointList = trgle
    var c = document.getElementById(ids);
    var ctx = c.getContext("2d");
    c.width = c.width
    for (var i = 0; i < trgle.length; i++) {
        createdot(trgle[i].x, trgle[i].y, ctx)
    }
    creatdTriangle(trgle, ctx)
    var tx, ty, stx, sty, oldx, oldy
    c.onmousedown = function(event) {
        var rect = c.getBoundingClientRect();
        tx = event.clientX - rect.left
        ty = event.clientY - rect.top
        oldx = tx
        oldy = ty
        var qe = chooseDot(tx, ty, trgle)
        if (qe || qe == 0) {
            if (tx - trgle[qe].x <= 2 && tx - trgle[qe].x >= -2) {
                stx = true
            } else {
                stx = !stx
            }
            if (ty - trgle[qe].y <= 2 && ty - trgle[qe].y >= -2) {
                sty = true
            } else {
                sty = !stx
            }
            if (stx == true && sty == true) {
                c.onmousemove = function(event) {
                    var rect = c.getBoundingClientRect();
                    c.width = c.width
                    trgle[qe].x = event.clientX - rect.left
                    trgle[qe].y = event.clientY - rect.top
                    for (var l = 0; l < trgle.length; l++) {
                        createdot(trgle[l].x, trgle[l].y, ctx)
                    }
                    creatdTriangle(trgle, ctx)

                }
                c.onmouseup = function(event) {
                    var b = chooseArr(trgle, qe)
                    var pp = allLineche(b)
                    var statusd = chooseINline(trgle[qe].x, trgle[qe].y, pp) //是否在线上
                    var km = null
                    if (trgle.length > 3) {
                        if (qe == 0) {
                            var kt = false
                            for (var i = 1; i < trgle.length - 1; i++) {
                                if (qe == i || qe + 1 == i) {
                                    kt = LineSegmentsIntersect(trgle[qe], trgle[trgle.length - 1], trgle[i], trgle[i + 1])
                                    continue
                                } else {
                                    if (i == trgle.length - 1) {
                                        var st = LineSegmentsIntersect(trgle[qe], trgle[qe + 1], trgle[trgle.length - 1], trgle[0])
                                    } else {
                                        var st = LineSegmentsIntersect(trgle[qe], trgle[qe + 1], trgle[i], trgle[i + 1])
                                    }
                                }
                                if (st || kt) {
                                    km = true
                                    break
                                }
                            }
                        } else if (qe == trgle.length - 1) {
                            var st = false
                            for (var t = 0; t < trgle.length - 2; t++) {
                                if (qe == t || qe - 2 == t) {
                                    kt = LineSegmentsIntersect(trgle[qe], trgle[0], trgle[t], trgle[t + 1])
                                    if (st || kt) {
                                        km = true
                                    }
                                    continue
                                } else {
                                    st = LineSegmentsIntersect(trgle[qe], trgle[qe - 1], trgle[t], trgle[t + 1])
                                }
                                if (st || kt) {
                                    km = true
                                    break
                                }
                            }

                        } else {
                            for (var t = qe; t < trgle.length + qe - 1; t++) {
                                if (qe + 1 == t + 1) {
                                    if (t + 2 >= trgle.length) {
                                        kt = LineSegmentsIntersect(trgle[qe], trgle[qe - 1], trgle[t + 1], trgle[t + 2 - trgle.length])
                                    } else {
                                        kt = LineSegmentsIntersect(trgle[qe], trgle[qe - 1], trgle[t + 1], trgle[t + 2])
                                    }
                                    if (st || kt) {
                                        km = true
                                        break
                                    } else {
                                        continue

                                    }
                                } else {
                                    if (t + 2 == trgle.length) {
                                        var st = LineSegmentsIntersect(trgle[qe], trgle[qe + 1], trgle[t + 1], trgle[t + 2 - trgle.length])
                                    } else if (t + 1 == trgle.length) {
                                        continue
                                    } else if (t + 2 > trgle.length) {
                                        var st = LineSegmentsIntersect(trgle[qe], trgle[qe + 1], trgle[t - trgle.length], trgle[t + 1 - trgle.length])
                                    } else {
                                        var st = LineSegmentsIntersect(trgle[qe], trgle[qe + 1], trgle[t + 1], trgle[t + 2])
                                    }
                                }
                                if (st || kt) {
                                    km = true
                                    break
                                }
                            }

                        }

                    }
                    if (km || statusd) {
                        c.onmousemove = null;
                        c.onmouseup = null;
                        c.width = c.width
                        trgle[qe].x = oldx
                        trgle[qe].y = oldy
                        for (var z = 0; z < trgle.length; z++) {
                            createdot(trgle[z].x, trgle[z].y, ctx)
                        }
                        newPointList = trgle
                        creatdTriangle(trgle, ctx)

                    } else {
                        newPointList = trgle
                        c.onmousemove = null;
                        c.onmouseup = null;
                    }
                };

            }
        }
    }
}
// 判断是哪个点
function chooseDot(a, b, trgle) {
    for (var i = 0; i < trgle.length; i++) {
        var o = trgle[i].x - a
        var p = trgle[i].y - b
        if (o >= -2 && o <= 2 && p >= -2 && p <= 2) {
            return i
        }
    }
}
// 判断点是否在线段上
function chooseINline(a, b, trgle) {
    for (var i = 0; i < trgle.length; i++) {
        if ((a - trgle[i].a.x) * (trgle[i].b.y - trgle[i].a.y) == (trgle[i].b.x - trgle[i].a.x) * (b - trgle[i].a.y)) {
            return true
        }
    }
}
// 重组数组
function chooseArr(d, qe) {
    var newArr = []
    for (var i = 0; i < d.length; i++) {
        if (i == qe) {
            continue
        } else {
            newArr.push(d[i])
        }
    }
    return newArr
}
// 组合线段数组
function allLineche(e) {
    var pArr = []
    for (var i = 0; i < e.length; i++) {
        for (var j = i + 1; j < e.length; j++) {
            pArr.push({
                a: e[i],
                b: e[j]
            })
        }
    }
    return pArr
}

function LineSegmentsIntersect(lh, lt, th, tt) {
    if (!(Math.min(lh.x, lt.x) <= Math.max(th.x, tt.x) && Math.min(th.y, tt.y) <= Math.max(lh.y, lt.y) && Math.min(th.x, tt.x) <= Math.max(lh.x, lt.x) && Math.min(lh.y, lt.y) <= Math.max(th.y, tt.y))) {
        return false;
    }
    if ((((lh.x - th.x) * (tt.y - th.y) - (lh.y - th.y) * (tt.x - th.x)) *
            ((lt.x - th.x) * (tt.y - th.y) - (lt.y - th.y) * (tt.x - th.x))) > 0 ||
        (((th.x - lh.x) * (lt.y - lh.y) - (th.y - lh.y) * (lt.x - lh.x)) *
            ((tt.x - lh.x) * (lt.y - lh.y) - (tt.y - lh.y) * (lt.x - lh.x))) > 0) {
        return false;
    } else {
        return true;
    }
}
