/**
 * Created by yexb on 2017-08-02
 */
var color = null;
var deviceTable = null;
var thingTable = null;

function initInfo() {
    var endTime = getEndTime();
    var startTime = getMonthStartTime(endTime);

    $.ajax({
        type: "POST",
        data:{
            start: startTime,
            end: endTime
        },
        url: "/pqs9200/device/getMsgInfo",
        dataType: 'json',
        success: function (data) {
            var str1 = "<b style='font-size: 13px;color: #006565;'>" + data.body.name + "：</b>\n<b style='font-size: 12px;color: #006565;'>监测点数：" +
            data.body.pointCount + "</b>\n<b style='font-size: 12px;color: #006565;'>终端数：" + data.body.count + "</b>\n<b style='font-size: 12px;color: #006565;'>在线率：" + data.body.online + "</b>\n";
        var str2 = "<b style='font-size: 13px;color: #006565;'>" + "国网：</b>\n<b style='font-size: 12px;color: #006565;'>监测点数：" +
            data.body.gwPointCount + "</b>\n<b style='font-size: 12px;color: #006565;'>终端数：" + data.body.gwCount + "</b>\n<b style='font-size: 12px;color: #006565;'>在线率：" + data.body.gwOnline + "</b>";
        var str = data.body.count == 0 ? "" : str1;
        str += data.body.gwCount == 0 ? "" : str2;

        $("#msgInfo").html(str);
        }
    })
}

$(document).ready(function () {
    //初始化地图
    initMap();
//    initInfo();
    deviceError();
    getThings();


    //获取json文件中颜色的配色
    $.getJSON("../json/colorSetting.json", function (data) {
        color = data;
    });
});


function addNewEle(obj, name, colorName) {
    var li = document.createElement("li");
    var i = document.createElement("i");
    li.setAttribute("class", "list-group-item");
    li.setAttribute("style", "padding: 2px 2px;background-color:#d9edf7;color:" + colorName + ";");
    li.innerHTML = name;
    i.setAttribute("style", "width:20px;display: block;height: 0;float: left;margin-top:7px;margin-right: 5px;border-top: 2px solid " + colorName + ";");
    li.appendChild(i)
    obj.appendChild(li);
}

/********************************************
 JS初始化百度地图
 *******************************************/
var map;//地理信息地图
var blfirstload = true;//首次登录界面
var activemarker;//活跃的监测点
var activesearchInfoWindow = null;//活跃的InfoWindow
var activepoint = null;//活跃的InfoWindow(point)
var markerClusterer;//监测点聚合
var markers = [];//需要聚合的监测点
var polylineA, polylineB, polylineC;//不同电压等级对应的线路
var line_indexs;//获取监测点
//聚合Styles
var myStyles = [{
    url: '../images/img/clusterer30.png',
    size: new BMap.Size(40, 40),
    textColor: theme,
    opt_textSize: 10
}, {
    url: '../images/img/clusterer40.png',
    size: new BMap.Size(55, 55),
    textColor: theme,
    opt_textSize: 12
}, {
    url: '../images/img/clusterer50.png',
    size: new BMap.Size(70, 70),
    textColor: theme,
    opt_textSize: 14
}];

/********************************************
 初始化地图加载
 *******************************************/
function initMap() {
    map = getGISMap("rightContent", true, true, 12);

    /**********************************************
     用地图的加载事件（移动事件）涵盖所有新算法
     *********************************************/
    //地图加载完毕事件
    map.addEventListener("tilesloaded", function () {
        if (blfirstload) {
            AnalysisLineMaps(false);//监测点数据获取
            blfirstload = false;
        }
        controlMapElements(map);
    });

    //地图移动事件
    map.addEventListener("moveend", function () {
        controlMapElements(map);
    });


    //地图单击事件0、
    map.addEventListener("click", function () {
        if (activesearchInfoWindow != null) {
            activesearchInfoWindow.close();
        }
    });

    /***********************************
     1、220kV    显示等级10-15层 C
     2、110kV    显示等级12-14层  B
     3、10kV     显示等级10-12层 A
     **********************************/
    markerClusterer = new BMapLib.MarkerClusterer(map, {markers: markers});
    //更改一些参数设置
    markerClusterer.setGridSize(40);//GridSize
    markerClusterer.setMaxZoom(14);//maxZoom
    markerClusterer.setStyles(myStyles);//重新设置聚合类型
}


