let vue_sjcx = new Vue({
    el: '#sjcx',
    data: {
        searchText: '',
        show: true,
        data_sjlxs: [],
        data_table_wfpz: [],
        num: 0,
        num1: 1000,
        offset:30,
        sjlx: '',
        data_sjlxs1: [],
        count: '',
        deptId: getCookie("bjpt_deptId"),
        fy_select: 20,
        gd_span: '',
        show_nums: false,
        state_arr: [],
        cllx_select: [],
        clzt_select: [],
        arr_cllx: [],
        jk_s:[],
        check_s:false,
    },
    methods: {
        fastSearch: function () {
            this.xzml();
        },
        xzml: 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_sjcx.searchText,
                            },
                            success: function (result) {
                                let defaultData = [];
                                if (result.code == 0) {
                                    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: '#ff000000',
                                        selectedColor: '#368ff3',
                                        onhoverColor: '#73a5ff26',
                                        showBorder: false,
                                        data: defaultData,
                                        multiSelect: false,
                                        level: 2,
                                        showCheckbox: 1,//复选框设置，也可以是true
                                        onNodeChecked: function (event, node) { //选中节点
                                            let selectNodes = getChildNodeIdArr(node); //获取所有子节点
                                            if (selectNodes) { //子节点不为空，则选中所有子节点
                                                $(this).treeview('checkNode', [selectNodes, {silent: true}]);
                                            }
                                            //如果当前节点的子节点都被选中了。则父节点也应该要选中
                                            setParentNodeCheck(node);
                                        }, onNodeUnchecked: function (event, node) { //取消选中节点
                                            let selectNodes = getChildNodeIdArr(node); //获取所有子节点
                                            if (selectNodes) { //子节点不为空，则取消选中所有子节点
                                                $(this).treeview('uncheckNode', [selectNodes, {silent: true}]);
                                            }
                                        }, onNodeExpanded: function (event, data) {

                                        }, onNodeSelected: function (event, node) {

                                        }

                                    });
                                    vue_sjcx.query(1, true);
                                }
                            }
                        });
                    }
                }
            });
        },
        qh_tab: function (el) {
            if (el == 1) {
                this.show = false;
            } else {
                this.show = true;
            }
        },
        //事件类型切换
        change: function (item, index) {
            this.num = index;
            this.num1 = 1000;
            this.sjlx = item.id;
            this.gd_span = '';
            vue_sjcx.query(1, true);
        },
        //事件类型切换
        change_gd: function (item, index) {
            this.num = 5;
            this.sjlx = item.id;
            this.num1 = index;
            this.gd_span = item.name;
            vue_sjcx.query(1, true);
        },
        //详情
        xq: function (item) {
            vue_sjsstx.video_src = '';
            vue_sjsstx.data_sj = item;
            vue_sjsstx.class_s = 'class_1';
            vue_sjsstx.class_s1 = 'class_2';
            vue_sjsstx.show_s = false;
            vue_sjsstx.img_src_s = '';
            vue_sjsstx.data_wfsp = [];
            if (item.img1path != null) {
                vue_sjsstx.img_src_s = '/TrafficStatistics/fielagent?ftpPath=' + item.img1path;
                vue_sjsstx.data_wfsp.push({src: '/TrafficStatistics/fielagent?ftpPath=' + item.img1path});
            }
            if (item.img2path != null) {
                vue_sjsstx.data_wfsp.push({src: '/TrafficStatistics/fielagent?ftpPath=' + item.img2path});
            }
            if (item.img3path != null) {
                vue_sjsstx.data_wfsp.push({src: '/TrafficStatistics/fielagent?ftpPath=' + item.img3path});
            }
            if (item.img4path != null) {
                vue_sjsstx.data_wfsp.push({src: '/TrafficStatistics/fielagent?ftpPath=' + item.img4path});
            }
            if (item.img5path != null) {
                vue_sjsstx.data_wfsp.push({src: '/TrafficStatistics/fielagent?ftpPath=' + item.img5path});
            }
            $("#myModal").modal("show");
        },
        query: function (pages, items) {
            let nodes = $('#tree-xzxq').treeview('getChecked').filter(n=>n.level == null).map(n=> {
                return n.href
            });
            let arr_nodes = "";
            if (nodes.length == 0) {
                nodes = "";
            } else {
                nodes.forEach((item, index)=> {
                    arr_nodes = arr_nodes + item + ',';
                });
            }
            if ($('#tree-xzxq').treeview('getChecked').length > 0 && nodes.length == 0) {
                arr_nodes = "null";
            };
            $(".div-ul").find('input').each(function () {
                $(this).removeAttr("checked", false);
                $(this).prop("checked", false);
            });
            this.show_nums = false;
            // arr_nodes = arr_nodes.substring(0,arr_nodes.length -1);
            let starttime = $("#kssj").val().substr(0, 19);
            let endtime = $("#kssj").val().substr(22, 19);
            let li = this.fy_select;
            let type = this.sjlx.toLowerCase();

            let objlabels = "";
            if (this.cllx_select.length == 0) {
                objlabels = "";
            } else {
                this.cllx_select.forEach((item, index)=> {
                    objlabels = objlabels + item + ',';
                });
            }
            ;
            let processstatus = "";
            if (this.clzt_select.length == 0) {
                processstatus = "";
            } else {
                this.clzt_select.forEach((item, index)=> {
                    processstatus = processstatus + item + ',';
                });
            }
            ;
            let json_s = {
                videoids: arr_nodes,
                page: pages,
                limit: li,
                recordtype: type,
                checkstatus: "",
                starttime: starttime,
                endtime: endtime,
                deptid: getCookie("bjpt_deptId"),
                construction: '2',
                objlabel: objlabels,
                processstatus: processstatus,
                rectificationtype:'',
            };
            $.ajax({
                url: "/TrafficStatistics/queryTraffalarmrecordByPage/0",
                dateType: 'json',
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify(json_s),
                success: function (result) {
                    // 拼接div





                    // vue_sjcx.data_table_wfpz = [];
                    // if (result.code == 0) {
                    //     let a_sum = result.count;
                    //     vue_sjcx.count = result.count;
                    //     vue_sjcx.data_table_wfpz = result.data;
                    //     if (items) {
                    //         $("#fy4").bootstrapPaginator({
                    //             bootstrapMajorVersion: 3, //版本，这里设置为3，大于2即可
                    //             currentPage: 1,//当前页
                    //             totalPages: Math.ceil(((a_sum > 0) ? a_sum : 1) / vue_sjcx.fy_select),//总页数
                    //             // numberofPages: 10,//显示的页数
                    //             itemTexts: function (type, page, current) { //修改显示文字
                    //                 switch (type) {
                    //                     case "first":
                    //                         return "首页";
                    //                     case "prev":
                    //                         return "上一页";
                    //                     case "next":
                    //                         return "下一页";
                    //                     case "last":
                    //                         return "末页";
                    //                     case "page":
                    //                         return page;
                    //                 }
                    //             }, onPageClicked: function (event, originalEvent, type, page) { //异步换页
                    //                 //请求加载数据
                    //                 vue_sjcx.query(page, false);
                    //             }
                    //         });
                    //     }
                    // }
                }
            });
        },
        getChange: function () {
            setTimeout(function () {
                vue_sjcx.query(1, true);
            }, 200);
        },
        cli_input: function () {
            vue_sjcx.state_arr = [];
            $(".div-ul").find('input:checked').each(function () {
                let arr = $(this).val().split("|");
                vue_sjcx.state_arr.push({recordid:arr[0],channelid:arr[1],fdid:arr[2],recordtime:arr[3],recordtype:arr[4]});
            });
            if (vue_sjcx.state_arr.length > 0) {
                vue_sjcx.show_nums = true;
            } else {
                vue_sjcx.show_nums = false;
            }
        },
        state_cli: function (e) {
            let json_s = [];
            vue_sjcx.state_arr.forEach((item, index)=> {
                json_s.push({recordid: item.recordid,channelid:item.channelid,fdid:item.fdid,recordtime:item.recordtime,recordtype:item.recordtype, 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) {
                        vue_sjcx.query(1, true);
                        info_new("状态修改成功");
                        window.setTimeout("$('#info-warning-new').modal('hide')", 2000);
                    }
                }
            });
        },
        zdsx:function () {
            vue_sjcx.check_s=document.getElementById('push').checked;
        },
        delete:function (item) {
            vue_sjsstx.delete(item);
        },
        send:function(item){
           vue_sjsstx.send(item);
        }
    },
    mounted(){
        $("#kssj").val(getTime_extent(6).pre_rq_start + ' - ' + getTime().jssj);
        $.ajax({
            url: "/dept/listAllvideoIdsByDeptid",
            dataType: "json",
            type: "GET",
            data: {
                deptid: getCookie("bjpt_deptId"),
            },
            success: function (result) {
                vue_sjcx.jk_s = [];
                if (result.code == 0) {
                    if (result.data.length > 0) {
                        vue_sjcx.jk_s = result.data;
                    }
                }
            }
        });
        $.ajax({
            url: "/TrafficStatistics/listcode",
            dataType: "json",
            type: "GET",
            data: {
                codeid: 3,
                alarmlevel: '',
            },
            success: function (result) {
                vue_sjcx.arr_cllx = [];
                if (result.code == 0) {
                    if (result.data.length > 0) {
                        result.data.forEach((item, index)=> {
                            if (item.id != 'TRICYCLE' && item.id != 'CART')
                                vue_sjcx.arr_cllx.push({id: item.id, value: item.name});
                        });
                        setTimeout(function () {
                            $("#cllxs").selectpicker('refresh');
                            $("#cllxs").selectpicker('render');
                        }, 200);
                    }
                }
            }
        });
        $.ajax({
            url: "/TrafficStatistics/listcode",
            dataType: "json",
            type: "GET",
            data: {
                codeid: 1,
                alarmlevel: '',
            },
            success: function (result) {
                vue_sjcx.data_sjlxs = [];
                if (result.code == 0) {
                    if (result.data.length > 0) {
                        vue_sjcx.data_sjlxs.push({name: '全部', id: "", type: "",});
                        let arrs = [];
                        result.data.forEach((item, index)=> {
                            if (item.id != 'ROADWORKS' && item.id != 'ROADWORKS_OUT_OF_LINE') {
                                arrs.push(item);
                            }
                        });
                        arrs.forEach((item, index)=> {
                            if (index < 4) {
                                vue_sjcx.data_sjlxs.push(item);
                            } else {
                                vue_sjcx.data_sjlxs1.push(item);
                            }
                        });
                    }
                }
            }
        });
//查询间隔时间
        $.ajax({
            url: "/code/list/4",
            dataType: "json",
            type: "GET",
            success: function (result) {
                if (result.code == 0) {
                    vue_sjcx.offset= parseInt(result.data[0].alarmlevel)
                    }
                }
        });
        this.xzml();
    },

});
let vue_sjsstx = new Vue({
    el: '#myModal',
    data: {
        sp_src: '',
        data_wfsp: [],
        data_sj: {},
        class_s: 'class_1',
        class_s1: 'class_2',
        show_s: false,
        img_src_s: '',
        video_src: '',
        cllx: [],
        jk_arr: [],

    },
    methods: {
        sp_qh: function (e) {
            if (e == 1) {
                this.class_s = 'class_1';
                this.class_s1 = 'class_2';
                this.show_s = false;
            } else {
                this.class_s = 'class_2';
                this.class_s1 = 'class_1';
                this.show_s = true;
                this.video_src = '/TrafficStatistics/fielagent?ftpPath=' + this.data_sj.videopath;
            }
        },
        click_img_bf: function (src) {
            this.img_src_s = src;
        },

    },
    mounted(){
        if (this.data_wfsp.length > 0) {
            this.data_wfsp[0].kg = true;
            this.sp_src = this.data_wfsp[0].src;
//                document.getElementById("my_video_1").play();
        }
        $.ajax({
            url: "/TrafficStatistics/listcode",
            dataType: "json",
            type: "GET",
            data: {
                codeid: 1,
                alarmlevel: '',
            },
            success: function (result) {
                vue_sjsstx.cllx = [];
                if (result.code == 0) {
                    if (result.data.length > 0) {
                        vue_sjsstx.cllx = result.data;
                    }
                }
            }
        });

        $.ajax({
            url: "/dept/listvideo",
            dataType: "json",
            type: "GET",
            data: {
                deptId: getCookie("bjpt_deptId"),
                username: getCookie("bjpt_realName"),
                tdmc:''
            },
            success: function (result) {
                vue_sjsstx.jk_arr = [];
                if (result.code == 0) {
                    vue_sjsstx.jk_arr = result.data;
                }
            }
        });
    }
});

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, checked: true};
                } else {
                    arr.icon = 'glyphicon glyphicon-facetime-video zx',
                        arr.state = {expanded: false, checked: true};
                    arr.selectable = true;
                }
                if (item.nodes.length > 0) {
                    arr.nodes = item.nodes;
                }
                res.push(arr);
            }
        }
        return res
    }

    return loop(parId)
}
function checkNode(parentNode, i) {
    if (parentNode.nodes[i].nodes != undefined && parentNode.nodes[i].nodes.length !== 0 && parentNode.nodes[i].nodes.filter(n => n.level === null).length > 0) {
        for (let j = 0; j < parentNode.nodes[i].nodes.length; j++) {
            let d = checkNode(parentNode.nodes[i], j);
            d && j--;
        }
    } else {
        parentNode.nodes.splice(i, 1);
        return true
    }
}
//获取选中的id
function getChildNodeIdArr(node) {
    let ts = [];
    if (node.nodes) {
        for (let x in node.nodes) {
            ts.push(node.nodes[x].nodeId);
            if (node.nodes[x].nodes) {
                let getNodeDieDai = getChildNodeIdArr(node.nodes[x]);
                for (let j in getNodeDieDai) {
                    ts.push(getNodeDieDai[j]);
                }
            }
        }
    } else {
        ts.push(node.nodeId);
    }
    return ts;
};

