let state_sj = false;
let myChart, myChart1, myChart2, myChart3;
let ws_j5fz;
let arr_sxx = [];
let flv_arr = [];
let flv_arr1 = [];
let flv_arr2 = [];
let typesss = true;
let video_arr_id = [
    {name: 'video1', id: '202011091016261340_1'},
    {name: 'video2', id: '202011091015195369_1'},
    {name: 'video3', id: '202011031443596917_1'},
    {name: 'video4', id: '202011031442238216_1'},
    {name: 'video5', id: '202011031439089875_1'},
    {name: 'video6', id: '202011031436562054_1'},
]
// function abc() {
//
//     let count = 0;
//     let outTime = 10;//分钟
//     window.setInterval(go, 1000);
//     function go() {
//         count++;
//         if (count == outTime * 1) {
//             var myMp3 = document.getElementById("audio");
//             audio.play();
//             setTimeout(function () {
//                 audio.pause();
//             }, 5000);
//         }
//     }
//
//     let x;
//     let y;
//     //监听鼠标
//     document.onmousemove = function (event) {
//         var x1 = event.clientX;
//         var y1 = event.clientY;
//         if (x != x1 || y != y1) {
//             count = 0;
//         }
//         x = x1;
//         y = y1;
//     };
// }
/**初始化波浪饼状图**/
    //饼状图下面波浪的大小
let value = 0.1;
let data = [value, value, value,];
let option = {
    title: {
        textStyle: {
            fontSize: 22,
            fontFamily: 'Microsoft Yahei',
            fontWeight: 'normal',
            color: '#63aafb',
            rich: {
                a: {
                    fontSize: 20,
                }
            }
        },
        x: 'center',
        y: '25%'
    },
    series: [
        {
            type: 'liquidFill',
            radius: '80%',
            //  shape: 'roundRect',
            data: data,
            backgroundStyle: {
                color: "#ffffff30",
            },
            outline: {
                borderDistance: 5,
                itemStyle: {
                    borderWidth: 3,
                    borderColor: {
                        type: 'linear',
                        x: 0,
                        y: 1,
                        x2: 0,
                        y2: 0,
                        colorStops: [{
                            offset: 0,
                            color: '#e2e2e24f'
                        }, {
                            offset: 0.5,
                            color: 'rgba(24, 197, 254, .4)'
                        }, {
                            offset: 1,
                            color: 'rgba(24, 197, 254, 1)'
                        }],
                        globalCoord: false
                    },
                    shadowBlur: 10,
                    shadowColor: '#000',
                }
            },
            color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [{
                    offset: 1,
                    color: '#368ff3'
                }, {
                    offset: 0.5,
                    color: 'rgba(24, 197, 254, .5)'
                }, {
                    offset: 0,
                    color: 'rgba(58, 71, 212, .8)'
                }],
                globalCoord: false
            },
            label: {
                normal: {
                    formatter: '',
                }
            }
        },
    ]
};
//行政目录
let vue_tree = new Vue({
    el: '.left-nav',
    data: {
        searchText: '',
        cllx: [],
        jk_arr: [],
        jk_s: [],
    },
    methods: {
        fastSearch: function () {
            this.xzlm();
            // $("#tree-xzxq").treeview('search', [this.searchText, {
            //     ignoreCase: true,      // case insensitive
            //     exactMatch: false,     // like or equals
            //     revealResults: true,   // reveal matching nodes
            // }]);
        },
        xzlm: function () {
            $.ajax({
                url: "/dept/getDeptParent/" + getCookie("bjpt_deptId"),
                dataType: "json",
                type: "GET",
                data: {},
                success: function (result) {
                    if (result.code == 0) {
                        let parIds = result.data[0].parentId;
                        $.ajax({
                            url: "/dept/listvideo",
                            dataType: "json",
                            type: "GET",
                            data: {
                                deptId: getCookie("bjpt_deptId"),
                                username: getCookie("bjpt_realName"),
                                tdmc: vue_tree.searchText,
                            },
                            success: function (result) {
                                let defaultData = [];
                                vue_tree.jk_arr = [];
                                if (result.code == 0) {
                                    vue_tree.jk_arr = result.data;
                                    defaultData = toTree(result.data, parIds + '');
                                    $('#tree-xzxq').treeview({
                                        expandIcon: 'glyphicon glyphicon-triangle-right selected-span',
                                        collapseIcon: 'glyphicon glyphicon-triangle-bottom selected-span',
                                        nodeIcon: 'glyphicon glyphicon-folder-open selected-span',
                                        selectedBackColor: '#ffffff',
                                        selectedColor: '#4a4a4a',
                                        onhoverColor: '#73a5ff26',
                                        showBorder: false,
                                        data: defaultData
                                    });
                                    $('#tree-xzxq').on('nodeSelected', function (event, data) {
                                        let item = vue_jkgl.data_sl.find(item => {
                                            return item.name == data.text;
                                        });
                                        let parent_id = $('#tree-xzxq').treeview('getParent', data.nodeId).href;
                                        if (item == undefined) {
                                            if(vue_jkgl.index_s + 1 == vue_jkgl.num){
                                                return
                                            }
                                            typesss = true;
                                            if (vue_jkgl.index_s + 1 == vue_jkgl.num || vue_jkgl.num == 1) {
                                                //当前框框的id  vue_jkgl.data_sl[vue_jkgl.index_s + 1].id
                                                //在此处将rtsp转码H5播放的流加载到指定ID上
                                                vue_jkgl.data_sl[0].type = true;
                                                vue_jkgl.data_sl[0].name = data.text;
                                                vue_jkgl.data_sl[0].parentids = parent_id;
                                                //div_id为当前便签的video_id
                                                //video_id当前点击监控的id
                                                let div_id = vue_jkgl.data_sl[0].id;
                                                let video_id = data.href;
                                                vue_jkgl.data_sl[0].video_id = video_id;
                                                vue_jkgl.data_sl[0].div_id = div_id;
                                                vue_jkgl.data_sl[0].type_bf = true;
                                                let types = false;
                                                video_arr_id.forEach((item, index)=> {
                                                    if (item.id == data.href) {
                                                        types = true;
                                                    }
                                                });
                                                if (types) {
                                                    dxdj_fun(vue_jkgl.data_sl[0].id, video_id, vue_jkgl.data_sl[0].canvas_id_1, vue_jkgl.data_sl[0].canvas_id_2, 0);
                                                } else {
                                                    monitor_sx(video_id, div_id, vue_jkgl.data_sl[0], 1);
                                                }
                                                vue_jkgl.index_s = 0;
                                            } else {
                                                //当前框框的id  vue_jkgl.data_sl[vue_jkgl.index_s + 1].id
                                                //在此处将rtsp转码H5播放的流加载到指定ID上
                                                vue_jkgl.index_s++;
                                                vue_jkgl.data_sl[vue_jkgl.index_s].type = true;
                                                vue_jkgl.data_sl[vue_jkgl.index_s].name = data.text;
                                                vue_jkgl.data_sl[vue_jkgl.index_s].parentids = parent_id;
                                                vue_jkgl.data_sl[vue_jkgl.index_s].type_bf = true;

                                                //div_id为当前便签的video_id
                                                //video_id当前点击监控的id
                                                let div_id = vue_jkgl.data_sl[vue_jkgl.index_s].id;
                                                let video_id = data.href;
                                                vue_jkgl.data_sl[vue_jkgl.index_s].video_id = video_id;
                                                vue_jkgl.data_sl[vue_jkgl.index_s].div_id = div_id;
                                                let types = false;
                                                video_arr_id.forEach((item, index)=> {
                                                    if (item.id == data.href) {
                                                        types = true;
                                                    }
                                                });
                                                if (types) {
                                                    dxdj_fun(vue_jkgl.data_sl[vue_jkgl.index_s].id, video_id, vue_jkgl.data_sl[vue_jkgl.index_s].canvas_id_1, vue_jkgl.data_sl[vue_jkgl.index_s].canvas_id_2, vue_jkgl.index_s);
                                                } else {
                                                    monitor_sx(video_id, div_id, vue_jkgl.data_sl[vue_jkgl.index_s], 1);
                                                }
                                            }
                                            //查找近5分钟的车流量数据，便于交参展示时先拿这个体现出来

                                            let arr_sxx_new = [];
                                            arr_sxx.forEach((item)=> {
                                                if (item.video_id != data.href) {
                                                    arr_sxx_new.push(item);
                                                }
                                            });
                                            arr_sxx = [];
                                            arr_sxx = arr_sxx_new;
                                            j5fz_jczssj(data.href);
                                        }
                                        // alert('点击选中');
                                    });
                                }
                            }
                        });
                    }
                }
            });
        },
    },
    mounted(){
        $.ajax({
            url: "/TrafficStatistics/listcode",
            dataType: "json",
            type: "GET",
            data: {
                codeid: 1,
                alarmlevel: '',
            },
            success: function (result) {
                vue_tree.cllx = [];
                if (result.code == 0) {
                    if (result.data.length > 0) {
                        vue_tree.cllx = result.data;
                    }
                }
            }
        });
        $.ajax({
            url: "/dept/listAllvideoIdsByDeptid",
            dataType: "json",
            type: "GET",
            data: {
                deptid: getCookie("bjpt_deptId"),
            },
            success: function (result) {
                vue_tree.jk_s = [];
                if (result.code == 0) {
                    if (result.data.length > 0) {
                        vue_tree.jk_s = result.data;
                    }
                }
            }
        });
        this.xzlm();
    }
});