/********************************************
 归一化处理后重新刷新地图
 *******************************************/
function refreshDatabaseMap(blFlag) {
    parent.layer.msg("系统进行归一化处理，地图刷新请注意!", {icon: 5, time: 2000});
    if (activesearchInfoWindow != null) {
        activesearchInfoWindow.close();
    }
    AnalysisLineMaps(blFlag);
}

/********************************************
 来新的暂降事件时候刷新地图
 *******************************************/
function refreshRealMap(data) {
    parent.layer.msg("有新的暂降事情，地图刷新请注意!", {icon: 5, time: 2000});
    var strLineId = "";
    if (activesearchInfoWindow != null) {
        activesearchInfoWindow.close();
    }

    markerClusterer.removeMarkers(markers);
    $.each(data, function (index, item) {
        strLineId = item.lineid;
        for (var i = 0; i < markers.length; i++) {
            marker = markers[i];
            if (marker.index == strLineId) {
                refreshPointInfo(marker, i);
                break;
            }
        }
    });
    markerClusterer.addMarkers(markers);
}

//更新相对应的监测点
function refreshPointInfo(marker, index) {
    //获取监测点的地址
    var lineMap = marker.lineMap;
    lineMap.totalcount = lineMap.totalcount + 1;//存储未处理事件
    //移除监测点
    markers.splice(index, 1);
    //重新添加监测点
    markers.push(getPoint(lineMap, map, 0));
}

/********************************************
 终端状态改变后刷新地图
 *******************************************/
function refreshDevice(data) {
    parent.layer.msg("有终端状态变更，地图刷新请注意!", {icon: 5, time: 2000});
    var strLineId = "";
    if (activesearchInfoWindow != null) {
        activesearchInfoWindow.close();
    }

    markerClusterer.removeMarkers(markers);
    $.each(data, function (index, item) {
        strLineId = item.lineid;
        for (var i = 0; i < markers.length; i++) {
            marker = markers[i];
            if (marker.index == strLineId) {
                refreshDeviceInfo(marker, i, item.devflag, item.status);
                break;
            }
        }
    });
    markerClusterer.addMarkers(markers);
}

//更新相对应的终端状态
function refreshDeviceInfo(marker, index, devflag, status) {
    //获取监测点的地址
    var lineMap = marker.lineMap;
    lineMap.devflag = devflag;//终端状态
    lineMap.status = status;//通讯状态
    //移除监测点
    markers.splice(index, 1);
    //重新添加监测点
    markers.push(getPoint(lineMap));
}

/********************************************
 获取所有监测点信息
 *******************************************/
var gisinfo = new Object();

