var cityName, areaImage, volImage, disImage, picHeight, generalData, areaInfo = [],total,status;
//判断地区可否点击
var areaAble;
//返回上一级按钮是否显示
var backAble;
var $area = $("#area");
var $startTime = $("#startTime");
var $endTime = $("#endTime");
$("#interval").val("月份");
$(document).ready(function () {
    picHeight = ($(window).height() - 100) * 0.5;
    //初始化区域
    $.ajax({
        type: "POST",
        url: "/pqs9200/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);
            //初始化页面内容
            areaInfo = 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);
});

//省级用户点击城市
function getPointData(name) {
    name = name.replace(/(^\s*)|(\s*$)/g, '');
    name = name.substring(0, name.indexOf("("));
    name = name.replace(/(^\s*)|(\s*$)/g, '');
    var area = getDeptsIndex(name);
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    refresh(area, startTime, endTime);
}


//后台获取数据
function refresh(area, startTime, endTime) {
    var zTree = $.fn.zTree.getZTreeObj("areaTree");
    var node=zTree.getNodeByParam('id',area);
    if(node.level!==0){
        zTree.expandAll(true);
    }
    var idea;
    $.ajax({
        type: "POST",
        url: "/pqs9200/area/getCityTotalTimes",
        dataType: "json",
        data: {
            area: area,
            startTime: startTime,
            endTime: endTime
        },
        beforeSend: function () {
            idea = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (info) {
            total = info.body.totalTimes;
            status = info.body.status;
            $("#area").val(getDeptsName(area));
            $("#area").attr("index", area);
            zTree.cancelSelectedNode();
            zTree.selectNode(node,true);
            //显示正确区域
            generalData = info;
            startQuery();
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(idea);
        }

    });
}

/**
 * 区域表格
 * */
function initArea(areaList) {
    if (areaList == null) {
        areaList = [];
    } else {
        //计算总计
        var city = '总计';
        var amounts = 0;
        var times = 0;
        for (var i = 0; i < areaList.length; i++) {
            amounts = areaList[i].amounts + amounts;
            //times = areaList[i].times + times;
        }
        times = total;
        var area = {};
        area.city = city;
        area.amounts = amounts;
        if (status === "1"){
            area.times = times + '(自定义部门和非自定义部门的去重数据)';
        } else {
            area.times = times;
        }
        area.dicIndex = "/";
        areaList.push(area);
        areaList.reverse();
    }
    $("#areaTable").DataTable({
        data: areaList,
        autoWidth: false,
        order: [1, "desc"],
        columnDefs: [{
            orderable: false,
            targets: [0]
        },
            {
                "width": "25%", "targets": 0, render: function (data, type, full, meta) {
                    var name = $area.find("option:selected").text();
                    var data = data;
                    if (name === data) {
                        data = '<span style="font-weight:bold">' + data + '</span>'
                    }
                    return data;
                }
            },
            {"width": "25%", "targets": 1},
            {"width": "25%", "targets": 2},
            {"width": "25%", "targets": 3}
        ],
        paging: true,
        lengthChange: false,
        searching: false,
        destroy: true,
        pageLength: 10,
        language: {
            url: '/pqs9200/json/chine.json',
        },
        columns: [
            {data: 'city'},
            {data: 'amounts'},
            {data: 'times'},
            {data: 'dicIndex'}
        ]
    })
}

/**
 * 电压等级表格
 * */
function initValtageTable(valList) {
    if (valList == null) {
        valList = [];
    } else {
        //计算总计
        var voltageValue = '总计';
        var amounts = 0;
        var times = 0;
        for (var i = 0; i < valList.length; i++) {
            amounts = valList[i].amounts + amounts;
            times = valList[i].times + times;
        }
        var voltage = {};
        voltage.voltageValue = voltageValue;
        voltage.amounts = amounts;
        voltage.times = times;
        valList.push(voltage);
        valList.reverse();
    }
    $("#valtageTable").DataTable({
        data: valList,
        autoWidth: false,
        order: [2, "desc"],
        columnDefs: [
            {"width": "33%", "targets": 0},
            {"width": "33%", "targets": 1},
            {"width": "33%", "targets": 2}
        ],
        paging: true,
        lengthChange: false,
        searching: false,
        destroy: true,
        pageLength: 10,
        language: {
            url: '/pqs9200/json/chine.json',
        },
        columns: [
            {data: 'voltageValue'},
            {data: 'amounts'},
            {data: 'times'}
        ]
    })
}

/**
 * 时间间隔表格
 * */
function initInter(interList) {
    if (interList == null) {
        interList = [];
    } else {
        //计算总计
        var monthName = '总计';
        var times = 0;
        for (var i = 0; i < interList.length; i++) {
            times = interList[i].times + times;
        }
        var month = {};
        month.month = monthName;
        month.times = times;
        month.year = 0;
        interList.push(month);
        interList.reverse();
    }
    $("#interTable").DataTable({
        data: interList,
        autoWidth: false,
        order: [1, "desc"],
        columnDefs: [
            {"width": "50%", "targets": 0}
        ],
        paging: true,
        lengthChange: false,
        searching: false,
        destroy: true,
        pageLength: 10,
        language: {
            url: '/pqs9200/json/chine.json',
        },
        columns: [
            {
                data: 'month',
                render: function (data, type, full, meta) {
                    var data = data;
                    if (full.year !== 0) {
                        data = full.year + "年" + data + "月";
                    }
                    return data;
                }
            },
            {data: 'times'}
        ]
    })
}


/**
 * 省级用户查看时间间隔图形绘制
 */
function initTimeIntervalProvice(interval) {
    $("#timeInterval").css('height', picHeight);
    echarts.dispose($("#timeInterval")[0]);
    var timetest = echarts.init(document.getElementById('timeInterval'));
    var months = [];
    var handle = [];
    var handled = [];
    if (interval != null) {
        for (var i = 0; i < interval.length; i++) {
            if (interval[i].month === "01" | i === 0) {
                months[i] = interval[i].month + "\n(" + interval[i].year
                    + ")";
            } else {
                months[i] = interval[i].month;
            }
            if (interval[i].handledTimes != null) {
                handled[i] = interval[i].handledTimes;
                var temp = interval[i].times - interval[i].handledTimes;
                if (temp < 0) {
                    temp = 0;
                }
                handle[i] = temp;
            }
        }
    }
    var timeOption = {
        backgroundColor: canvasBG,//背景色,
        title: {
            text: '月份',
            x: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                var tips = "";
                tips += params[0].name + '月<br/>';
                for (var i = 0; i < params.length; i++) {
                    tips += params[i].seriesName + ":" + params[i].value + "<br/>";
                }
                return tips;
            }
        },
        grid: {
            left: '3%',
            bottom: '6%',
            containLabel: true
        },
        legend: {
            data: ['未关联暂降次数', '已关联处理事件'],
            x: 'left'
        },
        xAxis: [{
            type: 'category',
            data: months,
            name: '月份',
            splitLine: {
                show: false
            },
            axisLabel: {
                show: true,
                interval: 0,
                fontSize:10
            }
        }],
        yAxis: [{
            type: 'value',
            name: '次'
        }],
        series: [{
            name: '未关联暂降次数',
            type: 'bar',
            stack: '事件总数',
            barMaxWidth: barMax,
            itemStyle: {
                normal: {
                    color: orange,
                    barBorderColor: orange,
                    barBorderWidth: 2,
                    barBorderRadius: 0
                }
            },
            data: handle
        }, {
            name: '已关联处理事件',
            type: 'bar',
            stack: '事件总数',
            barMaxWidth: barMax,
            itemStyle: {
                normal: {
                    color: lightgray,
                    barBorderColor: orange,
                    barBorderWidth: 2,
                    barBorderRadius: 0
                }
            },
            data: handled
        }]
    };
    timetest.setOption(timeOption);
    disImage = timetest.getDataURL();
}

/**
 * 地级市查看时间间隔数据
 */
function initTimeInterval(interval) {
    $("#timeInterval").css('height', picHeight);
    echarts.dispose($("#timeInterval")[0]);
    var timetest = echarts.init(document.getElementById('timeInterval'));
    var months = [];
    var handle = [];
    if (interval != null) {
        for (var i = 0; i < interval.length; i++) {
            if (interval[i].month === "01" | i === 0) {
                months[i] = interval[i].month + "\n(" + interval[i].year
                    + ")";
            } else {
                months[i] = interval[i].month;
            }
            handle[i] = interval[i].times;
        }
    }
    var timeOption = {
        backgroundColor: canvasBG,//背景色,
        title: {
            text: '月份',
            x: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                var tips = "";
                tips += params[0].name + '月</br/>';
                for (var i = 0; i < params.length; i++) {
                    tips += params[i].seriesName + ":" + params[i].value + "<br/>";
                }
                return tips;
            }
        },
        color: [orange],
        legend: {
            data: ['暂降次数'],
            x: 'left'
        },
        grid: {
            left: '3%',
            bottom: '6%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: months,
            name: '月份',
            splitLine: {
                show: false
            },
            axisLabel: {
                show: true,
                interval: 0,
                fontSize:10
            }
        }],
        yAxis: [{
            type: 'value',
            name: '次'
        }],
        series: [{
            name: '暂降次数',
            type: 'bar',
            barMaxWidth: barMax,
            itemStyle: {
                normal: {
                    label: {
                        show: true,
                        textStyle: {
                            color: purple
                        }
                    }
                }
            },
            data: handle
        }]
    };
    timetest.setOption(timeOption);
    disImage = timetest.getDataURL();
}