//右边视频监控
let vue_jkgl = new Vue({
    el: '.right-nav',
    data: {
        data_sl: [],
        num: 4,
        class_s: 'class_4',
        db_click: true,
        num_inx: 100,
        time: null,
        //判断echarts是否显示
        echarts_show: false,
        //判断是否全屏显示，全屏状态下才显示交参预览
        show_jcyl: false,
        //判断第几个显示
        index_s: -1,
        //全屏展示默认展示全屏，否则退出全屏
        qp_show: true,
        //判断是否有锁定的，有的话就为true
        is_bd: false,
        //锁定的video数据
        data_sd: [],
        //锁定全屏
        is_sfqp: true,
        sx_1: '',
        sx_2: '',
        sx_3: '',
        sx_4: '',
        xx_1: '',
        xx_2: '',
        xx_3: '',
        xx_4: '',
        //重置自动规则
        video_is_cz: '',
    },
    methods: {
        qp_span: function () {
            var full = document.getElementById("qpzs");
            launchIntoFullscreen(full);
            this.qp_show = false;
        },
        tcqp_span: function () {
            exitFullscreen();
            this.qp_show = true;
        },
        gzpz: function () {
            vue_model.pzx = [
                {iem: '基础检测区域'},
                {iem: '施工屏蔽区域'},
                {iem: '施工违规区域'},
                {iem: '交通拥堵检测'},
                {iem: '倒行/逆行检测'},
                {iem: '行人/非机动车禁区'},
                {iem: '机动车禁区'},
                {iem: '交通事故检测区域'},
            ];
            vue_model.tim = 1;
            $("#myModal").modal("show");
        },
        //出现框框
        click_as: function () {
            // alert(1);
            $.ajax({
                type: "get",
                url: "http://192.168.168.108:5000/vehicle_recognition/1",
                success: function (data) {
                    alert(111)
                },
                error: function () {
                    alert('fail');
                }
            });
        },
        //单击
        dj_click: function (index, item) {
            clearTimeout(this.time);
            this.time = setTimeout(() => {
                if (item.video_id != '') {
                    if (this.num_inx == index) {
                        //判断点击的是同一个;
                        this.num_inx = 100;
                    } else {
                        this.num_inx = index;
                    }
                    this.video_is_cz = item.video_id;
                }
            }, 300);
        },
        //双击
        sj_click: function (event, item) {
            clearTimeout(this.time);
            if (item.video_id != '') {
                if (this.db_click) {
                    this.show_jcyl = true;
                    document.getElementById(event.currentTarget.id).classList.add('qpfd');
                    this.db_click = false;
                } else {
                    if (ws_j5fz != undefined) {
                        ws_j5fz.close();
                    }
                    this.show_jcyl = false;
                    document.getElementById(event.currentTarget.id).classList.remove('qpfd');
                    this.db_click = true;
                    this.echarts_show = false;
                    document.getElementById(item.jcyl_id).value = '0';
                    document.getElementById(item.jcyl_id).style = "color:#a5a5a5";
                    document.getElementById(item.jcyl_id).title = document.getElementById(item.jcyl_id).title.replace('关闭', '开启');
                }
            }
        },
        dj_cp: function (e) {
            this.show_jcyl = false;
            this.echarts_show = false;
            if (e == 1) {
                let arr = [];
                arr.push(this.data_sl[0]);
                this.data_sl = arr;
                this.class_s = 'class_1';
            } else if (e == 4) {
                if (e >= this.data_sl.length) {
                    let lengths = this.data_sl.length;
                    for (let i = lengths; i < 4; i++) {
                        let sss = 'a' + i;
                        let canvass = 'canvas' + i;
                        let canvass_1 = 'canvas_s' + i;
                        let canvass_2 = 'canvas_e' + i;
                        let gzdjs = 'gzdjs' + i;
                        let dxdjs = 'dxdjs' + i;
                        let jcyls = 'jcyls' + i;
                        let sfs = 'sfs' + i;
                        let sxdjs = 'sxdjs' + i;
                        let gzszs = 'gzszs' + i;
                        let bjgzs = 'bjgzs' + i;
                        this.data_sl.push({
                            id: sss,
                            src: '',
                            type: false,
                            canvas_id: canvass,//canvas的id
                            canvas_id_1: canvass_1,//canvas的id
                            canvas_id_2: canvass_2,//canvas的id
                            gzdj_id: gzdjs,//规则叠加的id
                            dxdj_id: dxdjs,//对象叠加的id
                            jcyl_id: jcyls,//交参预览的id
                            sf_id: sfs,//算法的id
                            sxdj_id: sxdjs,//属性叠加的id
                            gzsz_id: gzszs,//规则设置的id
                            bjgz_id: bjgzs,//编辑规则的id
                            name: '',
                            monitor_id: '',
                            video_id: '',
                            div_id: '',
                            js_type: false,
                            canvas_show: false,
                            type_1: false,
                            track_1: false,

                            timeSpeed: 0,
                            timeIntervalSign: null,
                            timeIndex: 0,
                            videoMessage: '',
                            type_bf: false,
                        });
                    }
                } else {
                    let arr = [];
                    this.data_sl.forEach((item, index)=> {
                        if (index < 4) {
                            arr.push(this.data_sl[index]);
                        }
                    });
                    this.data_sl = arr;
                }
                this.class_s = 'class_4';
            } else {
                if (e >= this.data_sl.length) {
                    let lengths = this.data_sl.length;
                    for (let i = lengths; i < 9; i++) {
                        let sss = 'a' + i;
                        let canvass = 'canvas' + i;
                        let canvass_1 = 'canvas_s' + i;
                        let canvass_2 = 'canvas_e' + i;
                        let gzdjs = 'gzdjs' + i;
                        let dxdjs = 'dxdjs' + i;
                        let jcyls = 'jcyls' + i;
                        let sfs = 'sfs' + i;
                        let sxdjs = 'sxdjs' + i;
                        let gzszs = 'gzszs' + i;
                        let bjgzs = 'bjgzs' + i;
                        this.data_sl.push({
                            id: sss,
                            src: '',
                            type: false,
                            canvas_id: canvass,//canvas的id
                            canvas_id_1: canvass_1,//canvas的id
                            canvas_id_2: canvass_2,//canvas的id
                            gzdj_id: gzdjs,//规则叠加的id
                            dxdj_id: dxdjs,//对象叠加的id
                            jcyl_id: jcyls,//交参预览的id
                            sf_id: sfs,//算法的id
                            sxdj_id: sxdjs,//属性叠加的id
                            gzsz_id: gzszs,//规则设置的id
                            bjgz_id: bjgzs,//编辑规则的id
                            name: '',
                            monitor_id: '',
                            video_id: '',
                            div_id: '',
                            js_type: false,
                            canvas_show: false,
                            type_1: false,
                            track_1: false,

                            timeSpeed: 0,
                            timeIntervalSign: null,
                            timeIndex: 0,
                            videoMessage: '',
                            type_bf: false,
                        });
                    }
                } else {
                    // let arr = [];
                    // this.data_sl.forEach((item, index)=> {
                    //     if (index < 9) {
                    //         arr.push(this.data_sl[index]);
                    //     }
                    // });
                    // this.data_sl = arr;
                }
                this.class_s = 'class_9';
            }
            this.num = e;
            let num_sj = -1;
            this.data_sl.forEach((item, index)=> {
                if (item.type) {
                    num_sj++;
                }
            });
            this.index_s = num_sj;
        },
        echatrs_tb: function (id) {
            myChart = echarts.init(document.getElementById("ecs1"));
            myChart1 = echarts.init(document.getElementById("ecs2"));
            myChart2 = echarts.init(document.getElementById("ecs3"));
            myChart3 = echarts.init(document.getElementById("ecs4"));
            myChart.setOption(option);
            myChart1.setOption(option);
            myChart2.setOption(option);
            myChart3.setOption(option);
            let option_1 = {
                title: {text: ''},
                graphic: [{
                    type: 'group',
                    left: 'center',
                    top: '55%',
                    children: [{
                        type: 'text',
                        z: 100,
                        left: '10',
                        top: 'middle',
                        style: {
                            fill: '#fff',
                            text: '近5分钟流量',
                            font: '12px Microsoft YaHei'
                        }
                    }]
                }],
            };
            let option_2 = {
                title: {text: ''},
                graphic: [{
                    type: 'group',
                    left: 'center',
                    top: '55%',
                    children: [{
                        type: 'text',
                        z: 100,
                        left: '10',
                        top: 'middle',
                        style: {
                            fill: '#fff',
                            text: '机动车流量',
                            font: '12px Microsoft YaHei'
                        }
                    }]
                }],
            };
            myChart.setOption(option_1);
            myChart1.setOption(option_2);
            myChart2.setOption(option_1);
            myChart3.setOption(option_2);
            window.addEventListener("resize", function () {
                myChart.resize();
                myChart1.resize();
                myChart2.resize();
                myChart3.resize();
            });
            // let ids = id.slice(0,id.length-1)+(parseInt(id.slice(id.length-1,id.length))-1)+'';
            websocket_s(id);
        },
        //交参预览
        jcyl: function (e, item) {
            if (document.getElementById(item.jcyl_id).value == 1) {
                this.echarts_show = false;
                myChart.dispose();
                myChart1.dispose();
                myChart2.dispose();
                myChart3.dispose();
                ws_j5fz.close();
            } else {
                this.echarts_show = true;
                setTimeout(function () {
                    vue_jkgl.echatrs_tb(item.video_id);
                    arr_sxx.forEach((items)=> {
                        if (items.video_id == item.video_id) {
                            if (items.type == 1) {
                                vue_jkgl.sx_1 = items.sedan;
                                vue_jkgl.sx_2 = items.coach;
                                vue_jkgl.sx_3 = items.goodsvan;
                                vue_jkgl.sx_4 = items.other;

                                let sx_zl_up = items.total;
                                let option1 = {
                                    title: {text: items.fiveflow},
                                };
                                let option2 = {
                                    title: {text: sx_zl_up},
                                };
                                myChart.setOption(option1);
                                myChart1.setOption(option2);
                            } else {
                                vue_jkgl.xx_1 = items.sedan;
                                vue_jkgl.xx_2 = items.coach;
                                vue_jkgl.xx_3 = items.goodsvan;
                                vue_jkgl.xx_4 = items.other;
                                let sx_zl_down = items.total;
                                let option3 = {
                                    title: {text: items.fiveflow},
                                };
                                let option4 = {
                                    title: {text: sx_zl_down},
                                };
                                myChart2.setOption(option3);
                                myChart3.setOption(option4);
                            }
                        }
                    });
                }, 500);
            }
            this.pub_click(e, item);
        },
        //开启规则叠加
        gzdj: function (e, item, index1) {
            if (document.getElementById(item.gzdj_id).value != 1) {
                let arr_ids = item.video_id.slice(0, item.video_id.length - 1) + (parseInt(item.video_id.slice(item.video_id.length - 1, item.video_id.length)) - 1) + '';
                websocket_gzdj(arr_ids, item, index1);
            } else {
                if (vue_jkgl.data_sl[index1].ctx_s != undefined)
                    vue_jkgl.data_sl[index1].ctx_s.clearRect(0, 0, document.getElementById(item.id).offsetWidth, document.getElementById(item.id).offsetHeight);
                if (vue_jkgl.data_sl[index1].websockeds != undefined)
                    vue_jkgl.data_sl[index1].websockeds.close();
            }
            this.pub_click(e, item);
        },
        //开启对象叠加
        dxdj: function (e, item, index) {
            this.pub_click(e, item);
            if (document.getElementById(e.currentTarget.id).value == 1) {
                vue_jkgl.data_sl[index].type_1 = true;
                vue_jkgl.data_sl[index].track_1 = true;
            } else {
                document.getElementById(item.canvas_id_1).height = document.getElementById(item.canvas_id_1).height;
                document.getElementById(item.canvas_id_2).height = document.getElementById(item.canvas_id_2).height;
                vue_jkgl.data_sl[index].type_1 = false;
                vue_jkgl.data_sl[index].track_1 = false;
            }
        },
        //当前按钮变色
        pub_click: function (e, item) {
            if (document.getElementById(e.currentTarget.id).value == 1) {
                document.getElementById(e.currentTarget.id).value = '0';
                document.getElementById(e.currentTarget.id).style = "color:#a5a5a5";
                document.getElementById(e.currentTarget.id).title = document.getElementById(e.currentTarget.id).title.replace('关闭', '开启');
            } else {
                document.getElementById(e.currentTarget.id).title = document.getElementById(e.currentTarget.id).title.replace('开启', '关闭');
                document.getElementById(e.currentTarget.id).style = "color:rgb(0, 87, 218)";
                document.getElementById(e.currentTarget.id).value = '1';
            }
        },

        //删除锁定
        remove: function (item, index) {
            document.getElementById(vue_jkgl.data_sd[index].id).parentNode.parentNode.remove();
            vue_jkgl.data_sd.splice(index, 1);
            if (vue_jkgl.data_sd.length == 0) {
                vue_jkgl.is_bd = false;
            }
            ;
            flv_arr2.forEach((item, indexs)=> {
                if (item.videoID == vue_jkgl.data_sd[index].video_id) {
                    if(item.flv_s){
                        item.flv_s.pause();
                        item.flv_s.unload();
                        item.flv_s.detachMediaElement();
                        item.flv_s.destroy();
                    }
                    flv_arr2.splice(indexs,1);
                }
            });
        },
        //双击锁定全屏
        sj_click_sd: function (e) {
            if (this.is_sfqp) {
                var full = document.getElementById(e.currentTarget.id);
                launchIntoFullscreen(full);
                this.is_sfqp = false;
            } else {
                this.is_sfqp = true;
                exitFullscreen();
            }

        },
        //清除当前播放的所有监控
        qc_span: function () {
            vue_jkgl.data_sl.forEach((item,index)=>{
                if(item.timeIntervalSign){
                    clearTimeout(item.timeIntervalSign);
                    item.timeIntervalSign=null;
                }
                item.type_bf = false;
            });
            flv_arr.forEach((item, index)=> {
                if(item.flv_s){
                    item.flv_s.pause();
                    item.flv_s.unload();
                    item.flv_s.detachMediaElement();
                    item.flv_s.destroy();
                }
            });
            typesss = false;
            flv_arr = [];
            vue_jkgl.data_sl = [];
            vue_jkgl.data_sl.forEach((item, index)=> {
                document.getElementById(item.canvas_id).height = document.getElementById(item.canvas_id).height;
                document.getElementById(item.canvas_id_1).height = document.getElementById(item.canvas_id_1).height;
                document.getElementById(item.canvas_id_2).height = document.getElementById(item.canvas_id_2).height;
            });
            for (let i = 0; i < vue_jkgl.num; i++) {
                let sss = 'a' + i;
                let canvass = 'canvas' + i;
                let canvass_1 = 'canvas_s' + i;
                let canvass_2 = 'canvas_e' + i;
                let gzdjs = 'gzdjs' + i;
                let dxdjs = 'dxdjs' + i;
                let jcyls = 'jcyls' + i;
                let sfs = 'sfs' + i;
                let sxdjs = 'sxdjs' + i;
                let gzszs = 'gzszs' + i;
                let bjgzs = 'bjgzs' + i;
                vue_jkgl.data_sl.push({
                    id: sss,//video标签id
                    src: '',
                    type: false,//判断是否是弹出框的视频播放，false：弹出框播放
                    canvas_id: canvass,//canvas的id
                    canvas_id_1: canvass_1,//canvas的id
                    canvas_id_2: canvass_2,//canvas的id
                    gzdj_id: gzdjs,//规则叠加的id
                    dxdj_id: dxdjs,//对象叠加的id
                    jcyl_id: jcyls,//交参预览的id
                    sf_id: sfs,//算法的id
                    sxdj_id: sxdjs,//属性叠加的id
                    gzsz_id: gzszs,//规则设置的id
                    bjgz_id: bjgzs,//编辑规则的id
                    name: '',//监控的名称
                    monitor_id: '',//监控通过python获取的id
                    video_id: '',//监控的id
                    div_id: '',//div的id和上面的id一样
                    js_type: false,//判断是否存在视频，
                    canvas_show: false,//规则画线的canvas是否显示
                    type_1: false,
                    track_1: false,
                    timeSpeed: 0,
                    timeIntervalSign: null,
                    timeIndex: 0,
                    videoMessage: '',
                    type_bf: false,
                });
            }
            arr_sxx = [];
            vue_jkgl.index_s = -1;
        },

        //重置自动规则--发送数据
        ycczgz: function () {
            if (this.video_is_cz != '') {
                let id = this.video_is_cz;
                let ids = id.slice(0, id.length - 1) + (parseInt(id.slice(id.length - 1, id.length)) - 1) + '';
                $.ajax({
                    url: "/online/changedirection/" + ids,
                    dataType: "text",
                    type: "GET",
                    data: {},
                    success: function (result) {
                        console.log(result);
                    }
                });
            }
        },
    },
    mounted(){
        for (let i = 0; i < 4; i++) {
            let sss = 'a' + i;
            let canvass = 'canvas' + i;
            let canvass_1 = 'canvas_s' + i;
            let canvass_2 = 'canvas_e' + i;
            let gzdjs = 'gzdjs' + i;
            let dxdjs = 'dxdjs' + i;
            let jcyls = 'jcyls' + i;
            let sfs = 'sfs' + i;
            let sxdjs = 'sxdjs' + i;
            let gzszs = 'gzszs' + i;
            let bjgzs = 'bjgzs' + i;
            this.data_sl.push({
                id: sss,//video标签id
                src: '',
                type: false,//判断是否是弹出框的视频播放，false：弹出框播放
                canvas_id: canvass,//canvas的id
                canvas_id_1: canvass_1,//canvas的id
                canvas_id_2: canvass_2,//canvas的id
                gzdj_id: gzdjs,//规则叠加的id
                dxdj_id: dxdjs,//对象叠加的id
                jcyl_id: jcyls,//交参预览的id
                sf_id: sfs,//算法的id
                sxdj_id: sxdjs,//属性叠加的id
                gzsz_id: gzszs,//规则设置的id
                bjgz_id: bjgzs,//编辑规则的id
                name: '',//监控的名称
                monitor_id: '',//监控通过python获取的id
                video_id: '',//监控的id
                div_id: '',//div的id和上面的id一样
                js_type: false,//判断是否存在视频，
                canvas_show: false,//规则画线的canvas是否显示
                type_1: false,
                track_1: false,

                timeSpeed: 0,
                timeIntervalSign: null,
                timeIndex: 0,
                videoMessage: '',
                type_bf: false,
            });
        }
        ;
    },
});

