let state_sj = true;
var layer;
layui.config({
    base: '/lib/layui/extend/'
}).use(['layer'], function () {
    layer=layui.layer;
});

let vue_rwpfhistory = new Vue({
    el: '#rwpfhistory',
    data: {
        searchText: '',
        show: true,
        data_sjlxs: [],
        data_table_wfpz: [],
        num: 0,
        num1: 1000,
        sjlx: '',
        data_sjlxs1: [],
        count: '',
        deptId: getCookie("bjpt_deptId"),
        fy_select: 12,
        gd_span: '',
        show_nums: false,
        state_arr: [],
        cllx_select: [],
        taskwp_select:[{
            'id':0,
            'name':'否'
        },
            {
                'id':2,
                'name':'是'

            },

        ],
        taskwpmodel_select:[],
        clzt_select: [{
            'id':0,
            'name':'未处理'

        },{'id':1,
            'name':'正检'

        },{'id':2,
            'name':'误检'

        },{'id':3,
            'name':'重复事件'

        }],
        arr_cllx: [],
        jk_s: [],
        check_s: false,
        cllx: [],
        jk_arr: [],
        sjlx_select:[],
        model_select:[],
        taskwpmodel_select:null
    },
    methods: {
        fastSearch: function () {
            this.xzml();
        },
        xzml: function () {
            _this=this;
            $.ajax({
                url: "/dept/listvideo",
                dataType: "json",
                type: "GET",
                data: {
                    deptId: getCookie("bjpt_deptId"),
                    username: getCookie("bjpt_realName"),
                    tdmc: _this.searchText,
                },
                success: function (result) {
                    let defaultData = [];
                    _this.jk_arr = [];
                    if (result.code == 0) {
                        _this.jk_arr = result.data;
                        defaultData = toTree(result.data,  '0');
                        $('#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) {

                            }

                        });
                        _this.query(1, true);
                    }
                }
            });
            // $.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;
            //
            //         }
            //     }
            // });
        },
        qh_tab: function (el) {
            if (el == 1) {
                this.show = false;
            } else {
                this.show = true;
            }
        },
        //事件类型切换
        change: function (item, index) {
            _this=this;
            this.num = index;
            this.num1 = 1000;
            this.sjlx = item.id;
            this.gd_span = '';
            _this.query(1, true);
        },
        //事件类型切换
        change_gd: function (item, index) {
            _this=this;
            this.num = 5;
            this.sjlx = item.id;
            this.num1 = index;
            this.gd_span = item.name;
            _this.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 = [];
            //根据type 查询 详情

            $.ajax({
                url: "/traffic/queryTraffDetail/" + item.id + "/" + item.metatype,
                dateType: 'json',
                type: "GET",
                contentType: 'application/json',
                success: function (result) {
                    if (result.code == 0) {
                        //获得 json  的值，将详细信息展示在界面上
                        if (item.metatype == "3") {
                            vue_sjsstx.dataface = result.data[0];
                        }
                        else if (item.metatype == "1") {
                            vue_sjsstx.datapede = result.data[0];
                        }
                        else if (item.metatype == "2") {
                            vue_sjsstx.datatraffic = result.data[0];
                        }

                        else if (item.metatype == "4") {
                            vue_sjsstx.datapeople = result.data[0];
                        }
                    }

                    $("#myModal").modal("show");
                }
            });
            if (item.imagedata != null  && item.imagedata!='') {
                    vue_sjsstx.img_src_s ="http://zjh189.ncpoi.cc:7180"+item.imagedata;
                    vue_sjsstx.data_wfsp.push({src: "http://zjh189.ncpoi.cc:7180"+item.imagedata});

            }
            if (item.img2path != null  && item.img2path!='') {
                if(item.img2path.indexOf("http:")>-1) {
                    vue_sjsstx.img_src_s ="http://zjh189.ncpoi.cc:7180"+item.img2path;
                    vue_sjsstx.data_wfsp.push({src:  item.img2path});
                }
            }
            if (item.img3path != null && item.img3path!='') {
                if(item.img3path.indexOf("http:")>-1) {
                   // vue_sjsstx.img_src_s = '/traffic/fielagent?ftpPath=' + item.img3path;
                    vue_sjsstx.data_wfsp.push({src: item.img3path});
                }
            }
            if (item.img4path != null && item.img4path!='') {
                if(item.img4path.indexOf("http:")>-1) {
                   // vue_sjsstx.img_src_s = '/traffic/fielagent?ftpPath=' + item.img4path;
                    vue_sjsstx.data_wfsp.push({src: item.img4path});
                }
            }
            if (item.img5path != null && item.img4path!='') {
                if(item.img5path.indexOf("http:")>-1) {
                    vue_sjsstx.data_wfsp.push({src: item.img5path});
                }
            }

        }
        ,
        query: function (pages, items) {
            _this=this;
            let nodes = $('#tree-xzxq').treeview('getChecked').filter(n => n.level == null
            ).
            map(n => {
                return n.href
            }
            )
            ;
            let arr_nodes = "";
            if (nodes!=null && nodes.length > 0) {
                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 type = "";
            if (this.sjlx_select!=null &&this.sjlx_select.length >0) {
                type=this.sjlx_select.join(",")
            }
            ;
            let processstatus = "";
            if (this.model_select!=null &&this.model_select.length > 0) {
                processstatus=this.model_select.join(",");
            }
            let json_s = {
                videoids: arr_nodes,
                page: pages,
                limit: li,
                recordtype: type,
                starttime: starttime,
                endtime: endtime,
                deptid: getCookie("bjpt_deptId"),
                processstatus: processstatus,
                userid: getCookie("bjpt_userId"),
                sfpf: this.taskwpmodel_select
            };
            $.ajax({
                url: "/traffic/queryTraffalarmrecordByPage",
                dateType: 'json',
                type: "POST",
                contentType: 'application/json',
                data: JSON.stringify(json_s),
                success: function (result) {
                    _this.data_table_wfpz = [];
                    if (result.code == 0) {
                        let a_sum = result.count;
                        _this.count = result.count;
                        _this.data_table_wfpz = result.data;
                        if (items) {
                            $("#fy4").bootstrapPaginator({
                                bootstrapMajorVersion: 3, //版本，这里设置为3，大于2即可
                                currentPage: 1,//当前页
                                totalPages: Math.ceil(((a_sum > 0) ? a_sum : 1) / _this.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) { //异步换页
                                    //请求加载数据
                                    setTimeout(function () {
                                        _this.query(page, false);
                                    }, 100);

                                }
                            });
                        }

                    }
                }
            });
        },
        getChange: function () {
            setTimeout(function () {
                vue_rwpfhistory.query(1, true);
            }, 100);
        },
        back: function(){
            let taskexists=0;
            if(vue_rwpfhistory.state_arr.length>0) {
                //判断是否是已经下派的任务
                vue_rwpfhistory.state_arr.forEach(function (item, index) {
                    if (item.handler=="undefined"  || item.handler == null || item.handler == '') {
                        taskexists = 1;
                    }
                });
            }
            let str="";
            if(taskexists==1){
                str="存在尚未分配的告警，只撤回已经分派的任务,"
            }
            if(vue_rwpfhistory.state_arr.length>0) {
                layer.confirm(str+"确认撤回", {icon: 3, title: "提示"},
                    function (index) {
                    //将分派出去的任务信息删除
                        $.ajax({
                            url: "/traffic/delDisputesInfo",
                            dateType: 'json',
                            type: "POST",
                            contentType: 'application/json',
                            data: JSON.stringify(vue_rwpfhistory.state_arr),
                            success: function (result) {
                                if (result.code == 0) {
                                    vue_rwpfhistory.query(1, true);
                                    layer.msg("撤回成功");
                                    vue_rwpfhistory.state_arr=[];
                                }
                                else{
                                    layer.msg("撤回失败");
                                }
                            }
                        });


                        layer.close(index);
                    }, function (index) {//取消回调
                        layer.close(index);
                    }
                );
            }else{
                layer.msg("请选择告警信息！")
            }



     },
        distributed: function(){
            //派发,弹出窗口
            if(vue_rwpfhistory.state_arr.length>0) {
                $("#myModal_rwpfhistory").modal('show');
            }else{
                layer.msg("请选择告警信息！")
            }
        },
        sfpfrw:function(){
            let taskexists=0;
            if(vue_rwpfhistory.state_arr.length>0) {
                //判断是否是已经下派的任务
                vue_rwpfhistory.state_arr.forEach(function (item, index) {
                    if (item.handler != "undefined" && item.handler != null && item.handler != '') {
                        taskexists = 1;
                    }
                });
                return taskexists;
            }
        },
        del: function() {
                let sfpf= this.sfpfrw();
                msg="确认删除该告警?";
                if(sfpf==1) {
                    msg="存在已经被分派的告警信息,确认删除?";
                }

                layer.confirm(msg, {icon: 3, title: "提示"},
                    function (index) {
                        layer.close(index);
                        $.ajax({
                            url: "/traffic/delTraffalarmrecordByIds",
                            dateType: 'json',
                            type: "POST",
                            contentType: 'application/json',
                            data: JSON.stringify(vue_rwpfhistory.state_arr),
                            success: function (result) {
                                if (result.code == 0) {
                                    vue_rwpfhistory.query(1, true);
                                    layer.msg("删除成功");
                                    vue_rwpfhistory.state_arr=[];
                                }
                                else{
                                    layer.msg("删除失败");
                                }
                            }
                        });
                    }, function (index) {//取消回调
                        layer.close(index);
                    }
                );
                },
        cli_input: function () {
            vue_rwpfhistory.state_arr = [];
            $(".div-ul").find('input:checked').each(function () {
                let arr = $(this).val().split("|");
                vue_rwpfhistory.state_arr.push({
                    id: arr[0],
                    channelid: arr[1],
                    fdid: arr[2],
                    recordtime: arr[3],
                    recordtype: arr[4],
                    handler:arr[5]
                });
            });
            if (vue_rwpfhistory.state_arr.length > 0) {
                vue_rwpfhistory.show_nums = true;
            } else {
                vue_rwpfhistory.show_nums = false;
            }
        },
        state_cli: function (e) {
            let json_s = [];
            vue_rwpfhistory.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: "/traffic/updateTraffalarmrecordById",
                dateType: 'json',
                type: "POST",
                contentType: 'application/json',
				 data: JSON.stringify(json_s),
                success: function (result) {
                    if (result.code == 0) {
                        vue_rwpfhistory.query(1, true);
                        info_new("状态修改成功");
                        window.setTimeout("$('#info-warning-new').modal('hide')", 2000);
                    }
                }
            });
        },
        zdsx: function () {
            vue_rwpfhistory.check_s = document.getElementById('push').checked;
        },
        zdtx: function () {
            state_sj = document.getElementById('status').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_rwpfhistory.jk_s = [];
                if (result.code == 0) {
                    if (result.data.length > 0) {
                        vue_rwpfhistory.jk_s = result.data;
                    }
                }
            }
        });
        $.ajax({
            url: "/traffic/listcode",
            dataType: "json",
            type: "GET",
            data: {
                codeid: 3,
                alarmlevel: '',
            },
            success: function (result) {
                vue_rwpfhistory.arr_cllx = [];
                if (result.code == 0) {
                    if (result.data.length > 0) {

                        vue_rwpfhistory.arr_cllx=result.data;

                    }
                }
            }
        });
        $.ajax({
            url: "/traffic/listcode",
            dataType: "json",
            type: "GET",
            data: {
                codeid: 2,
                alarmlevel: '',
            },
            success: function (result) {
                vue_rwpfhistory.data_sjlxs = [];
                if (result.code == 0) {
                    if (result.data.length > 0) {
                        vue_rwpfhistory.data_sjlxs = result.data;
                    }

                }
                setTimeout(function () {
                    $("#cllxs").selectpicker('refresh');
                    $("#cllxs").selectpicker('render');
                }, 200);
            }
        });
        this.xzml();
        //初始化模态弹窗的角色和用户数据

        $.ajax({
            url: "/role/list?page=1&limit=100",
            dataType: "json",
            type: "GET",
            success: function (result) {
                vue_sjsstxnow.role_select = [];
                if (result.code == 0) {
                    if (result.data.length > 0) {
                        vue_sjsstxnow.role_select = result.data;
                    }
                    setTimeout(function () {
                        $("#role").selectpicker('refresh');
                        $("#role").selectpicker('render');
                    }, 200);
                }
                }
        });

        $.ajax({
            url: "/role/listAllUsers",
            dataType: "json",
            type: "GET",
            success: function (result) {
                vue_sjsstxnow.role_select = [];
                if (result.code == 0) {
                    if (result.data.length > 0) {
                        vue_sjsstxnow.user_data = result.data;
                    }
                }
            }
        });
    },
});