/**
 * 区域图形绘制
 */
function initDistrict(area, lineFeed,route) {
    $("#district").css('height', picHeight);
    echarts.dispose($("#district")[0]);
    var district = echarts.init(document.getElementById('district'));
    var colorLists = [];
    var areas = [];
    var times = [];
    if (area != null) {
        for (var i = 0; i < area.length; i++) {
            areas[i] = area[i].city +lineFeed+ "(" + area[i].amounts + ")";
            times[i] = area[i].times;
            colorLists.push(orange);
        }
        if (area.length === 1) {
            colorLists.length = 0;
            colorLists.push(orange);
        }
    }
    var disOption = {
        backgroundColor: canvasBG,
        title: {
            text: cityName,
            x: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            },
            formatter: function (params) {
                var tips = "";
                tips += params[0].name + '</br/>';
                for (var i = 0; i < params.length; i++) {
                    tips += params[i].seriesName + ":" + params[i].value + "<br/>";
                }
                return tips;
            }
        },
        color: [orange],
        //控制图表在dataroom中的位置大小
        grid: {
            left: '1%',
            right: '7%',
            bottom: '8%',
            containLabel: true
        },
        legend: {
            data: ['暂降次数'],
            selectedMode: false,
            x: 'left'
        },
        xAxis: [{
            type: 'category',
            data: areas,
            splitLine: {
                show: false
            },
            name: '地区\n(监测点数)',
            axisLabel: {
                interval: 0,
                show: true,
                rotate:route,
                fontSize:10
            }
        }],
        yAxis: [{
            type: 'value',
            name: '(次)'
        }],
        series: [{
            name: '暂降次数',
            type: 'bar',
            itemStyle: {
                normal: {
                    label: {
                        show: true,
                        textStyle: {
                            color: purple
                        }
                    }
                }
            },
            data: times,
            barMaxWidth: barMax
        }],
    };
    district.setOption(disOption);
    //点击事件
    district.on('click', function (param) {
        if (areaAble !== "normal") {
            getPointData(param.name);
        }
    });
    areaImage = district.getDataURL();
}