//模态框 检测规则配置
let vue_model = new Vue({
    el: '#myModal',
    data: {
        pzx: [],
        tim: '',
    },
    methods: {
        remove: function (item, index) {
            this.pzx.splice(index, 1);
        },
        add_cut: function (e) {
            if (e) {
                this.tim--;
            } else {
                this.tim++;
            }
        }
    }
});

//新的模态框,三等级模态框
let vue_sjsstx = new Vue({
    el: '#myModal_sj',
    data: {
        yjsj_data: [],
        ejsj_data: [],
        sjsj_data: [],
        index: 0,
    },
    methods: {
        djxx_modal: function (item) {
            vue_sjsstx_li.data_wfsp = [];
            vue_sjsstx_li.data_wfsp = item.src;
            vue_sjsstx_li.data_sj = {
                lx: item.sjlx,
                bjsj: item.bjsj,
                dwmc: item.dwmc,
            };
            vue_sjsstx_li.arrs = {
                timeSpeed: 0,
                timeIntervalSign: null,
                timeIndex: 0,
                videoMessage: '',
            };
            monitor_sx(item.videoid, 'my_video_1', vue_sjsstx_li.arrs, 2);
            $("#myModal_li").modal('show');
        },
        cli_input: function (item, e, indexs, a) {
            this.index++;
            vue_jkgl.is_bd = true;
            let iscz = false;
            vue_jkgl.data_sd.forEach((items, index)=> {
                if (items.video_id == item.videoid) {
                    iscz = true;
                }
            });
            if (e.currentTarget.checked) {
                if (iscz) {
                    e.currentTarget.checked = false;
                    info_new("此监控已在右侧展现，同一监控不可再次添加");
                    window.setTimeout("$('#info-warning-new').modal('hide')", 2000);
                } else {
                    if (a == 1) {
                        vue_sjsstx.yjsj_data[indexs].checked = true;
                    } else if (a == 2) {
                        vue_sjsstx.ejsj_data[indexs].checked = true;
                    } else {
                        vue_sjsstx.sjsj_data[indexs].checked = true;
                    }
                    let ids = 'bd_' + (this.index);
                    vue_jkgl.data_sd.push({
                        name: item.dwmc,
                        id: ids,
                        video_id: item.videoid,
                        timeSpeed: 0,
                        timeIntervalSign: null,
                        timeIndex: 0,
                        videoMessage: '',
                    });
                    monitor_sx(item.videoid, ids, vue_jkgl.data_sd[vue_jkgl.data_sd.length-1], 3);
                }
            } else {
                if (a == 1) {
                    vue_sjsstx.yjsj_data[indexs].checked = false;
                } else if (a == 2) {
                    vue_sjsstx.ejsj_data[indexs].checked = false;
                } else {
                    vue_sjsstx.sjsj_data[indexs].checked = false;
                }
                document.getElementById(vue_jkgl.data_sd[indexs].id).parentNode.parentNode.remove();
                vue_jkgl.data_sd.forEach((items, index)=> {
                    if (items.video_id == item.videoid) {
                        vue_jkgl.data_sd.splice(index, 1);
                    }
                });
                if (vue_jkgl.data_sd.length == 0) {
                    vue_jkgl.is_bd = false;
                }
            }

        },
        state_cli: function (item, e, index, type) {
            let json_s = [];
            json_s.push({
                recordid: item.recordid + '',
                channelid: item.channelid,
                fdid: item.fdid,
                recordtime: item.recordtime,
                recordtype: item.recordtype.toLowerCase(),
                processstatus: e
            });
            $.ajax({
                url: "/TrafficStatistics/updateTraffalarmrecordById",
                dateType: 'json',
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify(json_s),
                success: function (result) {
                    if (result.code == 0) {
                        info_new("处理成功");
                        window.setTimeout("$('#info-warning-new').modal('hide')", 2000);
                        if (type == 1) {
                            vue_sjsstx.yjsj_data[index].ss_type = e;
                        } else if (type == 2) {
                            vue_sjsstx.ejsj_data[index].ss_type = e;
                        } else {
                            vue_sjsstx.sjsj_data[index].ss_type = e;
                        }
                    }
                }
            });
        }
    },
    mounted(){

    }
});