function AnalysisLineMaps(blFlag) {
    markerClusterer.removeMarkers(markers);
    markers = [];
    //假如是已经有了波形，则清空后再加载
    if (blFlag && Object.keys(gisinfo).length > 0) {
        for (var i = 0; i < gisinfo.subMarkers.length; i++) {
            map.removeOverlay(subMarkers[i]);
        }

        for (var i = 0; i < gisinfo.subpointLines.length; i++) {
            map.removeOverlay(subpointLines[i]);
        }
        var dataarr = parent.parent.getLineMaps(blFlag, false);
        //把数据打到地图上去，供电公司，监测点，供电公司跟监测点连线
        gisinfo = drawElement(dataarr, map, 0);

        markers = gisinfo.pointMarkers;
        markerClusterer.addMarkers(markers);

        //查询时候增加查询条件
        var availableTags = [];
        for (var i = 0; i < markers.length; i++) {
            marker = markers[i];
            availableTags.push(marker.name);
        }

        $("#input_searchpoint").autocomplete({
            source: availableTags
        });
    }
    //假如首次加载，则读取数据
    else {
        $.ajax({
            type: "POST",
            async: true,
            url: "/pqs9200/overview/getLineMaps",
            dataType: "text",
            success: function (data) {
                var info = $.parseJSON(data);
                var dataarr = null;
                if (info != null) {
                    //取数据失败，则进行不进行操作
                    if (info.code == 500) {
                        parent.layer.msg(info.message, {icon: 5, time: 2000});
                    } else {
                        if (info.body != null) {
                            //开始遍历所有的数据,这里最终是Map,由key和value组成的
                            dataarr = getDataOffset(info.body);
                        }
                    }
                }
                //把数据打到地图上去，供电公司，监测点，供电公司跟监测点连线
                gisinfo = drawElement(dataarr, map, 0);

                markers = gisinfo.pointMarkers;
                markerClusterer.addMarkers(markers);

                //查询时候增加查询条件
                var availableTags = [];
                for (var i = 0; i < markers.length; i++) {
                    marker = markers[i];
                    availableTags.push(marker.name);
                }

                $("#input_searchpoint").autocomplete({
                    source: availableTags
                });
            }
        });
    }


    //changeIcon();
}

/************************************
 打开检测点
 ************************************/
function openmonitor(tmpline_index) {
    if (window.top.document.getElementById(dataPoint) != null) {
        window.top.addTab(dataPoint, '监测点');

        window.top.document.getElementById(dataPoint).contentWindow.zTreeOnAsyncSuccess(tmpline_index);
    } else if (window.top.document.getElementById('monitor') != null) {
        window.top.addTab('monitor', '监测点');
        window.top.document.getElementById('monitor').contentWindow.zTreeOnAsyncSuccess(tmpline_index);
    } else {
        window.top.addTab('monitor?line_index=' + tmpline_index, '监测点');
        dataPoint = 'monitor?line_index=' + tmpline_index;

        window.parent.parent.document.getElementById('dataPoint').value = dataPoint;
    }
}

/************************************
 查找未处理事件
 ************************************/
function openSagEvents(tmpline_index, totalcount) {
    if (totalcount > 0) {
        //双击事件的执行代码
        querySagEvents(tmpline_index);
    } else {
        parent.layer.msg("该监测点未找到未处理暂降事件", {icon: 6, time: 2000});
    }
}

/************************************
 前台按钮事件
 ************************************/
function divinfoopen() {
    var divinfo = document.getElementById("msgInfo");
    divinfo.style.display = "";
    var btnshrinkinfo = document.getElementById("btnshrinkinfo");
    btnshrinkinfo.style.display = "";
    var btnopeninfo = document.getElementById("btnopeninfo");
    btnopeninfo.style.display = "none";
}

function divinfoclose() {
    var divinfo = document.getElementById("msgInfo");
    divinfo.style.display = "none";

    var btnshrinkinfo = document.getElementById("btnshrinkinfo");
    btnshrinkinfo.style.display = "none";
    
    var btnopeninfo = document.getElementById("btnopeninfo");
    btnopeninfo.style.display = "";
}

function divdangerMouseOver() {
    var divinfo = document.getElementById("divdanger");
    divinfo.style.display = "";
}

function divdangerMouseOut() {
    var divinfo = document.getElementById("divdanger");
    divinfo.style.display = "none";
}

//展开div
function expandiv() {
    var divevent = document.getElementById("divevent");
    divevent.style.display = "";

    var divexpan = document.getElementById("divexpan");
    divexpan.style.display = "none";
}

//收缩div
function shrinkdiv() {
    var divevent = document.getElementById("divevent");
    divevent.style.display = "none";

    var divexpan = document.getElementById("divexpan");
    divexpan.style.display = "";
}