/**
 * 电压等级图形绘制
 */
function initVoltage(vol) {
    $("#voltage").css('height', picHeight);
    echarts.dispose($("#voltage")[0]);
    var voltage = echarts.init(document.getElementById('voltage'));
    var vols = [];
    var times = [];
    if (vol != null) {
        for (var i = 0; i < vol.length; i++) {
            vols[i] = vol[i].voltageValue + "\n(" + vol[i].amounts + ")";
            times[i] = vol[i].times;
        }
    }else{
        times.push(0)
    }
    var volOption = {
        backgroundColor: canvasBG,
        title: {
            text: '电压等级',
            x: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: { // 坐标轴指示器，坐标轴触发有效
                type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            },
            formatter: function (params) {
                var tips = "";
                tips += params[0].name + '</br/>';
                for (var i = 0; i < params.length; i++) {
                    tips += params[i].seriesName + ":" + params[i].value + "<br/>";
                }
                return tips;
            }
        },
        color: [orange],
        legend: {
            data: ['暂降次数'],
            selectedMode: false,
            x: 'left'
        },
        grid: {
            left: '3%',
            right: '12%',
            bottom: '6%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: vols,
            splitLine: {
                show: false
            },
            name: '电压等级\n(监测点数)',
            axisLabel: {
                interval: 0,
                show: true,
                fontSize:10
            }
        }],
        yAxis: [{
            type: 'value',
            name: '(次)'
        }],
        series: [{
            name: '暂降次数',
            type: 'bar',
            itemStyle: {
                normal: {
                    label: {
                        show: true,
                        textStyle: {
                            color: purple
                        }
                    }
                }
            },
            data: times,
            barMaxWidth: barMax
        }]
    };
    voltage.setOption(volOption);
    volImage = voltage.getDataURL();
}