//老的模态框
let vue_sjsstx_li = new Vue({
    el: '#myModal_li',
    data: {
        data_wfsp: [],
        data_sj: {
            lx: '',
            bjsj: '',
            dwmc: ''
        },
        class_s: 'class_1s',
        class_s1: 'class_2s',
        shows: true,
        src_img: '',
        arrs: {
            timeSpeed: 0,
            timeIntervalSign: null,
            timeIndex: 0,
            videoMessage: '',
        },
    },
    methods: {
        sp_qh: function (e) {
            if (e == 1) {
                this.class_s = 'class_1s';
                this.class_s1 = 'class_2s';
                this.shows = true;
            } else {
                this.class_s = 'class_2s';
                this.class_s1 = 'class_1s';
                this.shows = false;
            }
            this.src_img = this.data_wfsp[0].img_src;
        },
        click_img_bf: function (src) {
            this.src_img = src;
        },
    },
    mounted(){
    }
});

//生成树形结构数据
function toTree(list, parId) {
    let len = list.length;

    function loop(parId) {
        let res = [];
        for (let i = 0; i < len; i++) {
            let item = list[i];
            if (item.parentId === parId) {
                item.nodes = loop(item.href);
                let arr = {
                    href: item.href,
                    text: item.text,
                    level: item.level,
                    parentId: item.parentId,
                }
                if (item.level == 0 || item.level == 1 || item.level == 2) {
                    arr.selectable = false;
                    arr.state = {expanded: true};
                } else {
                    arr.state = {expanded: false};
                    arr.selectable = true;
                    arr.icon = 'glyphicon glyphicon-facetime-video zx';
                    if (item.vels != null && item.vels > 0) {
                        arr.color = '#1ab4e2';
                    }
                }
                if (item.nodes.length > 0) {
                    arr.nodes = item.nodes;
                }
                res.push(arr);
            }
        }
        return res
    }

    return loop(parId)
}

