let nodeCheckedSilent = false;
let nodeUncheckedSilent = false;
let vue_sjcx = new Vue({
    el: '#sjcx',
    data: {
        searchText: '',
        show: true,
        data_table_wfpz: [],
        sjlx: '',
        count: '',
        deptId: getCookie("bjpt_deptId"),
        fy_select: 20,
        gd_span: '',
        show_nums: false,
        state_arr: [],
        cllx_select: [],
        clzt_select: [],
        clzt_select1:'2',
        arr_cllx: [],
        jk_s:[],
        check_s:false,
    },
    methods: {
        fastSearch: function () {
            this.xzml();
            // $("#tree-xzxq1").treeview('search', [this.searchText, {
            //     ignoreCase: true,      // case insensitive
            //     exactMatch: false,     // like or equals
            //     revealResults: true,   // reveal matching nodes
            // }]);
        },
        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-xzxq1').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;
            }
        },
        //详情
        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-xzxq1').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-xzxq1').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: '1',
                objlabel: objlabels,
                processstatus: processstatus,
                rectificationtype:vue_sjcx.clzt_select1=='2'?'':vue_sjcx.clzt_select1,
                 userid:getCookie("bjpt_userId")
            };
            $.ajax({
                url: "/TrafficStatistics/queryTraffalarmrecordByPage/1",
                dateType: 'json',
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify(json_s),
                success: function (result) {
                    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 () {
                // 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]});
            });
            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({id: item.id,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;
        }
    },
    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);
                    }
                }
            }
        });
        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: ''
    },
    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();
        }
    }
});

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)
}
//获取选中的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-xzxq1").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-xzxq1").treeview("checkNode", parentNode.nodeId);
            setParentNodeCheck(parentNode);
        }
    }
};

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:/localhost: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.type == 'TRAFFIC_INCIDENT_ALARM') {
            if(!vue_sjcx.check_s){
                return;
            }
            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) {
                setTimeout(function () {
                    vue_sjcx.query(1, true);
                }, 200);
            }
        }
    }
};