var dataTable=null;
var resultData=null;
var tiggleValue="basicData";
var type = 'online'; //离线在线
var $area = $("#area");
var $startTime = $("#startTime");
var $endTime = $("#endTime");

$(document).ready(function(){

    initCheckBox()
    //初始化区域
    $.ajax({
        type: "POST",
        url: "/pqs9900/user/getAreasInfo",
        dataType:'json',
        success:function (data) {
            $("#area").val(data[0].name);
            $("#area").attr("index", data[0].id);
            areaTree = $.fn.zTree.init($("#areaTree"), settingAreaTree, data);
            //初始化页面内容
            var area = $area.eq(0).attr("index");
            var startTime = $startTime.eq(0).val();
            var endTime = $endTime.eq(0).val();
            refresh(area, startTime, endTime);
        }
    })
});

//点击确定，去后台请求参数
$("#query").click(function() {
    var area = $area.eq(0).attr("index");
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    refresh(area,startTime,endTime);
});

window.refreshes = function () {
    var area = $area.eq(0).attr("index");
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    refresh(area,startTime,endTime);
}


//获取表格数据
function refresh(area,startTime,endTime){
    var i ;
    $.ajax({
        type : "POST",
        url : "/pqs9900/area/getVoltageDetail",
        contentType: 'application/json;charset=UTF-8',
        dataType : "text",
        data : JSON.stringify({
            startTime : startTime,
            endTime : endTime,
            area:area,
            type:type
        }),
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        success : function(data) {
            data = $.parseJSON(data);
            if (data.code === 500) {
                layer.msg(data.message,{icon:2,time:2000})
                resultData=null;
            } else {
                resultData=data.body;
            }
            startQuery();
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(i);
        }
    });
}


function initTable(data){
    var height=$(window).height()-140;
    dataTable=$("#vdlist").DataTable();
    dataTable.clear().draw();
    dataTable=$('#vdlist').DataTable({
        order: [0, "desc"],
        columnDefs: [
            { "width": "15%", "targets": 0 },
            { "width": "10%", "targets": [1,2,3,4,5,7,8,9] },
        ],
        columns: [
            {data:"time"},
            {data:"gdName"},
            {data:"subName", render:function (data, type, full, meta) {
                    var value=data;
                    if(data.length>8){
                        value=data.substring(0,7)+"...";
                        value="<span title="+data+">"+value+"</span>";
                    }
                    return value;
                }},
            {data:"ip"},
            {data:"lineName"},
            {data:"scale"},
            {data:"eventValue",width:'3%'},
            {data:"persistTime"},
            {data:"severity",
                render:function (data, type, full, meta) {
                    return displayYzd(data,full.persistTime,full.eventValue);
                }
            },
            {data:"eventType",render:function (data, type, full, meta) {
                    return displayValue(data,full.eventValue);
                }},
            {data:"eventReason",render:function (data, type, full, meta) {
                    return displayValue(data,full.eventValue);
                }},
            {data:"fileFlag",render:function (data, type, full, meta) {
                    if(data == 1){
                        return '存在波形文件'
                    }else {
                        //未招
                        return '<button type="button" class="btn btn-primary" onclick="uploadWave(\''+full.lineId+'\',\''+full.eventDetailIndex+'\',\''+full.time+'\')">上传波形文件</button>'

                    }
                }}
        ],
        destroy : true,
        data : data,
        lengthChange: false,
        searching: true,
        dom:'rtip',
        scrollX:true,
        scrollY: height,
        lengthMenu : [ 50 ],
        language : {
            url:'/pqs9900/json/chine.json'
        },
        fnDrawCallback: function(oTable) {
            $("#vdlist_info").addClass("fl");
            $("#vdlist_paginate").addClass("fr");
            $("#vdlist_paginate").append("<div style='float:right;padding-top:4px;padding-left:10px'>到第 <input type='text' id='changePage' class='input-text' style='width:50px;height:28px;'> 页  <button class='btn btn-primary' id='dataTable-btn'>确定</button></div>");
            var table = $("#vdlist").dataTable();
            $('#dataTable-btn').click(function(e) {
                if($("#changePage").val() && $("#changePage").val() > 0) {
                    var redirectpage = $("#changePage").val() - 1;
                } else {
                    var redirectpage = 0;
                }
                table.fnPageChange(redirectpage);
            });
        }
    });
}