//查询监控对应的属性(访问Python里面默认的库存放的值)
function monitor_sx(video_id, div_id, arrs, types) {
    //若监控与之前的相同,去除之前的flvPlayer
    // flv_arr.forEach((item, index)=> {
    //     if (item.videoID == video_id) {
    //         if(item.flv_s){
    //             item.flv_s.destroy();
    //         }
    //     }
    // });
    $.ajax({
        url: "/getflv/" + video_id,
        dataType: "text",
        type: "GET",
        data: {},
        success: function (result) {
            if (result != "") {
                stop(types,video_id);
                monitor_bf_cs(result.replace("0.0.0.0", "33.50.1.21"), div_id, video_id, arrs, types);
            } else {
                // console.log('没有对应的flv视频地址:   监控ID为：' + video_id);
                arrs.videoMessage = '没有对应的flv视频地址\n监控ID为：' + video_id;
            }
        },
    });
}

let decTimes = [1, 3, 5, 8, 10, 20];
//监控播放
function monitor_bf_cs(http_rest, div_id, video_id, arrs, types) {
    if(arrs.type_bf)
    if (flvjs.isSupported()) {
        let videoElement = document.getElementById(div_id);
        let flvPlayer = flvjs.createPlayer(
            {type: 'flv', url: http_rest, isLive: true, duration: 0},
            {
                isLive: true, enableStashBuffer: false, lazyLoad: false,
                lazyLoadMaxDuration: 0,
                lazyLoadRecoverDuration: 0,
                deferLoadAfterSourceOpen: false,
                fixAudioTimestampGap: false,
            },
        );
        if (types == 1) {
            flv_arr.forEach((item, index)=> {
                if (item.videoID == video_id) {
                    if (item.flv_s) {
                        item.flv_s.pause();
                        item.flv_s.unload();
                        item.flv_s.detachMediaElement();
                        item.flv_s.destroy();
                    }
                    flv_arr.splice(index,1);
                }
            });
            flv_arr.push({flv_s: flvPlayer, videoID: video_id});
        } else if (types == 2) {
            flv_arr1.forEach((item, index)=> {
                if (item.videoID == video_id) {
                    if (item.flv_s) {
                        item.flv_s.pause();
                        item.flv_s.unload();
                        item.flv_s.detachMediaElement();
                        item.flv_s.destroy();
                    }
                    flv_arr1.splice(index,1);
                }
            });
            flv_arr1.push({flv_s: flvPlayer, videoID: video_id});
        } else {
            flv_arr2.forEach((item, index)=> {
                if (item.videoID == video_id) {
                    if (item.flv_s) {
                        item.flv_s.pause();
                        item.flv_s.unload();
                        item.flv_s.detachMediaElement();
                        item.flv_s.destroy();
                    }
                    flv_arr2.splice(index,1);
                }
            });
            flv_arr2.push({flv_s: flvPlayer, videoID: video_id});
        }
        flvPlayer.on(flvjs.Events.STATISTICS_INFO, function (message) {
            emitMessage(http_rest, div_id, video_id, arrs,types,message);
        });
        // flvPlayer.on(flvjs.Events.ERROR, e => {
        //     flvPlayer.unload();
        //     flvPlayer.load();
        //     flvPlayer.play();
        //     console.log(e);
        // });
        flvPlayer.attachMediaElement(videoElement);
        flvPlayer.load();
        flvPlayer.play();
    }
}
function emitMessage(http_rest, div_id, video_id, arrs,types,message) {
    let {decodedFrames, speed} = message;
    arrs.timeSpeed = speed;
    if (arrs.timeSpeed === 0) {
        if (arrs.timeIntervalSign) return;
        timeInterval(http_rest, div_id, video_id, arrs,types);
    } else {
        if (arrs.timeIntervalSign) {
            clearTimeout(arrs.timeIntervalSign);
            arrs.timeIntervalSign = null;
        }
        arrs.timeIndex = 0;
        arrs.videoMessage = '';
    }
}
function timeInterval(http_rest, div_id, video_id, arrs,types) {
    if (!decTimes[arrs.timeIndex]) {
        console.log('长时间未连接！已关闭！');
        arrs.videoMessage = '长时间未连接！已关闭！';
        clearTimeout(arrs.timeIntervalSign);
        arrs.timeIntervalSign = null;
        arrs.timeIndex = 0;
        stop(types,video_id);
        return;
    }
    console.log(`视频播放异常，${decTimes[arrs.timeIndex]}秒后重连！`);
    arrs.videoMessage = `视频播放异常，${decTimes[arrs.timeIndex]}秒后重连...`;
    arrs.timeIntervalSign = setTimeout(() => {
        monitor_bf_cs(http_rest, div_id, video_id, arrs,types);
        arrs.timeIntervalSign = null;
        clearTimeout(arrs.timeIntervalSign);
        // timeInterval(http_rest, div_id, video_id, arrs,types);
    }, decTimes[arrs.timeIndex++] * 1000);
}

