var mapEvent, loadingItem;
var load = 0;
var total = 0;
var color;
var companyname;

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

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 str0 = "<b style='font-size: 13px;color:" + color + ";'>" + "统计时间：" +
                "</b>\n<b style='font-size: 12px;color: " + color + ";'>&nbsp;&nbsp;" + startTime + "至" + endTime + "</b>\n";
            var str1 = "<b style='font-size: 13px;color:" + color + ";'>" + data.body.name +
                ":</b>\n<b style='font-size: 12px;color:" + color + ";'>&nbsp;&nbsp;监测点数:" + data.body.pointCount +
                "</b>\n<b style='font-size: 12px;color: " + color + ";'>&nbsp;&nbsp;终端数：" + data.body.count +
                "</b>\n<b style='font-size: 12px;color: " + color + ";'>&nbsp;&nbsp;在线率：" + data.body.online + "%</b>\n";
            var str2 = "<b style='font-size: 13px;color: " + color + ";'>" + companyname +
                "</b>\n<b style='font-size: 12px;color: " + color + ";'>&nbsp;&nbsp;监测点数：" + data.body.gwPointCount +
                "</b>\n<b style='font-size: 12px;color: " + color + ";'>&nbsp;&nbsp;终端数：" + data.body.gwCount +
                "</b>\n<b style='font-size: 12px;color: " + color + ";'>&nbsp;&nbsp;在线率：" + data.body.gwOnline + "%</b>\n";
            var str = str0;
            str += data.body.count == 0 ? "" : str1;
            str += data.body.gwCount == 0 ? "" : str2;

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

$(document).ready(function () {
    $.ajax({
        type: "POST",
        url: "/pqs9200/theme/getThemeInfo",
        async: false,
        dataType: 'json',
        success: function (data) {
            color = data.body.value;
            companyname = data.body.name;
        }
    })

    initInfo();

    var t1 = getRole("/pqs9200/business/sbyxzt");
    var t2 = getRole("/pqs9200/business/dlxxt");
    var t3 = getRole("/pqs9200/business/qypg");
    var t4 = getRole("/pqs9200/business/qygk");

    var index = 0;

    addIndex(t1, "#item0");
    addIndex(t2, "#item1");
    addIndex(t3, "#item2");
    addIndex(t4, "#item3");

    function addIndex(t, str) {
        if (t1 + t2 + t3 + t4=== 1) {
            index = 1;
        }

        if (t == 1) {
            $(str).addClass("item" + index);
            index++;
        }
    }

    total = t1 + t3 + t4;

    startQuery();
    loadingItem = ityzl_SHOW_LOAD_LAYER();

    if (t2 == 1) {
        getGISMap("map", false, false, 12);
    }

    // 初始化图表以及表格数据
    var endTime = getEndTime();
    var startTime = getMonthStartTime(endTime);
    // 初始化区域页面图标
    if (t4 == 1) {
        $.ajax({
            type: "POST",
            url: "/pqs9200/area/getGeneralData",
            dataType: "text",
            data: {
                startTime: startTime,
                endTime: endTime
            },
            success: function (data) {
                load = load + 1;
                var info = $.parseJSON(data);
                if (info.code === 500) {
                    // 区域
                    initSagEvent(null);
                } else {
                    // 区域
                    initSagEvent(info.body.area);
                }
            }
        });
    }
    // 初始化终端状态的图表
    if (t1 == 1) {
        $.ajax({
            type: "POST",
            url: "/pqs9200/overview/deviceStatus",
            dataType: "text",
            data: {
                startTime: startTime,
                endTime: endTime
            },
            success: function (data) {
                load = load + 1;
                var info = $.parseJSON(data);
                if (info.code === 500 || info.code === null) {
                    // 区域
                    initRun(null);
                } else {
                    // 区域
                    initRun(info.body.area);
                }
            }
        });
    }

    // 初始化监测网分布
    if (t3 == 1) {
        $.ajax({
            type: "POST",
            url: "/pqs9200/area/getDevMap",
            dataType: "text",
            data: {},
            success: function (data) {
                load = load + 1;
                var info = $.parseJSON(data);
                if (info.code == 500) {
                    initDevMap(null);
                } else {
                    initDevMap(info.body.maps);
                }
            }
        });
    }

    //绑定点击跳转
    $('ul').on('click', '.item1 .item-content', function () {
        var endTime = getEndTime();
        var startTime = getMonthStartTime(endTime);
        var id = $(this).prop("id");
        var title = $(this).prop("title");
        if (id !== '') {
            if (id === 'map') {
                id = 'dlxxt';
                title = "地理信息与电网拓扑图";
            } else if (id === "run") {
                id = 'sbyxzt';
                title = "终端运行统计" + getTitleInfoDeviceStatus(startTime, endTime);
            } else if (id === "sagevent") {
                id = 'qygk';
                title = "区域暂降事件统计";
            } else if (id === "qypg") {
                id = 'qypg';
                title = "区域暂降评估" + getTitleInfo(startTime, endTime);
            }
            onContent(id, title);
        }
    });
});

