var areaImage, volImage, disImage, picHeight, cityName, generalData,total,status;
$(document).ready(function () {
    picHeight = ($(window).height() - 110) * 0.5;
    var idea;
    var endTime = getEndTime();
    var startTime = getMonthStartTime(endTime);
    $.ajax({
        type: "POST",
        url: "/pqs9200/area/getGeneralData",
        dataType: "text",
        data: {
            startTime: startTime,
            endTime: endTime
        },
        beforeSend: function () {
            idea = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (data) {
            var info = $.parseJSON(data);
            total = info.body.totalTimes;
            status = info.body.status;
            generalData = info;
            startQuery();

            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(idea);
        }
    });
});

//获取起始日期
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 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 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 initTimeIntervalTest(interval) {
    $("#timeInterval").css('height', picHeight);
    echarts.dispose(document.getElementById('timeInterval'));
    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;
            }
        },
        legend: {
            data: ['未关联暂降次数', '已关联处理事件'],
            x: 'left',
        },
        grid: {
            left: '3%',
            bottom: '3%',
            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',
            stack: '事件总数',
            barMaxWidth: barMax,
            itemStyle: {
                normal: {
                    color: orange,
                    barBorderColor: orange,
                    barBorderWidth: 2,
                    barBorderRadius: 0
                }
            },
            data: handle
        }, {
            name: '已关联处理事件',
            type: 'bar',
            stack: '事件总数',
            barMaxWidth: 30,
            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(document.getElementById('timeInterval'));
    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: '3%',
            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: 30,
            itemStyle: {
                normal: {
                    label: {
                        show: true,
                        textStyle: {
                            color: purple
                        }
                    }
                }
            },
            data: handle
        }]
    };
    timetest.setOption(timeOption);
    disImage = timetest.getDataURL();
}

/**
 * 区域图形绘制
 */
function initDistrict(cityName,area, lineFeed,route) {
    $("#district").css('height', picHeight);
    echarts.dispose(document.getElementById('district'));
    var district = echarts.init(document.getElementById('district'));
    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;
        }
    }
    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;
            }
        },
        //控制图标在dataroom中的位置大小
        grid: {
            left: '1%',
            right: '8%',
            bottom: '9%',
            containLabel: true
        },
        legend: {
            data: ['暂降次数'],
            selectedMode: false,
            x: 'left'
        },
        xAxis: [{
            type: 'category',
            data: areas,
            splitLine: {
                show: false
            },
            name: '地区\n(监测点数)\n',
            axisLabel: {
                interval: 0,
                show: true,
                rotate:route,
                fontSize:10
            }
        }],
        yAxis: [{
            type: 'value',
            name: '(次)'
        }],
        series: [{
            name: '暂降次数',
            type: 'bar',
            itemStyle: {
                normal: {
                    color: [orange],
                    label: {
                        show: true,
                        textStyle: {
                            color: purple
                        }
                    }
                }
            },
            data: times,
            barMaxWidth: barMax
        }],
    };
    district.setOption(disOption);
    areaImage = district.getDataURL();
}

/**
 * 电压等级图形绘制
 */
function initVoltage(vol) {
    $("#voltage").css('height', picHeight);
    echarts.dispose(document.getElementById('voltage'));
    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;
        }
    }
    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: '11%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: vols,
            splitLine: {
                show: false
            },
            name: '电压等级\n(监测点数)\n',
            axisLabel: {
                show: true,
                interval: 0,
                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();
}

/**
 * 保存图片
 */
$('#saveImage').on('click', function () {
    var endTime = getEndTime();
    var startTime = getMonthStartTime(endTime);
    var name = cityName + "_" + startTime + '到' + endTime;
    drawOnCanvas(areaImage, volImage, disImage, name);
});


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

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

}

/* 刷新查询 */
function refreshQuery() {
    var width = $("#district").width();
    var endTime = getEndTime();
    var startTime = getMonthStartTime(endTime);
    startTime = startTime.replace(/-/g, "/");
    endTime = endTime.replace(/-/g, "/");
    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);
            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(cityName,areaData,noLineFeed,barRouteIncline);
            }else{
                initDistrict(cityName,areaData,lineFeed,barRouteZero);
            }
            //电压等级
            initVoltage(generalData.body.vol);
            //时间间隔
            if (generalData.body.pro === "normal") {
                initTimeInterval(generalData.body.interval);
            } else {
                initTimeIntervalTest(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 endTime = getEndTime();
    var startTime = getMonthStartTime(endTime);
    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 = "overview";
    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 = cityName + '暂降事件统计_' + startTime + '_' + endTime + '.xlsx';
            a.click();
            a.remove();
        }
        //***********关闭loading
        ityzl_CLOSE_LOAD_LAYER(i);
    }

})