function stop(types,video_id) {
    if(types==1){
        flv_arr.forEach((item, index)=> {
            if (item.videoID == video_id) {
                if (item.flv_s) {
                    item.flv_s.pause();
                    item.flv_s.unload();
                    item.flv_s.detachMediaElement();
                    item.flv_s.destroy();
                }
                item.flv_s = null;
            }
        });
    }else if(types==2){
        flv_arr1.forEach((item, index)=> {
            if (item.videoID == video_id) {
                if (item.flv_s) {
                    item.flv_s.pause();
                    item.flv_s.unload();
                    item.flv_s.detachMediaElement();
                    item.flv_s.destroy();
                }
                item.flv_s = null;
            }
        });
    }else{
        flv_arr2.forEach((item, index)=> {
            if (item.videoID == video_id) {
                if (item.flv_s) {
                    item.flv_s.pause();
                    item.flv_s.unload();
                    item.flv_s.detachMediaElement();
                    item.flv_s.destroy();
                }
                item.flv_s = null;
            }
        });
    }
}

//临时存储传过来的事件的值（当弹框存在时，后面的事件的值临时存放）
let arr_right_s = [];

//websocket连接
let d = new Date().getTime();
let web_ip = "ws:/33.50.1.22:8089/websocket/" + d;
let wss = new WebSocket(web_ip);
wss.onopen = function () {
    console.log("连接成功");
    // var from = {"serialNo": "xxx", "idNo": "xxx"};
    // wss[i].send(JSON.stringify(from));//发送参数
};
wss.onmessage = function (evt) {
    var data = JSON.parse(event.data);
    // console.log(data);
    if (data.type == "alarm") {

        if (data.data.incident_type == 'ROADWORKS' || data.data.incident_type == 'ROADWORKS_OUT_OF_LINE') {
            //排除工程检测
            return;
        }
        //if_cz 判断前来的事件是不是本部门下的
        let if_cz = false;
        //jk_video_id为监控id
        // let a_id = data.data.video_id.slice(0, data.data.video_id.length - 1) + (parseInt(data.data.video_id.slice(data.data.video_id.length - 1, data.data.video_id.length)) + 1) + '';
        let jk_video_id = data.data.video_id;
        // let jk_video_id = data.data.video_id;
        vue_tree.jk_s.forEach((item, index) = > {
            if(item.VIDOID == jk_video_id
    )
        {
            if_cz = true;
        }
    })
        ;
        let a_s = false;
        vue_jkgl.data_sd.forEach((item, index) = > {
            if(item.video_id == jk_video_id
    )
        {
            a_s = true;
        }
    })
        ;
        if (a_s) {
            return;
        }
        if (if_cz) {
            //事件id
            let sjid = data.recordid;
            //报警时间
            let sj = (new Date(parseInt(data.data.ts))).Format("yyyy-MM-dd hh:mm:ss");
            //事件类型
            let bjlx = '';
            //事件等级
            let sjdj = '';
            vue_tree.cllx.forEach((item, index) = > {
                if(item.id == data.data.incident_type
        )
            {
                bjlx = item.name;
                sjdj = item.alarmlevel;
            }
        })
            ;

            //监控名称
            let jkmc = '';
            vue_tree.jk_arr.forEach((item, index) = > {
                if(item.href == jk_video_id
        )
            {
                jkmc = item.text;
            }
        })
            ;
            //违法图片
            let wfsp = [];
            data.data.img_base64.forEach((item, index) = > {
                let src = 'data:image/jpg;base64,' + item;
            wfsp.push({img_src: src});
        })
            ;
            //右边消息弹出框的id
            let tss = 'a' + data.data.ts;
            //判断三级弹出框是否已经弹出，没有弹出，则清空，若是弹出，则继续push
            if ($("#myModal_sj")[0].style.display != 'block') {
                $(".carousel").collapse();
                vue_sjsstx.yjsj_data = [];
                vue_sjsstx.ejsj_data = [];
                vue_sjsstx.sjsj_data = [];
                $("#myModal_sj").modal("show");

                $("#myModal_sj").find('input').each(function () {
                    $(this).removeAttr("checked", false);
                    $(this).prop("checked", false);
                });
            }
            if (sjdj == '1') {
                $("#a1s").collapse();
                vue_sjsstx.yjsj_data.unshift({
                    src: wfsp,
                    videoid: jk_video_id,
                    dwmc: jkmc,
                    sjlx: bjlx,
                    bjsj: sj,
                    checked: false,
                    recordid: sjid,
                    channelid: jk_video_id.slice(jk_video_id.length - 1),
                    fdid: jk_video_id.slice(0, jk_video_id.length - 2),
                    recordtime: sj,
                    recordtype: data.data.incident_type,
                    ss_type: '',
                });
                setTimeout(function () {
                    $("#a1s .carousel-indicators li").removeClass("active");
                    $("#a1s .carousel-inner > div").removeClass("active");
                    $("#a1s .carousel-indicators li:first-child").addClass("active");
                    $("#a1s .carousel-inner > div:first-child").addClass("active");

                    // #点击轮播图下方小圆点可以改变轮播图片
                    $("#a1s li").click(function () {
                        var index = $(this).attr("data-slide-to");
                        $('#a1s').carousel(parseInt(index))
                    });
                    $('#a1s').carousel({
                        interval: 3000,
                    });
                }, 500);
            } else if (sjdj == '2') {
                $("#a2s").collapse();
                vue_sjsstx.ejsj_data.unshift({
                    src: wfsp,
                    videoid: jk_video_id,
                    dwmc: jkmc,
                    sjlx: bjlx,
                    bjsj: sj,
                    checked: false,
                    recordid: sjid,
                    channelid: jk_video_id.slice(jk_video_id.length - 1),
                    fdid: jk_video_id.slice(0, jk_video_id.length - 2),
                    recordtime: sj,
                    recordtype: data.data.incident_type,
                    ss_type: '',
                });
                setTimeout(function () {
                    $("#a2s .carousel-indicators li").removeClass("active");
                    $("#a2s .carousel-inner > div").removeClass("active");
                    $("#a2s .carousel-indicators li:first-child").addClass("active");
                    $("#a2s .carousel-inner > div:first-child").addClass("active");

                    // #点击轮播图下方小圆点可以改变轮播图片
                    $("#a2s li").click(function () {
                        var index = $(this).attr("data-slide-to");
                        $('#a2s').carousel(parseInt(index))
                    });
                    $('#a2s').carousel({
                        interval: 3000,
                    });
                }, 500);

            } else if (sjdj == '3') {
                $("#a3s").collapse();
                vue_sjsstx.sjsj_data.unshift({
                    src: wfsp,
                    videoid: jk_video_id,
                    dwmc: jkmc,
                    sjlx: bjlx,
                    bjsj: sj,
                    checked: false,
                    recordid: sjid,
                    channelid: jk_video_id.slice(jk_video_id.length - 1),
                    fdid: jk_video_id.slice(0, jk_video_id.length - 2),
                    recordtime: sj,
                    recordtype: data.data.incident_type,
                    ss_type: '',
                });
                setTimeout(function () {
                    $("#a3s .carousel-indicators li").removeClass("active");
                    $("#a3s .carousel-inner > div").removeClass("active");
                    $("#a3s .carousel-indicators li:first-child").addClass("active");
                    $("#a3s .carousel-inner > div:first-child").addClass("active");
                    // #点击轮播图下方小圆点可以改变轮播图片
                    $("#a3s li").click(function () {
                        var index = $(this).attr("data-slide-to");
                        $('#a3s').carousel(parseInt(index))
                    });
                    $('#a3s').carousel({
                        interval: 3000,
                    });
                }, 500);
            }
            new NoticeJs({
                text: 'Notification message',
                position: 'bottomRight',
                // id: tss,
                id: 11,
                sjlx: bjlx,
                dwmc: jkmc,
                animation: {
                    open: 'animated bounceIn',
                    close: 'animated bounceOut'
                }
            }).show();
            //播放声音
            let myMp3 = document.getElementById("audio");
            audio.play();
        }
    }
};