//根据跳转页面
function onContent(id, title) {
    layer.open({
        id: 'overview',
        type: 2,
        title: title,
        resize: false,
        shadeClose: true, //点击遮罩关闭层
        area: ['100%', '100%'],
        content: id,
        scrollbar: false
    });
}


//获取layer打开新页面后，在标题添加内容并向右浮动
function getTitleInfo(startTime, endTime) {
    startTime = startTime.replace(/-/g, '/');
    endTime = endTime.replace(/-/g, '/');
    return "<span  class='fr font12' ><span class='fr font12'>统计时间：<span class='fontBold' >" + startTime + "-" + endTime + "</span></span>";
}

//获取layer打开新页面后，在标题添加内容并向右浮动
function getTitleInfoDeviceStatus(startTime, endTime) {
    startTime = startTime.replace(/-/g, '/');
    endTime = endTime.replace(/-/g, '/');
    return "<span  class='fr font12 fontBold' > 终端在线率(右柱) <span class='info'><span  class='inB bg-info smallBlock'></span> 在线率≥90%</span><span class='warn''> " +
        "<span class='inB bg-warn smallBlock'></span>" +
        " 60%≤在线率<90% </span><span class='error'> <span class='inB bg-error smallBlock'></span> 在线率" +
        "<60%</span> </span><span class='fr font12 fontBold'>终端状态(左柱) <span class='run'><span  class='inB bg-run smallBlock'></span> 投运 </span><span class='breaks'><span  class='inB bg-breaks smallBlock'></span> 检修 </span><span class='grey'><span  class='inB bg-grey smallBlock'></span> 退运 &nbsp;</span></span><span class='fr font12 '><span class='fontBold'>统计时间：</span><span class='' >" + startTime + "-" + endTime + "&nbsp;</span></span>";

}