//用户点击返回，查询省级数据
$("#backpro").click(function () {
    var area = getDeptsPIndex($area.eq(0).val());
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    refresh(area, startTime, endTime);
})

$("#backpro").mouseover(function () {
    $(this).removeClass("themeBGColor")

});
$("#backpro").mouseout(function () {
    $(this).addClass("themeBGColor");
});

//保存页面中的图
$("#saveImage").on('click', function () {
    var area = $area.eq(0).val();
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    var name = area + startTime + '到' + endTime;
    drawOnCanvas(areaImage, volImage, disImage, name);
});


//特殊处理，表头紧缩问题--start
var it = null;

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

}

/* 刷新查询 */
function refreshQuery() {
    var width = $("#district").width();
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    startTime = startTime.replace(/-/g, "/");
    endTime = endTime.replace(/-/g, "/");
    startTime=filterXSS(startTime);
    endTime=filterXSS(endTime);
    if (width > 120) {
        if (generalData.code === null) {
            return;
        }
        $(".tongjiTime").html(startTime + "-" + endTime)
        cityName = generalData.body.cityName;
        $(".tongjiArea").html(cityName);
        if (generalData.code === 500) {
            $(".tongjiCounts").html(0);
            //初始化三个图表
            //区域
            initDistrict(null,lineFeed,barRouteZero);
            initArea(null);
            //电压等级
            initVoltage(null);
            initValtageTable(null);
            //时间间隔
            initTimeInterval(null);
            initInter(null);
        } else {
            $(".tongjiCounts").html(generalData.body.totalTimes);
            //初始化三个图表
            var areaData=generalData.body.area;
            var areaLength=areaData==null?0:areaData.length;
            if(Number(areaLength)>Number(barUpperLimit12)){
                initDistrict(areaData,noLineFeed,barRouteIncline);
            }else{
                initDistrict(areaData,lineFeed,barRouteZero);
            }
            initVoltage(generalData.body.vol);
            areaAble = generalData.body.pro;
            backAble = generalData.body.root;
            if (backAble !== "root") {
                $("#backpro").css("display", "inline-block");
            } else {
                $("#backpro").css("display", "none");
            }
            if (areaAble === "normal") {
                initTimeInterval(generalData.body.interval);
            } else {
                initTimeIntervalProvice(generalData.body.interval);
            }
            if (generalData.body.area != null) {
                initArea(generalData.body.area);
            } else {
                initArea(null);
            }
            if (generalData.body.vol != null) {
                initValtageTable(generalData.body.vol);
            } else {
                initValtageTable(null);
            }
            if (generalData.body.interval != null) {
                initInter(generalData.body.interval);
            } else {
                initInter(null);
            }
        }
        window.clearInterval(it)
    }
}

//特殊处理，表头紧缩问题--end


//点击导出报表数据
$("#exportData").on("click", function () {
    var area = $area.eq(0).attr("index");
    var name = $area.eq(0).val();
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    var xhr = new XMLHttpRequest();
    xhr.open('post', '/pqs9200/area/downloadGeneralData', true);
    xhr.responseType = 'blob';
    xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
    var commontParamter = {};
    commontParamter.area = area;
    commontParamter.startTime = startTime;
    commontParamter.endTime = endTime;
    var i = ityzl_SHOW_LOAD_LAYER();
    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 = name + '暂降事件统计_' + startTime + '_' + endTime + '.xlsx';
            a.click();
            a.remove();
        }
        //***********关闭loading
        ityzl_CLOSE_LOAD_LAYER(i);
    }
})