//点击右边消息提示框查看事件（此事件在../js/notice.js里面调用）目前不调用
// function ck_sj(id) {
//     setTimeout(function () {
//         var thisNode = document.getElementById(id);
//         thisNode.parentElement.removeChild(thisNode);
//         let arr = {};
//         arr_right_s.forEach((item, index)=> {
//             if (item.id == id) {
//                 arr = item;
//             }
//         });
//         vue_sjsstx_li.data_wfsp = [];
//         vue_sjsstx_li.data_wfsp = arr.wfsp;
//         vue_sjsstx_li.data_sj = {
//             lx: arr.bjlx,
//             bjsj: arr.sj,
//             dwmc: arr.jkmc,
//         };
//         vue_sjsstx_li.src_img = vue_sjsstx_li.data_wfsp[0].img_src;
//         monitor_sx(arr.videoid, 'my_video_1', 1);
//         // jsq_s1(arr.videoid);
//         $("#myModal_li").modal("show");
//     }, 200);
// }

//监听myModal_li隐藏事件
$('#myModal_li').on('hidden.bs.modal', function () {
    flv_arr1.forEach((item, index)=> {
        if(item.flv_s){
            item.flv_s.pause();
            item.flv_s.unload();
            item.flv_s.detachMediaElement();
            item.flv_s.destroy();
        }
        flv_arr1.splice(index,1);
    });
    flv_arr1 = [];
});

//放大缩小图片
$('[data-gallery=manual]').click(function (e) {

    e.preventDefault();

    var items = [],
        options = {
            index: $(this).index()
        };

    $('[data-gallery=manual]').each(function () {
        items.push({
            src: $(this).attr('src'),
            title: '图片查看'
        });
    });
    new PhotoViewer(items, options);
});

//打开或关闭推送
$('[name="status"]').bootstrapSwitch({
    onText: "打开",
    offText: "关闭",
    onColor: "success",
    offColor: "warning",
    onSwitchChange: function (event, state) {
        if (state == true) {
            state_sj = true;
            console.log('已打开');
        } else {
            state_sj = false;
            console.log('已关闭');
        }
    }
});

//推送近5分钟数据
function websocket_s(ds) {
    let web_ips = "ws:/33.50.1.22:8089/websocket/" + ds;
    ws_j5fz = new WebSocket(web_ips);
    ws_j5fz.onopen = function () {
        console.log("连接成功");
        // var from = {"serialNo": "xxx", "idNo": "xxx"};
        ws_j5fz.send("videoid");//发送参数
    };
    ws_j5fz.onmessage = function (evt) {
        if (evt.data != 'videoid') {
            var data = JSON.parse(evt.data);
            if (data.type == "rule") {
                return;
            }
            // vue_sjcx.j5fzll = data.FIVEFLOW;
            // vue_sjcx.j5fzll_tb = data.TBFIVEFLOW;
            // vue_sjcx.j5fzll_hb = data.HBFIVEFLOW;
            vue_jkgl.sx_1 = data[4].SEDAN;
            vue_jkgl.sx_2 = data[4].COACH;
            vue_jkgl.sx_3 = data[4].GOODSVAN;
            vue_jkgl.sx_4 = data[4].OTHER;

            vue_jkgl.xx_1 = data[5].SEDAN;
            vue_jkgl.xx_2 = data[5].COACH;
            vue_jkgl.xx_3 = data[5].GOODSVAN;
            vue_jkgl.xx_4 = data[5].OTHER;

            let sx_zl_up = data[1].DAYFLOW;
            let sx_zl_down = data[2].DAYFLOW;
            let option1 = {
                title: {text: data[1].FIVEFLOW},
            };
            let option2 = {
                title: {text: sx_zl_up},
            };
            let option3 = {
                title: {text: data[2].FIVEFLOW},
            };
            let option4 = {
                title: {text: sx_zl_down},
            };
            myChart.setOption(option1);
            myChart1.setOption(option2);
            myChart2.setOption(option3);
            myChart3.setOption(option4);
        }
    };
}

//推送自动规则
function websocket_gzdj(video_id, items, indexs_1) {
    let web_ips = "ws:/33.50.1.22:8089/websocket/" + video_id;
    let ws_gzdj = new WebSocket(web_ips);
    ws_gzdj.onopen = function () {
        console.log("连接成功");
        // var from = {"serialNo": "xxx", "idNo": "xxx"};
    };
    ws_gzdj.onmessage = function (evt) {
        var data = JSON.parse(evt.data);
        if (data.type != "rule") {
            return;
        }
        if (data.data.rule_area != undefined) {
            let c = document.getElementById(items.canvas_id);//初始化;
            c.width = document.getElementById(items.id).offsetWidth;
            c.height = document.getElementById(items.id).offsetHeight;
            let width = c.offsetWidth;
            let height = c.offsetHeight;
            let ctx = c.getContext("2d");
            ctx.strokeStyle = "#33fd00";
            ctx.setLineDash([5, 10]);
            ctx.lineWidth = 2;
            ctx.beginPath();
            let arr = data.data.rule_area[0].vertexes;
            ctx.clearRect(0, 0, width, height);
            vue_jkgl.data_sl[indexs_1].websockeds = ws_gzdj;
            arr.forEach((item, index)=> {
                if (index == 0) {
                    ctx.moveTo(item.x * width, item.y * height);
                } else if (index == arr.length - 1) {
                    ctx.lineTo(arr[0].x * width, arr[0].y * height);
                } else {
                    ctx.lineTo(item.x * width, item.y * height);
                }
            });
            ctx.stroke();
            vue_jkgl.data_sl[indexs_1].ctx_s = ctx;
            vue_jkgl.data_sl[indexs_1].canvas_show = true;
        }
    };
}