function initDevMap(data) {
    //给div指定宽高
    var mapnor = [];
    var mapbre = [];
    var tmpmap = {};
    if (data != null) {
        for (var i = 0; i < data.length; i++) {
            // 获取变电站名称（key，由变电站名称，经度，纬度组成：事例：变电站1,123.00,135.00）
            var key = data[i].subname + "," + data[i].longitude + ","
                + data[i].latitude;
            // 假如key已经存在了
            if (tmpmap[key]) {
                var tmpdata = tmpmap[key];
                tmpdata.push(data[i]);
            } else {
                var tmpdata = [];
                tmpdata.push(data[i]);
                tmpmap[key] = tmpdata;
            }
        }
    }

    // 根据分组后的监测点进行偏移算法
    var r = 0.035;
    for (tmpkey in tmpmap) {
        var arr = tmpmap[tmpkey];
        var tmplength = arr.length;
        var norarr = [];
        var brearr = [];
        for (var i = 0; i < tmplength; i++) {
            var info = arr[i];
            var datatmp = [];
            info.longitude = (info.longitude + r
                * Math.cos(2 * Math.PI * (i) / tmplength)).toFixed(3);
            info.latitude = (info.latitude + r
                * Math.sin(2 * Math.PI * (i) / tmplength)).toFixed(3);
            datatmp = [info.longitude, info.latitude];
            if (info.status == 1) {
                mapnor.push({
                    value: datatmp,
                    itemStyle: {
                        normal: {
                            color: green
                        }
                    }
                });
            } else {
                mapbre.push({
                    value: datatmp,
                    itemStyle: {
                        normal: {
                            color: red
                        }
                    }
                });
            }
        }
    }

    echarts.dispose($("#qypg")[0]);
    var dom = document.getElementById("qypg");
    var devmapChart = echarts.init(dom);
    $.ajaxSettings.async = false;
    var pNode, node;
    $.ajax({
        url: '/pqs9200/area/getMapInfo',
        type: 'post',
        data: {
            area: "overview"
        },
        async: false,
        dataType: 'json',
        success: function (data) {
            pNode = data.body.name;
            node = data.body.subName;
        }
    })
    // $.ajax({
    //     url: '/pqs9200/area/getBaseMapInfo',
    //     type: 'post',
    //     data: {
    //         area: getMapUrl(pNode)
    //     },
    //     async: false,
    //     dataType: 'json',
    //     success: function (data) {
    //         console.log(data)
    //     }
    // })
    var geoJson = getFullMapData(pNode, node);
    echarts.registerMap('监测网分布', geoJson);
    var option = {
        backgroundColor: canvasBG,
        title: {
            text: '区域暂降评估',
            left: 'center'
        },
        legend: {
            data: ['正常', '中断'],
            x: 'left',
            y: 'bottom',
            orient: 'vertical',
            show: true,
            selectedMode: false
        },
        geo: {
            map: '监测网分布',
            itemStyle: {
                normal: {
                    areaColor: '#CCCCCC',
                    borderColor: 'dodgerblue'
                }
            },
            label: {
                normal: {
                    show: true,
                    textStyle: {
                        color: 'black',
                        fontSize: 10
                    }
                }
            },
            roam: false
        },
        series: [{
            name: '正常',
            type: 'scatter',
            coordinateSystem: 'geo',
            data: mapnor,
            symbolSize: 5
        }, {
            name: '中断',
            type: 'scatter',
            coordinateSystem: 'geo',
            data: mapbre,
            symbolSize: 5
        }],
        color: [green, red]
    };
    devmapChart.setOption(option, true);
}


/*******************************************************************************
 * 归一化处理后重新刷新地图
 ******************************************************************************/
function refreshDatabaseMap(blFlag) {
    var frameId = document.getElementById('dlxxt').getElementsByTagName(
        "iframe")[0].id;
    if (document.getElementById(frameId) != null) {
        document.getElementById(frameId).contentWindow
            .refreshDatabaseMap(blFlag);
    }
}

/*******************************************************************************
 * 来新的暂降事件时候刷新地图
 ******************************************************************************/
function refreshRealMap(data) {
    var frameId = document.getElementById('dlxxt').getElementsByTagName(
        "iframe")[0].id;
    if (document.getElementById(frameId) != null) {
        document.getElementById(frameId).contentWindow.refreshRealMap(data);
    }
}

/*******************************************************************************
 * 终端状态改变后刷新地图
 ******************************************************************************/
function refreshDevice(data) {
    var frameId = document.getElementById('dlxxt').getElementsByTagName(
        "iframe")[0].id;
    if (document.getElementById(frameId) != null) {
        document.getElementById(frameId).contentWindow.refreshDevice(data);
    }
}

$(function () {
    $('#dg-container').gallery();
    $('.dg-prev,.dg-next').on(
        'click',
        function () {
            $('.dg-wrapper').find('.dg-center').each(
                function () {
                    if ($(this).hasClass('current')) {
                        var currentIndex = $(this).index();
                    }
                    $('.dg-sub').find('b').eq(currentIndex).addClass(
                        'red').siblings().removeClass('red');
                    ;
                })
        })
});


// 获取当前日期，精确到日
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;
}

/**
 * 设备运行状态缩略图绘制
 * **/