//新的模态框,三等级模态框
let vue_sjsstxnow = new Vue({
    el: '#myModal_rwpfhistory',
    data: {
        role_select: [],
        rolepmodel_select:null,
        usermodel_select: null,
        user_select:[],
        user_data:[],
        index: 0,
    },
    methods: {
        state_cli: function (item, e, index, type) {
            let json_s = [];
            json_s.push({
                id: item.recordid + '',
                channelid: item.channelid,
                fdid: item.fdid,
                recordtime: item.recordtime,
                recordtype: item.recordtype.toLowerCase(),
                processstatus: e
            });
            $.ajax({
                url: "/traffic/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_sjsstxnow.yjsj_data[index].ss_type = e;
                        } else if (type == 2) {
                            vue_sjsstxnow.ejsj_data[index].ss_type = e;
                        } else {
                            vue_sjsstxnow.sjsj_data[index].ss_type = e;
                        }
                    }
                }
            });
        },
        getusers:function(event,item) {
            //根据角色选择的值，查询用户信息
            let json = [];
            roleid=parseInt(event.target.value);
            this.user_data.forEach(function(item, index) {
                if(item.parentid == roleid)
                {
                    json.push(item);
                }
            });
            this.user_select = json;
            setTimeout(function () {

                $("#user").selectpicker('refresh');
                $("#user").selectpicker('render');
            }, 200);
        },
        dorwpf:function(){
            //获得选中的userid,告警id
            let jsonstr=[];
            vue_rwpfhistory.state_arr.forEach(function(item,index){
                jsonstr.push(item.id);
            });
            $.ajax({
                url: "/role/addtaskinfo",
                dateType: 'json',
                type: "POST",
                data:JSON.stringify({
                    "traffid":jsonstr,
                    "userid":vue_sjsstxnow.usermodel_select
                }),
                contentType: 'application/json',
                success: function (result) {
                    if (result.code == 0) {
                        layer.alert("派发成功！", {
                            icon: 1,
                            skin: 'layer-ext-moon'
                        })
                        $("#myModal_rwpfhistory").modal('hide');
                       vue_rwpfhistory.getChange();
                    }
                    else{
                        layer.alert("派发超时！", {
                            icon: 2,
                            skin: 'layer-ext-moon'
                        })

                    }
                }
            });

        },
        del: function () {
            let json_s = [];
            if(vue_rgjy.state_arr.length>0) {
                layer.confirm("确认删除?", {icon: 3, title: "提示"},
                    function (index) {
                        // vue_sjcx.state_arr.forEach((item, index) = > {
                        //     json_s.push({  id: item.id       });
                        // });
                        $.ajax({
                            url: "/traffic/deltaskinfoByIds",
                            dateType: 'json',
                            type: "POST",
                            contentType: 'application/json',
                            data: JSON.stringify(vue_rgjy.state_arr),
                            success: function (result) {
                                if (result.code == 0) {
                                    layer.msg("删除成功");
                                    layer.close(index);
                                    vue_rgjy.query(1, true);
                                }
                            }
                        });
                    }, function (index) {//取消回调
                        layer.close(index);
                    }
                );
            }else{
                layer.msg("请选择告警信息!");
            }
        },
    },
    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, 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);
        }
    }
};

laydate.render({
    elem: '#kssj'
    , type: 'datetime'
    , theme: '#368ff3'
    , range: true
});
// 全选/取消
$("#all").click(function () {
    $(".div-ul").find('input').each(function () {
        $(this).prop("checked", true);
    });
    vue_rwpfhistory.state_arr = [];
    $(".div-ul").find('input:checked').each(function () {
        // vue_rwpfhistory.state_arr.push($(this).val());
        let arr = $(this).val().split("|");
        vue_rwpfhistory.state_arr.push({
            id: arr[0],
            channelid: arr[1],
            fdid: arr[2],
            recordtime: arr[3],
            recordtype: arr[4],
            handler:arr[5]
        });
    });
    vue_rwpfhistory.show_nums = true;
});
$("#unall").click(function () {
    $(".div-ul").find('input').each(function () {
        $(this).removeAttr("checked", false);
        $(this).prop("checked", false);
        vue_rwpfhistory.state_arr = [];
    });
    vue_rwpfhistory.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);
});