//默认5分钟数据查询
function j5fz_jczssj(id) {

    $.ajax({
        url: "/TrafficStatistics/list/vehiclesByVideoIdAndType",
        dataType: "json",
        type: "get",
        data: {
            pageNum: 1,
            pageSize: 10,
            deptid: getCookie("bjpt_deptId") == '-1' ? '' : getCookie("bjpt_deptId"),
            videoname: '',
            starttime: getTime().kssj,
            endtime: getTime().jssj,
            ruletag: '1',
            videoid: id,
        },
        success: function (result) {
            let arrs = {
                video_id: id,
                total: 0,
                sedan: 0,
                coach: 0,
                goodsvan: 0,
                other: 0,
                fiveflow: 0,
                type: 1,
            };
            if (result.code == 0) {
                if (result.data.length > 0) {
                    arrs = {
                        total: result.data[0].total,
                        sedan: result.data[0].sedan,
                        coach: result.data[0].coach,
                        goodsvan: result.data[0].goodsvan,
                        other: result.data[0].other,
                        fiveflow: result.data[0].fiveflow,
                    };
                    arr_sxx.push(arrs);
                }
            }
        }
    });
    $.ajax({
        url: "/TrafficStatistics/list/vehiclesByVideoIdAndType",
        dataType: "json",
        type: "get",
        data: {
            pageNum: 1,
            pageSize: 10,
            deptid: getCookie("bjpt_deptId") == '-1' ? '' : getCookie("bjpt_deptId"),
            videoname: '',
            starttime: getTime().kssj,
            endtime: getTime().jssj,
            ruletag: '2',
            videoid: id,
        },
        success: function (result) {
            let arrs = {
                video_id: id,
                total: 0,
                sedan: 0,
                coach: 0,
                goodsvan: 0,
                other: 0,
                fiveflow: 0,
                type: 2,
            };
            if (result.code == 0) {
                if (result.data.length > 0) {
                    arrs = {
                        total: result.data[0].total,
                        sedan: result.data[0].sedan,
                        coach: result.data[0].coach,
                        goodsvan: result.data[0].goodsvan,
                        other: result.data[0].other,
                        fiveflow: result.data[0].fiveflow,
                    };
                    arr_sxx.push(arrs);
                }
            }
        }
    });
}

//车辆画框
function dxdj_fun(id, video_id, canvas_1, canvas_2, index_s) {
    let names = '';
    let ss = true;
    //判断是不是那6个固定的监控，是的话，就画框，否则不画框
    video_arr_id.forEach((item, index)=> {
        if (item.id == video_id) {
            names = item.name;
            ss = false;
        }
    });
    if (ss) {
        return;
    }
    const localResourceUrl = './public/2020-12-24/';
    // 控制开关
    // let status = {
    //     type: true,
    //     track: true,
    // };
    const typeMap = {
        SEDAN: '轿车',
        MINIBUS: '面包车',
        SUV_MPV: 'SUV/MPV',
        MEDIUM_COACH: '中型客车',
        COACH: '大型客车',
        TRUCK: '工程车',
        HEAVY_GOODS_VAN: '中重型货车',
        LIGHT_GOODS_VAN: '轻型货车',
        TRAILER: '拖挂车',
        TRICYCLE: '三轮车',
        CART: '二轮车',
        PEDESTRIAN: '行人',
    }
    const mseVideo = new MseVideo(document.getElementById(id));
    const videoCanvas = new Canvas(document.getElementById(canvas_1));
    const videoCanvas2 = new Canvas(document.getElementById(canvas_2));


    mseVideo.on('draw', (objects, drawTraj) => {
        if (!vue_jkgl.data_sl[index_s].type_1 && !vue_jkgl.data_sl[index_s].track_1) return;
        if (vue_jkgl.data_sl[index_s].type_1) {
            videoCanvas.clearCanvas();
        }
        if (drawTraj && vue_jkgl.data_sl[index_s].track_1) {
            videoCanvas2.clearCanvas();
        }
        objects.forEach(({loc, type, traj}) => {
            const {x, y, width, height} = loc;
            if (vue_jkgl.data_sl[index_s].type_1) {
                videoCanvas.drawItem({
                    name: type,
                    label: typeMap[type.toUpperCase()] || type,
                    dataType: 'relative',
                    data: [x, y, width, height],
                    color: 'red',
                })
            }
            if (drawTraj && vue_jkgl.data_sl[index_s].track_1) {
                videoCanvas2.drawLine(traj);
            }
        });
    })
    // 异步接口
    const API = {
        async proxy(method, url, options) {
            try {
                const result = await axios({
                    method,
                    url,
                    ...options
                });
                if (result && result.status === 200) {
                    return result.data;
                }
            } catch (error) {
                window.console.log(`${url}请求发生异常！`, error);
            }
        },

        async getArrayBufferVideo(url) {
            return this.proxy('get', url, {
                responseType: 'arraybuffer'
            });
        },

        async getJson(url) {
            return this.proxy('get', url);
        },
    }

    async function getFile() {
        const res = await axios.get(localResourceUrl);
        return res.status === 200 ? res.data.filter(filename => filename.endsWith('mp4')) : [];
    }

    async function appendUnit(unitName) {
        return new Promise(async(reslove, reject) => {
            if (mseVideo) {
                const videoBuf = await API.getArrayBufferVideo(unitName + '.mp4');
                const videoJSON = await API.getJson(unitName + '.json');
                let dataMap = new Map();
                (videoJSON).forEach(({
                    ts,
                    objects
                }) => dataMap.set(ts, objects.filter((o) => o.type !== 'unknown_vehicle')));
                mseVideo.append(unitName + '.mp4', videoBuf, dataMap);

                reslove(true);
            }
        })
    }


    // 入口
    async function main() {
        // const files = await getFile();

        // const hasNewFiles = (newThree) => {
        //     newThree.forEach(item => {
        //         appendUnit(item.split('.')[0])
        //     })
        // }
        // 这里模拟从服务器定时获取数据
        let fileListSet = new Set();
        const getFileSign = setInterval(() => {
            if(typesss){
                $.ajax({
                    // url: "/getjson/" + vue_jkgl.data_sl[index].video_id,
                    url: "/getjson/" + names,
                    dataType: "text",
                    type: "GET",
                    data: {},
                    success: function (result) {
                        if (result != '' || result != null) {
                            result = result.replace(".mp4", "").replace(".json", "");
                            if (!fileListSet.has(result)) {
                                fileListSet.add(result);
                                appendUnit(result);
                            }
                            if (fileListSet.size > 10) {
                                fileListSet = new Set(Array.from(fileListSet).slice(-10));
                            }
                        }
                    },
                });
            }else{
                clearTimeout(getFileSign);
            }
        }, 2000);
    }

    main();
}