//获取严重度显示的值
function displayYzd(data,persisttime,eventvaule) {
    var yzd=0;
    if(null===data|data===0.0){
        //根据持续时间计算出严重度
        yzd=calculateYzd(persisttime,eventvaule);
    }else{
        yzd=data;
    }
    //判断是否为暂升事件
    if(eventvaule>100){
        yzd="/";
        return "<span style='color:#000'>"+yzd+"</span>";
    }
    if(0<=yzd&yzd<=1){
        return "<span style='color:#22B14C'>"+yzd+"</span>";
    }else if(yzd<=2){
        return "<span style='color:#3F48CC'>"+yzd+"</span>";
    }else if(yzd<=5){
        return "<span style='color:#FFF200'>"+yzd+"</span>";
    }else if(yzd<=10){
        return "<span style='color:#FF7F27'>"+yzd+"</span>";
    }else{
        return "<span style='color:#ED1C24'>"+yzd+"</span>";
    }
}


//计算严重度
function calculateYzd(persisttime,eventvaule){
    persisttime=persisttime*1000;
    eventvaule=eventvaule/100;
    var yzd=0;
    if (persisttime <= 20) {
        yzd = 1-eventvaule;
    } else if (persisttime > 20 && persisttime <= 200) {
        yzd = 2*(1-eventvaule);
    } else if (persisttime > 200 && persisttime <= 500) {
        yzd = 3.3*(1-eventvaule);
    }else if(persisttime > 500 && persisttime <=10000){
        yzd=5*(1-eventvaule);
    } else {
        yzd = 10*(1-eventvaule);
    }
    yzd=yzd.toFixed(3);
    return yzd;
}


//获取暂降类型暂降原因显示的值
function displayValue(data,eventValue) {
    if(eventValue>100){
        data="/";
    }
    return data;
}


//搜索表中的数据
function searchResult(value) {
    dataTable.search(value).draw();
}

//特殊处理，表头紧缩问题--start
var it=null;
function startQuery() {
    //实时刷新时间单位为毫秒
    it= setInterval('refreshQuery()',100);

}
/* 刷新查询 */
function refreshQuery(){
    var width=$("#vdlist").width();
    if(width>100){
        initTable(resultData);
        window.clearInterval(it)
    }
}
//特殊处理，表头紧缩问题--end


//点击导出按钮，根据用户选择的区域、时间节点去后台查询数据，下载所有范围内的数据包括波形
$("#downloadData").on("click",function () {
    var index;
    var area = $area.eq(0).attr("index");
    var startTime = $("#startTime").val();
    var endTime = $("#endTime").val();
    $.ajax({
        type : "POST",
        url : "/pqs9900/offdata/waveData",
        dataType : "json",
        beforeSend: function () {
            index = ityzl_SHOW_LOAD_LAYER();
        },
        data : {
            startTime : startTime,
            endTime : endTime,
            area:area
        },
        success : function(data) {
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(index);
            if(data.code===200){
                //前去下载波形
                location.href="/pqs9900/offdata/downWaveZip";
            }else{
                //异常信息提示
                layer.msg(data.message,{icon:2,time:2000});

            }
        }
    });
})