/************************************
 获取未处理暂降事件列表
 ************************************/
function querySagEvents(line_index) {
    var obj = new Object();
    var arr = [];
    obj.lineId = line_index;
    arr.push(obj);
    line_indexs = line_index;
    $.ajax({
        type: 'POST',
        dataType: "json",
        data: {
            queryCondition: JSON.stringify(arr)
        },
        url: '/pqs9200/advanced/querySagEventss',
        success: function (data) {
            var divevent = document.getElementById("divevent");
            divevent.style.display = "";

            var divexpan = document.getElementById("divexpan");
            divexpan.style.display = "none";

            processSagData(data);
        },
        error: function () {
            //layer.msg("暂降事件列表查询失败！");
            var divevent = document.getElementById("divevent");
            divevent.style.display = "none";

            var divexpan = document.getElementById("divexpan");
            divexpan.style.display = "none";

            initTableBtn($('#example'), [], 8, '波形分析');
        }
    });
}

/*
 * 处理暂降事件数据
 */
function processSagData(data) {
    // 空值判断
    if (data.length == 0) {
        initTableBtn($('#example'), data, 8, '波形分析');
        return;
    }

    var tableData = [];
    var offset = 0;
    processData = [];
    while (offset < data.object.list.length) {
        // 后台返回到前台的表格数据
        tableData += '["' + data.object.list[offset].indexEventDetail + '","'
            + (offset + 1).toString() + '","' + data.object.list[offset].strTime
            + '","' + data.object.list[offset].strPersist + '","'
            + data.object.list[offset].strEventValue + '","'
            + data.object.list[offset].plantInfo.nameGD + '","'
            + data.object.list[offset].plantInfo.nameBD + '","'
            + data.object.list[offset].plantInfo.namePoint + '","' + '' + '"],';

        // 事件关联处理，传送到后台数据
        var obj = new Object();
        obj.msec = data.object.list[offset].msec;
        obj.strTime = data.object.list[offset].strTime;
        obj.time = data.object.list[offset].time;
        obj.sagTime = data.object.list[offset].sagTime;
        obj.indexPoint = data.object.list[offset].plantInfo.indexPoint;
        processData.push(obj);

        offset++;
    }
    /*
     * 去除最右边',' string转json
     */
    tableData = tableData.substring(0, tableData.lastIndexOf(','));
    tableData = eval('[' + tableData + ']');
    objTable = initTableBtn($('#example'), tableData, 8, '波形分析');
}

/*
 * 行内按钮 obj:表格对象 tableData:表格数据 nIndex:按钮添加的列 nameBtn:按钮名称
 */
