
let vue_right = new Vue({
    el: '.right-nav',
    data: {
        data_table_monitor: [],
        xz_jg: getCookie("bjpt_deptId"),
        count: '',
        level: '',
        fy_select:20,
    },
    methods: {

        addtask: function (item) {
            // vue_sjcx.widthdata="440px";
            vue_sjcx.cheakallornot=null;
            vue_sjcx.sbbh=item.sbbh;
            vue_sjcx.sfzdzptype=item.tdlx==2?1:0;
            vue_sjcx.imgsrc=item.kz3;
            $("#myModal2").modal("show");
            let  iframe=document.getElementById('iframe');
            iframe.onload=function() {
                document.getElementById('iframe').contentWindow.frames.setImg();
            }
            },
        add: function (item){
            vue_default.data_s.xh=null;
            $("#myjgModal1").modal("show");
        },
        edit: function (item) {
                vue_default.data_s.xh = item.xh;
                vue_default.data_s.sbbh = item.sbbh;
                vue_default.data_s.tdbh = item.tdbh;
                vue_default.data_s.tdmc = item.tdmc;
                vue_default.valueId= item.xzbh;
                vue_default.data_s.tdlx=item.tdlx;
                vue_default.initHandle();
                $("#myjgModal1").modal("show");
        },
        del: function (item) {
            if (!confirm("确认删除监控吗？")) {
                return;
            }
            $.ajax({
                url: "/video/delete/" + item.xh,
                dataType: "json",
                type: "GET",
                data: {},
                success: function (result) {
                    vue_right.queryRY(1, true);
                    layer.alert("监控删除成功");

                }
            });
        },
        queryRY: function (pages, items) {
            $.ajax({
                url: "/video/list",
                dataType: "json",
                type: "get",
                data: {
                    page: pages,
                    pageSize: this.fy_select,
                    deptId: this.xz_jg,
                    userId: getCookie("bjpt_userId"),
                    username: getCookie("bjpt_realName"),
                    videoName: $("#ryxm").val(),
                },
                success: function (result) {
                    vue_right.data_table_monitor = [];
                    if (result.code == 0) {
                        let a_sum = result.count;
                        vue_right.count = result.count;
                        vue_right.data_table_monitor = result.data;
                        if (items) {
                            $("#fy4").bootstrapPaginator({
                                bootstrapMajorVersion: 3, //版本，这里设置为3，大于2即可
                                currentPage: 1,//当前页
                                totalPages: Math.ceil(((a_sum > 0) ? a_sum : 1) / vue_right.fy_select),//总页数
                                // numberofPages: this.fy_select,//显示的页数
                                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_right.queryRY(page, false);
                                }
                            });
                        }
                    }
                }
            });
        },
        getChange:function () {
            this.queryRY(1,true);
        }
    },
    mounted(){
        this.queryRY(1, true);
    }
});
let vue_sjcx = new Vue({
    el:"#myModal2",
    data:{
        widthdata:'440px',
        cheakallornot:null,
        sbbh:null,
        timetype:0,
        detectType:null,
        notljt:1,
        notface:1,
        sfzdzptype:0,
        imgsrc:''
    },
    methods:
        {
            setimg:function(item){
                var iframe=document.getElementById("iframe");
                document.getElementById('iframe').contentWindow.frames.setImg();
                iframe.onload=function(){
                    iframe.contentWindow.document.getElementById("draw-canvas").style.backgroundImage = 'url("' + item+ '")';
                }

            },
            changewidth: function() {
                if(this.cheakallornot=="0"){
                    this.widthdata="1070px";
                    this.setimg(this.imgsrc);
                }
                else if(this.cheakallornot=="1") {
                    this.widthdata = "440px";
                }
            },

            getPic:function(){
                //根据当前设备sbbh 调用抽帧服务
                that=this;
                $.ajax({
                        url: "/video/getsnapPic/"+this.sbbh,
                        dataType: "json",
                        type: "GET",
                        contentType: 'application/json',
                        success: function (result) {
                            if(result.errorCode=="0"){
                               that.imgsrc="http://zjh189.ncpoi.cc:7180"+ result.data;
                                document.getElementById('iframe').contentWindow.frames.setImg();
                                // draw.src=result.data;
                            }
                            else{
                                alert("抽帧繁忙，请重试!")
                            }

                        },error:function(result){
                            alert("获得失败!")

                        }
                });
            },
            changedetectType: function(){
            if(this.detectType=="15" ){
                //垃圾桶检测
                this.notljt=0;
            }else{
                this.notljt=1;
            }
            if(this.detectType=="60"){
                this.notljt=2;
                this.objectType="6";
            }
            else{
                this.notljt=1;
            }
            },
            addtask: function (item) {
                if($("#starthour").val()=="" && $("#endhour").val()!="")
                {
                    layer.msg("请输入执行开始时刻！");
                    return;
                }
                if( $("#starthour").val()!="" && $("#endhour").val()=="")
                {
                    layer.msg("请输入执行结束时刻！");
                    return;
                }
                if(parseInt($("#starthour").val()) >24)
                {
                    layer.msg("开始时间超过24时！");
                    return;
                }

                if(parseInt($("#endhour").val()) >24)
                {
                    layer.msg("结束时间超过24时！");
                    return;
                }
                if(parseInt($("#starthour").val()) > parseInt($("#endhour").val()))
                {
                    layer.msg("执行开始时刻大于执行结束时刻，请重新输入！");
                    return;
                }

                if($("#schedulerRule").val()=='' && this.sfzdzptype==0){
                    layer.msg("请输入执行时间间隔！");
                    return;
                }
                if($("#name").val()==''){
                    layer.msg("请输入任务名称！");
                    return;
                }

                if($("#detectType").val()==''){
                    layer.msg("请输入事件类型！");
                    return;
                }
                if(this.detectType!="15") {
                    if ($("#objectType").val() == '') {
                        layer.msg("请输入检测对象！");
                        return;
                    }
                    if(this.sfzdzptype=="1")//自动抓拍的相机)
                    {
                        //调用新增自动抓拍任务
                        $.ajax({
                            url: "/video/autoSnapTask",
                            dataType: "json",
                            type: "POST",
                            contentType: 'application/json',
                            data: JSON.stringify(
                                {
                                    detectType: this.detectType,
                                    deviceId: vue_sjcx.sbbh,
                                    type: "0",
                                    name: $("#name").val(),
                                    params: {
                                        starthour: $("#starthour").val() ,
                                        endhour:$("#endhour").val(),
                                        thresholdValue:$("#thresholdValue").val(),
                                        objectType: $("#objectType").val(),
                                        sendType: $("#autosend").val(),//是否自动推送,
                                    },
                                    area: this.cheakallornot == "1" ? [] : [{
                                        x: $("#objectxy").val().split(",")[0],
                                        y: $("#objectxy").val().split(",")[1],
                                        w: $("#objectxy").val().split(",")[2],
                                        h: $("#objectxy").val().split(",")[3],
                                    }],
                                    callBackUrl: $("#url").val()
                                }
                            ),
                            success: function (result) {
                                if (result.errorCode == '0') {
                                    vue_right.queryRY(1, true);
                                    layer.msg("任务新增成功", {
                                        icon: 1,
                                        time: 2000
                                    });
                                    $("#myModal2").modal("hide");
                                } else {
                                    layer.msg(result.errorMsg, {
                                        icon: 2,
                                        time: 2000
                                    });
                                }
                            }
                        });
                    }else {
                            if( this.timetype == 0){
                                str=$("#starthour").val() + "," + $("#endhour").val() + "," + $("#schedulerRule").val();
                            }else{
                                str= $("#starthour").val() + "," + $("#endhour").val() + "," + $("#schedulerRule").val() * this.timetype * 60;
                            }

                        //确认添加任务事件
                        $.ajax({
                            url: "/video/task",
                            dataType: "json",
                            type: "POST",
                            contentType: 'application/json',
                            data: JSON.stringify(
                                {
                                    detectType: this.detectType,
                                    deviceId: vue_sjcx.sbbh,
                                    type: "0",
                                    name: $("#name").val(),
                                    params: {
                                        schedulerRule: str,
                                        thresholdValue:$("#thresholdValue").val(),
                                        objectType: $("#objectType").val(),
                                        sendType: $("#autosend").val(),//是否自动推送,
                                    },
                                    area: this.cheakallornot == "1" ? [] : [{
                                        x: $("#objectxy").val().split(",")[0],
                                        y: $("#objectxy").val().split(",")[1],
                                        w: $("#objectxy").val().split(",")[2],
                                        h: $("#objectxy").val().split(",")[3],
                                    }],
                                    callBackUrl: $("#url").val()
                                }
                            ),
                            success: function (result) {
                                if (result.errorCode == '0') {
                                    vue_right.queryRY(1, true);
                                    layer.msg("任务新增成功", {
                                        icon: 1,
                                        time: 2000
                                    });
                                    $("#myModal2").modal("hide");
                                } else {
                                    if (result.errorCode == '-1')
                                        {
                                            result.errorMg="超时";
                                        }
                                        else{
                                            result.errorMsg="任务已存在";
                                        }
                                    layer.msg(result.errorMsg, {
                                        icon: 2,
                                        time: 2000
                                    });
                                }
                            }
                        });
                    }
                }
                else{//调用垃圾识别算法服务
                    str=$("#schedulerRule").val()*this.timetype*60000;
                    if(this.timetype==0){
                        str=$("#schedulerRule").val()*1000;
                    }

                    $.ajax({
                        url: "/video/LJTtask",
                        dataType: "json",
                        type: "POST",
                        contentType: 'application/json',
                        data: JSON.stringify(
                            {
                                deviceNum: vue_sjcx.sbbh,
                                spId: vue_sjcx.sbbh,
                                interfaceCode: "NEW_LJTMYJC_001",
                                interval:str ,
                                status:1,
                                params: {
                                    starthour: $("#starthour").val(),
                                    endhour: $("#endhour").val(),
                                    name :$("#name").val(),
                                    region:{
                                        x: $("#objectxy").val().split(",")[0],
                                        y: $("#objectxy").val().split(",")[1],
                                        w: $("#objectxy").val().split(",")[2],
                                        h: $("#objectxy").val().split(",")[3],
                                    },
                                    sendType:$("#autosend").val()//是否自动推送
                                },
                                callBackUrl:$("#url").val()
                            }
                        ),
                        success: function (result) {
                            if(result.errorCode=='0') {
                                vue_right.queryRY(1, true);
                                layer.msg("任务新增成功");
                                $("#myModal2").modal("hide");
                            }
                            else{
                                layer.alert(result.errorMsg);
                            }
                        }
                    });
                }


            }
        },
});
let  vue_default= new Vue({
    el:"#myjgModal1",
        name: "el-tree-select",
        data() {
            return {
                isClearable: true,      // 可清空（可选）
                isAccordion: true,      // 可收起（可选）
                valueId: 0,            // 初始ID（可选）
                valueTitle: '',
                defaultExpandedKey: [],
                tdlxdata:[{
                    'id':'1',
                    'name':'RTSP'
                },{'id':'0',
                    'name':'HLS'
                },
                {'id':'2',
                    'name':'自动抓拍'
                }],
                data_s: {
                    xh: '',
                    sbbh: '',
                    tdbh: '0',
                    tdmc: '',
                    xzbh: '',
                    jd: '',
                    wd: '',
                    tdlx:'',
                    squrllj : '',
                    wbbh: '',
                },
                // 选项列表数据(树形结构的对象数组)
                options: {type: Array, default: []},
                props: {                // 配置项（必选）
                    value: 'id',
                    label: 'name',
                    children: 'children',
                },
                // 选项列表（必选）
                list: [
                    ]};
        },
        mounted() {
            that=this;
            $.ajax({
                url: "/depttree/alltree",
                dataType: "json",
                type: "GET",
                success: function (result) {
                    if (result.code == 0) {
                        that.list=result.data;
                        that.initHandle();
                    }
                }
            });
        },
        methods: {
            define(){
                if(vue_default.valueId==null || vue_default.valueId=='')
                {
                    layer.msg("请选择设备所属部门！");
                    return;
                }
                vue_default.data_s.xzbh=vue_default.valueId;
                if(vue_default.data_s.xh!=null && vue_default.data_s.xh!='')
                {//编辑监控
                    $.ajax({
                        url: "/video/edit",
                        dataType: "json",
                        type: "POST",
                        data: vue_default.data_s,
                        success: function (result) {
                            if (result.code == 0) {
                                vue_right.queryRY(1, true);
                                $("#myjgModal1").modal("hide");
                                layer.msg("监控修改成功");
                            }
                        }
                    });
                }
                else{
                    $.ajax({
                        url: "/video/add",
                        dataType: "json",
                        type: "POST",
                        data: vue_default.data_s,
                        success: function (result) {
                            if (result.code == 0) {
                                vue_right.queryRY(1, true);
                                $("#myjgModal1").modal("hide");
                                info_new("监控新增成功");
                                window.setTimeout("$('#info-warning-new').modal('hide')", 2000);
                            }
                        }
                    });
                }
            },
            // 初始化值
            initHandle() {
                if (this.valueId) {
                    this.valueTitle = this.$refs.selectTree.getNode(this.valueId).data[this.props.label]     // 初始化显示
                    this.$refs.selectTree.setCurrentKey(this.valueId)       // 设置默认选中
                    this.defaultExpandedKey = [this.valueId]      // 设置默认展开
                }
                this.initScroll()
            },

            // 初始化滚动条
            initScroll() {
                this.$nextTick(()=> {
                    let scrollWrap = document.querySelectorAll('.el-scrollbar .el-select-dropdown__wrap')[0]
                    let scrollBar = document.querySelectorAll('.el-scrollbar .el-scrollbar__bar')
                    scrollWrap.style.cssText = 'margin: 0px; max-height: none; overflow: hidden;'
                scrollBar.forEach(ele => ele.style.width = 0
            )
            })
            },

            // 切换选项
            handleNodeClick(node) {
                this.valueTitle = node[this.props.label]
                this.valueId = node[this.props.value]
                this.$emit('getValue', this.valueId)
                this.defaultExpandedKey = []
            },

            // 清除选中
            clearHandle() {
                this.valueTitle = ''
                this.valueId = null
                this.defaultExpandedKey = []
                this.clearSelected()
                this.$emit('getValue', null)
            },

            // 清空选中样式
            clearSelected() {
                let allNode = document.querySelectorAll('#tree-option .el-tree-node')
                allNode.forEach((element) => element.classList.remove('is-current')
            )
            }

        },
        watch: {
            value() {
                this.valueId = this.value
                this.initHandle()
            }
        },
        computed: {
            /* 转树形数据 */
            optionData() {
                that=this;
                let cloneData =  JSON.parse(JSON.stringify(that.list ))  ;     // 对源数据深度克隆
                return cloneData.filter(father => {                      // 循环所有项，并添加children属性
                    let branchArr = cloneData.filter(child => father.id == child.parentId
                        )
                    ;       // 返回每一项的子级数组
                    branchArr.length > 0 ? father.children = branchArr : ''   //给父级添加一个children属性，并赋值
                    return father.parentId == "0";      //返回第一层
                })
                    ;
            }
        },
    } );
var lastSelectedNodeId = null;
//最后一次触发时间
var lastSelectTime = null;
function customBusiness(data) {
//        alert("双击获得节点名字： "+data.text);
}
function clickNode(event, data) {
    if (lastSelectedNodeId && lastSelectTime) {
        var time = new Date().getTime();
        var t = time - lastSelectTime;
        if (lastSelectedNodeId == data.nodeId && t < 300) {
            customBusiness(data);
        }
    }
    lastSelectedNodeId = data.nodeId;
    lastSelectTime = new Date().getTime();
}
//自定义双击事件
function customDblClickFun() {
    //节点选中时触发
    $('#tree-xzxq').on('nodeSelected', function (event, data) {
        clickNode(event, data)
    });
    //节点取消选中时触发
    $('#tree-xzxq').on('nodeUnselected', function (event, data) {
        clickNode(event, data)
    });
}
$(document).ready(function () {
    customDblClickFun();
});
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) {
                if(item.level!=null){
                    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) {
                        if (item.nodes.length > 0) {
                            arr.nodes = item.nodes;
                            arr.state = {expanded: true};
                        }
                    }else{

                        arr.selectable = true;
                    }
                    res.push(arr);
                }
            }
        }
        return res
    }
    return loop(parId)
}