//点击导入按钮，用户选择本地的excel进行数据导入
$("#uploadData").on("click",function(){
    if(tiggleValue==="basicData"){
        //上传的是配置文件
        var indexC;
        layer.open({
            type:'1',
            title:"上传离线数据",
            shadeClose:true,
            resize:false,
            scrollbar:false,
            closeBtn:0,
            content:"<form class='ml5 mt15' enctype='multipart/form-data' id='uploadForm'> <div class='form-group'  > <input type='file' name='file' id='offdataFile'> </div></form>",
            btn:['确定','取消'],
            yes:function (index,layero) {
                var uploadEventFile=$("#offdataFile").val();

                /**
                 * xuyang
                 * 前端对所选文件的大小做个简单判断
                 */
                var uploadFile = document.getElementById("offdataFile").files;
                //文件大小
                var size = uploadFile[0].size;
                if (Math.floor(size/1024) <= 3072){
                    if(uploadEventFile === ''){
                        layer.msg("请选择Excel文件，再上传！",{icon:2,time:2000},function () {
                            layer.close(index);
                        });
                    }else if(uploadEventFile.lastIndexOf(".xls")<0){
                        layer.msg("只能上传Excel文件",{icon:2,time:2000},function () {
                            layer.close(index);
                        });
                    }else{
                        layer.confirm('确定导入？', function(index){
                            var formData = new FormData($('#uploadForm')[0]);
                            $.ajax({
                                method : "post",
                                url : "/pqs9900/offdata/uploadExcelData",
                                data :formData,
                                beforeSend: function () {
                                    indexC = ityzl_SHOW_LOAD_LAYER();
                                },
                                dataType:"json",
                                success : function(data) {
                                    ityzl_CLOSE_LOAD_LAYER(indexC);
                                    if(data.code===200){
                                        layer.msg('导入成功',{icon:1,time:2000},function () {
                                            layer.close(index);
                                        });
                                    }else{
                                        layer.msg(data.message,{icon:2,time:2000},function () {
                                            layer.close(index);
                                        });
                                    }
                                },
                                cache: false,
                                contentType: false,
                                processData: false
                            });
                        })
                    }
                }else {
                    layer.msg("上传失败,文件大小超过3M!",{icon:5,time:2000},function(){
                        layer.closeAll()});
                }
            },btn2: function(index, layero){
                layer.close(index);
            }
        })
    }else{
        //选择离线监测点，上传波形文件
        layer.open({
            type: 2,
            title: '导入波形',
            maxmin: false,
            resize:false,
            shadeClose: true, //点击遮罩关闭层
            area: ['100%', '100%'],
            content: 'offlinetree',
            scrollbar: false
        });
    }

})


//初始化复选框
function initCheckBox(){
    $(".checkbox").bootstrapSwitch({
        onText : "基础配置",      // 设置ON文本
        offText : "波形文件",    // 设置OFF文本
        onColor : "primary",// 设置ON文本颜色     (info/success/warning/danger/primary)
        offColor : "primary",  // 设置OFF文本颜色        (info/success/warning/danger/primary)
        size : "small",    // 设置控件大小,从小到大  (mini/small/normal/large)
        handleWidth:"50",//设置控件宽度
        // 当开关状态改变时触发
        onSwitchChange : function(event, state) {
            if (state == true) {
                tiggleValue="basicData";
            } else {
                tiggleValue="waveData";
            }
            //重新画图
        }
    });

    $(".off_line").bootstrapSwitch({
        onText : "在线",      // 设置ON文本
        offText : "离线",    // 设置OFF文本
        onColor : "primary",// 设置ON文本颜色     (info/success/warning/danger/primary)
        offColor : "primary",  // 设置OFF文本颜色        (info/success/warning/danger/primary)
        size : "small",    // 设置控件大小,从小到大  (mini/small/normal/large)
        handleWidth:"50",//设置控件宽度
        // 当开关状态改变时触发
        onSwitchChange : function(event, state) {
            if (state == true) {
                $('#off').hide()
                $('#online').show()
                type = 'online'
                var area = $area.eq(0).attr("index");
                var startTime = $startTime.eq(0).val();
                var endTime = $endTime.eq(0).val();
                refresh(area,startTime,endTime);
            } else {
                $('#online').hide()
                $('#off').show()
                type = 'offline'
                var area = $area.eq(0).attr("index");
                var startTime = $startTime.eq(0).val();
                var endTime = $endTime.eq(0).val();
                refresh(area,startTime,endTime);
            }
        }
    });

    //------------------------------------2021
    $('#addEvent').click(function () {
        layer.open({
            type: 2,
            title: "新增暂降事件",
            resize: false,
            shadeClose: true, //点击遮罩关闭层
            area: ['100%', '100%'],
            content: 'adddownevent',
            scrollbar: false
        })
    })


}


//上传波形文件
function uploadWave(lineIndex,eventDetailIndex,time){
    console.log(lineIndex)
    layer.open({
        type: 2,
        title: "上传波形文件",
        resize: false,
        shadeClose: true, //点击遮罩关闭层
        area: ['60%', '50%'],
        content: 'uploadwave?lineIndex='+lineIndex+"&eventDetailIndex="+eventDetailIndex+"&time="+time,
        scrollbar: false
    })
}