function initRun(area) {
    $("#run").css("height", $("li").height());
    $("#run").css("width", $("li").width());
    var normal = [];
    var breaks = [];
    var shutdown = [];
    var areas = [];
    var rate = [];
    if (null != area) {
        if (area.length > 8) {
            area = area.slice(0, 8);
        }
        for (var i = 0; i < area.length; i++) {
            areas[i] = area[i].name + "\n(" + area[i].amounts + ")";
            var monitors = area[i].amounts;
            if (Number(monitors) === 0) {
                var singleData = {};
                var item = {};
                singleData.value = 3.1415;
                item.color = noMonitor;
                singleData.itemStyle = item;
                normal[i] = singleData;
                rate[i] = singleData;
                breaks[i] = 0;
                shutdown[i] = 0;
            } else {
                normal[i] = area[i].status.normal;
                breaks[i] = area[i].status.breaks;
                shutdown[i] = area[i].status.shutdown;
                var onlineRate;
                onlineRate = Number(area[i].online);
                var singleData = {};
                var normalTemp = {};
                var itemStyle = {};
                normalTemp.color = getColor(onlineRate);
                if (onlineRate < 3.1414) {
                    singleData.value = 3.1415;
                    //item.actual = onlineRate;
                } else {
                    singleData.value = onlineRate;
                }
                itemStyle.normal = normalTemp;
                singleData.itemStyle = itemStyle;
                rate[i] = singleData;
            }
        }
    }
    var option = {
        backgroundColor: canvasBG,
        title: {
            text: '终端运行统计',
            left: '46%'
        },
        color: [runColor, breaksColor, grey],
        grid: {
            left: '1%',
            right: '13%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            name: '地区\n(终端个数)',
            splitLine: {
                show: false
            },
            axisLabel: {
                show: true,
                interval: 0
            }
        }],
        yAxis: [{
            type: 'value',
            name: '%',
            nameLocation: 'center',
            max: 100
        }],
        series: [{
            name: '正常',
            type: 'bar',
            stack: 'sum',
            barMaxWidth: barMax,
            data: normal
        }, {
            name: '检修',
            type: 'bar',
            stack: 'sum',
            barMaxWidth: barMax,
            data: breaks
        }, {
            name: '退运',
            type: 'bar',
            stack: 'sum',
            barMaxWidth: barMax,
            data: shutdown
        }, {
            name: '在线率',
            type: 'bar',
            barGap: 0,
            barMaxWidth: barMax,
            data: rate
        }]
    };
    echarts.dispose($("#run")[0]);
    var run = echarts.init($("#run")[0]);
    run.setOption(option);
}

/**
 * 区域暂降事件次数统计图绘制
 ***/
function initSagEvent(area) {
    $("#sagevent").css("height", $("li").height());
    $("#sagevent").css("width", $("li").width());
    var areas = [];
    var times = [];
    if (area != null) {
        if (area.length > 8) {
            area = area.slice(0, 8);
        }
        for (var i = 0; i < area.length; i++) {
            areas[i] = area[i].city + "\n(" + area[i].amounts + ")";
            times[i] = area[i].times;
        }
    }
    var option = {
        backgroundColor: canvasBG,
        title: {
            text: '暂降事件统计',
            x: 'center'
        },
        color: [orange],
        legend: {
            data: ['统计次数'],
            selectedMode: false,
            x: 'left'
        },
        grid: {
            left: '1%',
            right: '13%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            splitLine: {
                show: false
            },
            name: '地区\n(监测点数)',
            axisLabel: {
                show: true,
                interval: 0
            }
        }],
        yAxis: [{
            type: 'value',
            name: '(次)'
        }],
        series: [{
            name: '统计次数',
            type: 'bar',
            itemStyle: {
                normal: {
                    label: {
                        show: true,
                        textStyle: {
                            color: purple
                        }
                    }
                }
            },
            data: times,
            barMaxWidth: barMax
        }]
    };
    echarts.dispose($("#sagevent")[0]);
    var district = echarts.init($("#sagevent")[0]);
    district.setOption(option);
}


function divdangerMouseOver() {
    var frameId = document.getElementById('balanceView').getElementsByTagName(
        "iframe")[0].id;
    $('#' + frameId)[0].contentWindow.divdangerMouseOver();
}

function divdangerMouseOut() {
    var frameId = document.getElementById('balanceView').getElementsByTagName(
        "iframe")[0].id;
    $('#' + frameId)[0].contentWindow.divdangerMouseOut();
}

var it = null;

function startQuery() {
    //实时刷新时间单位为毫秒
    it = setInterval('refreshQuery()', 100);
}

/* 刷新查询 */
function refreshQuery() {
    if (load === total) {
        ityzl_CLOSE_LOAD_LAYER(loadingItem);
        window.clearInterval(it)
    }
}


//根据在线率获取颜色
function getColor(data) {
    if (data >= 90) {
        return green;
    } else if (data === 3.1415) {
        return noMonitor;
    } else if (data === 3.14159) {
        return noData;
    } else if (data < 60) {
        return red;
    } else {
        return yellow;
    }
}