function initTableBtn(obj, tableData, nIndex, nameBtn) {
    var oTable = obj
        .DataTable({
            scrollX: true,
            data: tableData,
            lengthChange: false,
            info: false,
            paging: false,
            ordering: false,
            lengthChange: false,
            searching: false,
            bDestroy: true,
            columnDefs: [{
                targets: [0],
                visible: false
            }],
            language: {
                url: '../json/Chinese.json'
            },
            'fnDrawCallback': function (oTable) {
                $("#example_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 = $("#example").dataTable();
                $('#dataTable-btn').click(function (e) {
                    if ($("#changePage").val() && $("#changePage").val() > 0) {
                        var redirectpage = $("#changePage").val() - 1;
                    } else {
                        var redirectpage = 0;
                    }
                    table.fnPageChange(redirectpage);
                });
            },
        });

    return oTable;
}

/*****************************
 画线
 *****************************/
function drawline(data) {
    var pointlineA = new Array();
    var pointlineB = new Array();
    var pointlineC = new Array();

    var number;
    //开始遍历所有的数据
    for (var i = 0; i < data.length; i++) {
        var gridtop = data[i];
        //电压等级
        switch (gridtop.volLevel) {
            case 0:
                pointlineA[i] = new BMap.Point(gridtop.longItude, gridtop.latItude);
                number = i;
                break;
            case 1:
                pointlineB[i - number - 1] = new BMap.Point(gridtop.longItude, gridtop.latItude);
                break;
            case 2:
                break;
        }
    }

    if (pointlineA.length > 0) {
        polylineA = new BMap.Polyline(pointlineA, {strokeColor: color['110kV'], strokeWeight: 3, strokeOpacity: 0.8});//定义折线
        map.addOverlay(polylineA);
    }

    if (pointlineB.length > 0) {
        polylineB = new BMap.Polyline(pointlineB, {strokeColor: color['10kV'], strokeWeight: 3, strokeOpacity: 0.8});//定义折线
        map.addOverlay(polylineB);

        polylineC = new BMap.Polyline(pointlineB, {strokeColor: color['220kV'], strokeWeight: 3, strokeOpacity: 0.8});//定义折线
        map.addOverlay(polylineC);
    }
}

/*****************************
 根据输入的监测点名称进行查询
 *****************************/
var searchPointVal = "";

function searchPoint(type) {
    var searchPoint = document.getElementById('input_searchpoint');
    if (type === 1) {
        searchPoint.value = searchPointVal;
    }
    if (searchPoint.value != "") {
        var marker;
        var blFlag = false;
        var points = [];
        for (var i = 0; i < markers.length; i++) {
            marker = markers[i];
            //先匹配是否有全名称的
            if (marker.name === searchPoint.value) {
                blFlag = true;
                points = [];
                points.push(marker.getPosition());
                break;
            } else if (marker.name.indexOf(searchPoint.value) >= 0) {
                blFlag = true;
                points.push(marker.getPosition());
            }
        }
        if (blFlag) {
            map.centerAndZoom(points[0], 15);
            marker.searchInfoWindow.open(points[0]);
            activesearchInfoWindow = marker.searchInfoWindow;
            activepoint = points[0];
        }
        if (!blFlag) {
            parent.layer.msg("未找到符合条件监测点!", {icon: 5, time: 2000});
        }
    } else {
        parent.layer.msg("请输入监测点名称!", {icon: 5, time: 2000});
    }
}

/*****************************
 Enter
 *****************************/
document.onkeydown = function (event) {
    var e = event || window.event || arguments.callee.caller.arguments[0];
    // enter键
    if (e && e.keyCode == 13) {
        searchPoint(0);
    }
};
$("#query").click(function () {
    window.top.addTab('relevances?line_index=' + line_indexs, '事件关联分析处理')
});

var $height = document.body.clientHeight * 0.4 - 20;
var $height1 = document.body.clientHeight * 0.3 - 20;

function deviceError() {
    $.ajax({
        type: "POST",
        url: "/pqs9200/device/getSbyc",
        dataType: "text",
        success: function (data) {
            var tableData = [];
            var info = $.parseJSON(data);

            if (info.code === 200) {
                var JSONObj = '';

                $.each(info.body, function (index, item) {
                    if (index + 1 == info.body.length) {
                        JSONObj += str2JSON(index + 1, item[9], item[0],
                            item[3], item[6]);
                        return false;
                    }

                    JSONObj += str2JSON(index + 1, item[9], item[0],
                        item[3], item[6]) + ',';
                });

                tableData = eval('[' + JSONObj + ']');
            }

            deviceTable = $("#deviceError").DataTable({
                data: tableData,
                paging: false,
                scrollY: $height1,
                scrollCollapse: false,
                lengthChange: false,
                searching: false,
                destroy: true,
                info: false,
                ordering: false
                , columns: [
                    {"width": "12%"},
                    {"width": "28.5%"},
                    {"width": "20.6%"},
                    {"width": "20.6%"},
                    {"width": "18.8%"}
                ]
                , language: {
                    url: '/pqs9200/json/chine.json'
                },
                "createdRow": function (row, data, index) {
                    if (data[2].length > 6) {
                        var realValue = data[2];
                        var s = data[2].substr(0, 6) + '...';
                        $('td', row).eq(2).prevObject[2].innerHTML = "<span title='" + realValue + "'>" + s + "</span>";
                    }

                    if (data[3].length > 6) {
                        var realValue = data[3];
                        var s = data[3].substr(0, 6) + '...';
                        $('td', row).eq(3).prevObject[3].innerHTML = "<span title='" + realValue + "'>" + s + "</span>";
                    }
                }
            });
        }
    });
}

function getThings() {
    $.ajax({
        type: "POST",
        url: "/pqs9200/area/getZjsj",
        dataType: "text",
        success: function (data) {
            var tableData = [];
            var info = $.parseJSON(data);

            if (info.code === 200) {
                var JSONObj = '';

                $.each(info.body, function (index, item) {
                    if (index + 1 == info.body.length) {
                        JSONObj += str2JSON(index + 1, item[1], item[0],
                            item[3], item[2]);
                        return false;
                    }

                    JSONObj += str2JSON(index + 1, item[1], item[0],
                        item[3], item[2]) + ',';
                });

                tableData = eval('[' + JSONObj + ']');
            }

            thingTable = $("#things").DataTable({
                data: tableData,
                paging: false,
                scrollY: $height,
                scrollCollapse: false,
                lengthChange: false,
                searching: false,
                destroy: true,
                info: false,
                ordering: false,
                columns: [
                    {"width": "11.8%"},
                    {"width": "27.9%"},
                    {"width": "15.2%"},
                    {"width": "25.4%"},
                    {"width": "19.6%"}
                ],
                language: {
                    url: '/pqs9200/json/chine.json'
                },
                "createdRow": function (row, data, index) {
                    if (data[2].length > 6) {
                        var realValue = data[2];
                        var s = data[2].substr(0, 6) + '...';
                        $('td', row).eq(2).prevObject[2].innerHTML = "<span title='" + realValue + "'>" + s + "</span>";
                    }
                }
            });
        }
    });
}

function str2JSON(str1, str2, str3, str4, str5) {
    var JSONstr = '["' + str1 + '","' + str2
        + '","' + str3 + '","' + str4
        + '","' + str5 + '"]';
    return JSONstr;
}

$('#things').on("click", "tr", function () {
    if (thingTable != null) {
        thingTable.$('tr.selected').removeClass('selected');
        $(this).addClass('selected');
        var item = thingTable.row($(this).closest('tr')).data();
        searchPointVal = item[2];
        searchPoint(1);
    }
});

$("#exportData").on("click", function () {
    var xhr = new XMLHttpRequest();
    xhr.open('post', '/pqs9200/device/downloadExcel', true);
    xhr.responseType = 'blob';
    xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
    var i = ityzl_SHOW_LOAD_LAYER();
    var commontParamter = {};
    commontParamter.area = '';
    commontParamter.startTime = '';
    commontParamter.endTime = '';
    xhr.send(JSON.stringify(commontParamter));
    xhr.onload = function () {
        if (this.status === 200) {
            var blob = this.response;
            var a = document.createElement('a');
            var url = window.URL.createObjectURL(blob);
            a.href = url;
            //设置文件名称
            a.download = '概览.xlsx';
            a.click();
            a.remove();
        }

        ityzl_CLOSE_LOAD_LAYER(i);
    }
});

function getEndTime() {
    var now = new Date();
    var sep = "-";
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    if (month < 10) {
        month = "0" + month;
    }
    var date = now.getDate();
    if (date < 10) {
        date = "0" + date;
    }
    // 拼接当前的日期
    var endTime = year + sep + month + sep + date;
    return endTime;
}

// 获取起始日期
function getStartTime(endTime) {
    var sep = "-";
    var arr = endTime.split("-");
    var year = arr[0];
    var month = "01";
    var date = "01";
    var startTime = year + sep + month + sep + date;
    return startTime;
}