//设置父节点
function setParentNodeCheck(node) {
    let parentNode = $("#tree-xzxq").treeview("getNode", node.parentId);
    if (parentNode.nodes) {
        let checkedCount = 0;
        for (let x in parentNode.nodes) {
            if (parentNode.nodes[x].state.checked) {
                checkedCount++;
            } else {
                break;
            }
        }
        if (checkedCount === parentNode.nodes.length) {
            $("#tree-xzxq").treeview("checkNode", parentNode.nodeId);
            setParentNodeCheck(parentNode);
        }
    }
};


//删除该事件
function deletetraff(recordid)
{
    stop(recordid);
       $.ajax({
        url: "/TrafficStatistics/deleteTraffalarmrecordById/"+recordid,
        type: "GET",
        success: function (result) {
            if (result.code == 0) {
//移除某li

             $("#" + recordid + "").remove();


            }
        }
    });
}
function send(recordid) {
    //调用接口发送给事件推送平台，然后更新表中推送状态
    $.ajax({
        url: "/TrafficStatistics/updateTraffalarmrecordPushStatusById/"+recordid,
        type: "GET",
        success: function (result) {
            if (result.code == 0) {
                //移除该
                $("#" + recordid + "").remove();
            }

        }
    });
}



laydate.render({
    elem: '#kssj'
    , type: 'datetime'
    , theme: '#368ff3'
    , range: true
});
// 全选/取消
$("#all").click(function () {
    $(".div-ul").find('input').each(function () {
        $(this).prop("checked", true);
    });
    vue_sjcx.state_arr = [];
    $(".div-ul").find('input:checked').each(function () {
        // vue_sjcx.state_arr.push($(this).val());
        let arr = $(this).val().split("|");
        vue_sjcx.state_arr.push({recordid:arr[0],channelid:arr[1],fdid:arr[2],recordtime:arr[3],recordtype:arr[4]});
    });
    vue_sjcx.show_nums = true;
});
$("#unall").click(function () {
    $(".div-ul").find('input').each(function () {
        $(this).removeAttr("checked", false);
        $(this).prop("checked", false);
        vue_sjcx.state_arr = [];
    });
    vue_sjcx.show_nums = false;
});
//放大缩小图片
$('[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);
});
let d = new Date().getTime();
let web_ip = "ws:/33.65.250.179: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 == "recordalarm") {
        if (data.data.type == 'TRAFFIC_INCIDENT_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 = a_id;
            // let jk_video_id = data.data.video_id;
            vue_sjcx.jk_s.forEach((item, index)=> {
                if (item.VIDOID == jk_video_id) {
                    if_cz = true;
                }
            });
            if (if_cz) {
                //事件类型
                let bjlx = '';
                //事件等级
                let sjdj = '';
                vue_sjsstx.cllx.forEach((item, index)=> {
                    if (item.id == data.data.incident_type) {
                    bjlx = item.name;
                    sjdj = item.alarmlevel;
                }
            });

                //监控名称
                let jkmc = '';
                vue_sjsstx.jk_arr.forEach((item, index)=> {
                    if (item.href == jk_video_id) {
                    jkmc = item.text;
                }
            });

            //     //违法图片
            //     let wfsp ="   <div class=\"pub-div\" v-show=\"!shows\">\n" +
            //         "                        <div class=\"div-img\" >\n" +
            //         "                            <img :src=\"item.img_src\" @click=\"click_img_bf(item.img_src)\">\n";
            //
            //     data.data.img_base64.forEach((item, index) => {
            //          wfsp = wfsp+'<img src="data:image/png;base64,'+item+'"'+' onclick=\"click_img_bf("'+item+'")\">';
            //
            // }
                //                 "                        </div>\n" +
                //                 "                    </div>";

            let html='<div class="li-top">'+
                '<img src="data:image/png;base64,'+data.data.img_base64[0]+'"></div>'+
                ' <div class="li-center">'+
                '<div>'+
                ' <span class="lx-span" v-text="item.recordname">'+bjlx +' </span>'+
                '</div>'+
                ' <div>'+
                ' <span>告警时间：</span>'+
                '<span >'+(new Date(parseInt(data.data.ts))).Format("yyyy-MM-dd hh:mm:ss")+'</span>'+
                '  </div>'+
                ' <div>'+
                ' <span>通道名称：</span>'+
                '  <span >'+jkmc+'</span>'+
                '  </div>'+
                '  </div>'+
                '  <div class="li-bottom">'+
                '  <a href="#" onclick="deletetraff('+data.recordid+')">&nbsp;&nbsp;删除</a>'+
                '<a href="#" onclick="send('+data.recordid+')">&nbsp;&nbsp;推送</a>'+
                // '  <a href="#" onclick="xq('+data.recordid+')">&nbsp;&nbsp;详情</a>'+
                ' </div><div class="timer" id="timer_"'+data.recordid+'>' +
                '<span class="display" id="display_'+  data.recordid+'">' +zero(parseInt(vue_sjcx.offset / 60), 2)+':'+
                zero(vue_sjcx.offset % 60, 2)+'.000' +'</span></div>';

                var timer_div = document.createElement("li");
                timer_div.className = "timer";
                timer_div.id = data.recordid;
                timer_div.innerHTML = html;

                $("#manualtable").append(timer_div);

                begin(data.recordid,vue_sjcx.offset);
                // setTimeout(function () {
                //     vue_sjcx.query(1, true);
                // }, 200);
            }
        }
    }
};