var picHeight;
var tabs;
var $area = $("#area");
var $startTime = $("#startTime");
var $endTime = $("#endTime");
$("#interval").val("月份");
var tiggleValue;
var allData;
var type=0;
var buttonname;
var companyname;
var lineGradeInte = 95

// 新增tab页
function addTab(url, label) {
    tabs.add({url: url, label: label});
}

/*$("#datatype").on("change",function() {
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    if($("option:selected",this).val() == 0){
        $.ajax({
            type: "POST",
            url: "/pqs9900/user/getAreasInfo",
            dataType: 'json',
            async:false,
            success: function (data) {
                $("#area").val(data[0].name);
                $("#area").attr("index", data[0].id);
                areaTree = $.fn.zTree.init($("#areaTree"), settingAreaTree, data);
            }
        })
        $("#area").attr("disabled",true);
        $("#scale").attr("disabled",false);
        $("#manc").attr("disabled",false);
        $("#loadtype").attr("disabled",false);
        type = 0;
        var area = $area.eq(0).attr("index");
        var scale = $("#scale").val();
        var manc = $("#manc").val();
        var loadtype = $("#loadtype").val();
        refresh(startTime, endTime, area,scale,manc,loadtype)
    }else if($("option:selected",this).val() == 1){
        loadselect("电压等级","scale");
        $("#area").attr("disabled",false);
        $("#scale").attr("disabled",true);
        $("#manc").attr("disabled",false);
        $("#loadtype").attr("disabled",false);
        $("#area").css("background-color","#fff");
        type = 1;
        var area = $area.eq(0).attr("index");
        var scale = $("#scale").val();
        var manc = $("#manc").val();
        var loadtype = $("#loadtype").val();
        refresh(startTime, endTime, area,scale,manc,loadtype);
    }else if($("option:selected",this).val() == 2){
        loadselect("制造厂商","manc");
        $("#area").attr("disabled",false);
        $("#scale").attr("disabled",false);
        $("#manc").attr("disabled",true);
        $("#loadtype").attr("disabled",false);
        $("#area").css("background-color","#fff");
        type = 2;
        var area = $area.eq(0).attr("index");
        var scale = $("#scale").val();
        var manc = $("#manc").val();
        var loadtype = $("#loadtype").val();
        refresh(startTime, endTime, area,scale,manc,loadtype);
    }else if($("option:selected",this).val() == 3){
        loadselect("干扰源类型","loadtype");
        $("#area").attr("disabled",false);
        $("#scale").attr("disabled",false);
        $("#manc").attr("disabled",false);
        $("#loadtype").attr("disabled",true);
        $("#area").css("background-color","#fff");
        type = 3;
        var area = $area.eq(0).attr("index");
        var scale = $("#scale").val();
        var manc = $("#manc").val();
        var loadtype = $("#loadtype").val();
        refresh(startTime, endTime, area,scale,manc,loadtype);
    }
})*/

$(function () {
    var start = $startTime.eq(0).val();
    var end = $endTime.eq(0).val();

    loadselect("电压等级","scale");
    loadselect("制造厂商","manc");
    loadselect("干扰源类型","loadtype");
    initselect()



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


        $('#rightContent').width(document.body.clientWidth - 290).height(document.body.offsetHeight - 115);
        tabs = $('#tabs').cleverTabs();
        picHeight = ($(window).height() - 78);
        $.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);

             /*   $("#area").attr("disabled",false);
                $("#scale").attr("disabled",false);
                $("#manc").attr("disabled",false);
                $("#loadtype").attr("disabled",false);*/
                //初始化页面内容
                var area = $area.eq(0).attr("index");
                var startTime = $startTime.eq(0).val();
                var endTime = $endTime.eq(0).val();
                refresh(startTime, endTime, area,null,null,null,0);
            }
        })
})

//点击查询按钮
$("#query").click(function () {
    var area = $area.eq(0).attr("index");
    var startTime = $startTime.eq(0).val();
    var endTime = $endTime.eq(0).val();
    var scale = $("#scale").val();
    var manc = $("#manc").val();
    var loadtype = $("#loadtype").val();
    var lineGrade = $("#lineGrade").val();
    queryListForRun(lineGrade)
    refresh(startTime, endTime, area,scale,manc,loadtype,lineGrade);
});

//请求后台刷新页面数据
function refresh(startTime, endTime, area,scale,manc,loadtype,linGrade) {
    let datatype = $("#datatype").val()
    type = datatype
    var i;
    $.ajax({
        url: '/pqs9900/areaData/dataIntegrality',
        data: {
            startTime: startTime,
            endTime: endTime,
            overview:datatype,
            lineGrade:linGrade,
            area: area,
            scale:scale,
            manc:manc,
            loadtype:loadtype
        },
        type: 'post',
        dataType: 'json',
        beforeSend: function () {
            i = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (data) {
            if (data.code === 500 | data.body === null) {
                allData = null;
                if(type == 0){
                    drawAreaPic(null);
                }else if(type == 1){
                    drawVoltagePic(null);
                }else if(type == 2){
                    drawCompanyPic(null);
                }else if(type == 3){
                    drawLoadTypePic(null);
                }
            } else {
                allData = data.body;
                if(type == 0){
                    drawAreaPic(data.body.area);
                }else if(type == 1){
                    drawVoltagePic(data.body.vol);
                }else if(type == 2){
                    drawCompanyPic(data.body.interval);
                }else if(type == 3){
                    drawLoadTypePic(data.body.loadtype);
                }
            }

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

//开关触发图片更新
function reDrawAllPic() {
    if (allData === null) {
        drawAreaPic(null);
    } else {
        if($("#datatype").val() == "0"){
            drawAreaPic(allData.area);
        }else if($("#datatype").val() == "1"){
            drawVoltagePic(allData.vol)
        }else if($("#datatype").val() == "2"){
            drawCompanyPic(allData.interval)
        }else if($("#datatype").val() == "3"){
            drawLoadTypePic(allData.loadtype)
        }
    }
}


//绘画区域数据
function drawAreaPic(area) {
    var $area = $("#areaChart");
    $area.css("height", picHeight);
    var width = $area.width();
    if (width <= 120) {
        $area.css("width", $(window).width() - 30);
    }
    var areaOption = echarts.init($("#areaChart")[0]);
    var inte = [];
    var areas = [];
    var route;
    var lineFeedBar;
    if (null != area) {
        if(area.length>barUpperLimit12){
            route=barRouteIncline;
            lineFeedBar=noLineFeed;
        }else{
            route=barRouteZero;
            lineFeedBar=lineFeed;
        }
        for (var i = 0; i < area.length; i++) {
            var integralityRate;
            if (tiggleValue == buttonname) {
                areas[i] = area[i].name + lineFeedBar+"(" + area[i].amounts + ")";
                integralityRate = Number(area[i].dataIntegrity);
            } else {
                areas[i] = area[i].name + lineFeedBar+"(" + area[i].gwamounts + ")";
                integralityRate = Number(area[i].gwdataIntegrity);
            }
            var singleData = {};
            var item = {};
            item.color = getColor(integralityRate);
            if (integralityRate < 3.1414) {
                singleData.value = 3.1415;
                item.actual = integralityRate;
            } else {
                singleData.value = integralityRate;
            }
            singleData.itemStyle = item;
            singleData.areaIndex = area[i].deptsIndex;
            inte[i] = singleData;
        }
    }
    var option = {
        backgroundColor: canvasBG,//背景色
        title: {
            text: '区域',
            x: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                var color = params[0].color;
                var tips = "";
                tips += params[0].name;
                if (color === noMonitor) {
                    tips += '<br/>' + params[0].seriesName + ' : /';
                } else if (color === noData) {
                    tips += '<br/>' + params[0].seriesName + ' : （暂无数据）';
                } else {
                    if (params[0].data.itemStyle.actual !== undefined) {
                        tips += '<br/>' + params[0].seriesName + ' : ' + params[0].data.itemStyle.actual;
                    } else {
                        tips += '<br/>' + params[0].seriesName + ' : ' + params[0].value;
                    }
                }
                return tips;
            }
        },
        //控制图标在dataroom中的位置大小
        grid: {
            left: '1%',
            right: '7%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            name: '地区\n(监测点数)\n',
            axisLabel: {
                interval: 0,
                show: true,
                rotate:route,
                fontSize:10
            }
        }],
        yAxis: [{
            type: 'value',
            name: '%',
            min: '0',
            max: '100'
        }],
        series: [{
            name: '完整性',
            type: 'bar',
            barMaxWidth: barMax,
            data: inte
        }]
    };
    areaOption.setOption(option);
    areaOption.on('click', function (params) {
        if(type == 0){
            var city = params.data.areaIndex;
            var startTime = $startTime.eq(0).val();
            var endTime = $endTime.eq(0).val();
            var interval = $("#interval").val();
            if (getRole("/pqs9900/area/integralitytable")) {
                window.top.addTab('/pqs9900/area/integralitytable?startTime=' + startTime + '&endTime=' + endTime + '&area=' + city + '&interval=' + interval, '完整性列表')
            }
        }
    });
}

//绘制电压等级
function drawVoltagePic(vol) {
    var $voltage = $("#areaChart");
    $voltage.css("height", picHeight);
    var width = $voltage.width();
    if (width <= 120) {
        $voltage.css("width", ($(window).width() - 30) * 0.5);
    }
    var volOption = echarts.init($("#areaChart")[0]);
    var inte = [];
    var areas = [];
    if (null != vol) {
        for (var i = 0; i < vol.length; i++) {
            var integralityRate;
            if (tiggleValue === buttonname) {
                areas[i] = vol[i].name + "\n(" + vol[i].amounts + ")";
                integralityRate = Number(vol[i].dataIntegrity);
            } else {
                areas[i] = vol[i].name + "\n(" + vol[i].gwamounts + ")";
                integralityRate = Number(vol[i].gwdataIntegrity);
            }
            var singleData = {};
            var item = {};
            item.color = getColor(integralityRate);
            if (integralityRate < 3.1414) {
                singleData.value = 3.1415;
                item.actual = integralityRate;
            } else {
                singleData.value = integralityRate;
            }
            singleData.itemStyle = item;
            inte[i] = singleData;
        }
    }
    var option = {
        backgroundColor: canvasBG,//背景色
        title: {
            text: '电压等级',
            x: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                var color = params[0].color;
                var tips = "";
                tips += params[0].name;
                if (color === noMonitor) {
                    tips += '<br/>' + params[0].seriesName + ' : /';
                } else if (color === noData) {
                    tips += '<br/>' + params[0].seriesName + ' : （暂无数据）';
                } else {
                    if (params[0].data.itemStyle.actual !== undefined) {
                        tips += '<br/>' + params[0].seriesName + ' : ' + params[0].data.itemStyle.actual;
                    } else {
                        tips += '<br/>' + params[0].seriesName + ' : ' + params[0].value;
                    }
                }
                return tips;
            }
        },
        //控制图标在dataroom中的位置大小
        grid: {
            left: '3%',
            right: '13%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            name: '电压等级\n(监测点数)\n',
        }],
        yAxis: [{
            type: 'value',
            name: '%',
            min: '0',
            max: '100'
        }],
        series: [{
            name: '完整性',
            type: 'bar',
            barMaxWidth: barMax,
            data: inte
        }]
    };
    volOption.setOption(option);
    volOption.on('click', function (params) {
        if(type == 1){
            var startTime = $startTime.eq(0).val();
            var endTime = $endTime.eq(0).val();
            var interval = $("#interval").val();
            if (getRole("/pqs9900/area/integralitytable")) {
                window.top.addTab('/pqs9900/area/integralitytable?startTime=' + startTime + '&endTime=' + endTime + '&area=' + $area.eq(0).attr("index") + '&interval=' + interval, '完整性列表')
            }
        }
    });
}

//绘制设备厂家
function drawCompanyPic(company) {
    var $company = $("#areaChart");
    $company.css("height", picHeight);
    var width = $company.width();
    if (width <= 120) {
        $company.css("width", ($(window).width() - 30) * 0.5);
    }
    var comOption = echarts.init($("#areaChart")[0]);
    var inte = [];
    var areas = [];
    if (null != company) {
        for (var i = 0; i < company.length; i++) {
            var integralityRate;
            if (tiggleValue === buttonname) {
                areas[i] = company[i].name + "\n(" + company[i].amounts + ")";
                integralityRate = Number(company[i].dataIntegrity);
            } else {
                areas[i] = company[i].name + "\n(" + company[i].gwamounts + ")";
                integralityRate = Number(company[i].gwdataIntegrity);
            }
            var singleData = {};
            var item = {};
            item.color = getColor(integralityRate);
            if (integralityRate < 3.1414) {
                singleData.value = 3.1415;
                item.actual = integralityRate;
            } else {
                singleData.value = integralityRate;
            }
            singleData.itemStyle = item;
            inte[i] = singleData;
        }
    }
    var option = {
        backgroundColor: canvasBG,//背景色
        title: {
            text: '终端厂家',
            x: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                var color = params[0].color;
                var tips = "";
                tips += params[0].name;
                if (color === noMonitor) {
                    tips += '<br/>' + params[0].seriesName + ' : /';
                } else if (color === noData) {
                    tips += '<br/>' + params[0].seriesName + ' : （暂无数据）';
                } else {
                    if (params[0].data.itemStyle.actual !== undefined) {
                        tips += '<br/>' + params[0].seriesName + ' : ' + params[0].data.itemStyle.actual;
                    } else {
                        tips += '<br/>' + params[0].seriesName + ' : ' + params[0].value;
                    }
                }
                return tips;
            }
        },
        //控制图标在dataroom中的位置大小
        grid: {
            left: '3%',
            right: '13%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            name: '终端厂家\n(监测点数)\n',
        }],
        yAxis: [{
            type: 'value',
            name: '%',
            min: '0',
            max: '100'
        }],
        series: [{
            name: '完整性',
            type: 'bar',
            barMaxWidth: barMax,
            data: inte
        }]
    };
    comOption.setOption(option);
    comOption.on('click', function (params) {
        if(type == 2){
            var startTime = $startTime.eq(0).val();
            var endTime = $endTime.eq(0).val();
            var interval = $("#interval").val();
            if (getRole("/pqs9900/area/integralitytable")) {
                window.top.addTab('/pqs9900/area/integralitytable?startTime=' + startTime + '&endTime=' + endTime + '&area=' + $area.eq(0).attr("index") + '&interval=' + interval, '完整性列表')
            }
        }
    });
}

//绘制干扰源类型
function drawLoadTypePic(vol) {
    var $voltage = $("#areaChart");
    $voltage.css("height", picHeight);
    var width = $voltage.width();
    if (width <= 120) {
        $voltage.css("width", ($(window).width() - 30) * 0.5);
    }
    var volOption = echarts.init($("#areaChart")[0]);
    var inte = [];
    var areas = [];
    if (null != vol) {
        for (var i = 0; i < vol.length; i++) {
            var integralityRate;
            if (tiggleValue === buttonname) {
                areas[i] = vol[i].name + "\n(" + vol[i].amounts + ")";
                integralityRate = Number(vol[i].dataIntegrity);
            } else {
                areas[i] = vol[i].name + "\n(" + vol[i].gwamounts + ")";
                integralityRate = Number(vol[i].gwdataIntegrity);
            }
            var singleData = {};
            var item = {};
            item.color = getColor(integralityRate);
            if (integralityRate < 3.1414) {
                singleData.value = 3.1415;
                item.actual = integralityRate;
            } else {
                singleData.value = integralityRate;
            }
            singleData.itemStyle = item;
            inte[i] = singleData;
        }
    }
    var option = {
        backgroundColor: canvasBG,//背景色
        title: {
            text: '干扰源类型',
            x: 'center'
        },
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'shadow'
            },
            formatter: function (params) {
                var color = params[0].color;
                var tips = "";
                tips += params[0].name;
                if (color === noMonitor) {
                    tips += '<br/>' + params[0].seriesName + ' : /';
                } else if (color === noData) {
                    tips += '<br/>' + params[0].seriesName + ' : （暂无数据）';
                } else {
                    if (params[0].data.itemStyle.actual !== undefined) {
                        tips += '<br/>' + params[0].seriesName + ' : ' + params[0].data.itemStyle.actual;
                    } else {
                        tips += '<br/>' + params[0].seriesName + ' : ' + params[0].value;
                    }
                }
                return tips;
            }
        },
        //控制图标在dataroom中的位置大小
        grid: {
            left: '3%',
            right: '13%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: [{
            type: 'category',
            data: areas,
            name: '干扰源类型\n(监测点数)\n',
        }],
        yAxis: [{
            type: 'value',
            name: '%',
            min: '0',
            max: '100'
        }],
        series: [{
            name: '完整性',
            type: 'bar',
            barMaxWidth: barMax,
            data: inte
        }]
    };
    volOption.setOption(option);
    volOption.on('click', function (params) {
        if(type == 3){
            var startTime = $startTime.eq(0).val();
            var endTime = $endTime.eq(0).val();
            var interval = $("#interval").val();
            if (getRole("/pqs9900/area/integralitytable")) {
                window.top.addTab('/pqs9900/area/integralitytable?startTime=' + startTime + '&endTime=' + endTime + '&area=' + $area.eq(0).attr("index") + '&interval=' + interval, '完整性列表')
            }
        }
    });
}

//根据数据完整性获取颜色
function getColor(data) {
    if (data >= lineGradeInte) {
        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;
    }
}

function loadselect(dictypeName,div){
    var part='#'+div;
    $(part).find("option").remove();
    $.ajax({
        method : "post",
        url : "/pqs9900/device/getselect",
        data : {
            dictypeName:dictypeName
        },
        async:false,
        success : function(data) {
            if(data == null){
                var message = dictypeName + '信息加载失败';
                layer.msg(message,{icon:1,time:1000});
            }else{
                var option0 = $("<option selected value=''>"
                    + "全部" + "</option>");
                $(part).append(option0);
                $.each(data, function(i, item) {
                    var option = $("<option value='"
                        + item.dicIndex + "'>"
                        + item.dicName + "</option>");
                    $(part).append(option);
                })
            }
        }
    })
}

function initselect(){
    var option = "<option value=''>全部</option>";
    $.ajax({
        method: "post",
        url: "/pqs9900/device/getselect",
        data: {
            dictypeName: '终端等级'
        },
        dataType: 'json',
        async: false,
        success: function (data) {
            for (var i = 0; i < data.length; i++) {

                option = option + "<option value='"
                    + data[i].dicLeave + "'>"
                    + data[i].dicName + "</option>";

            }
            $("#lineGrade").empty()
            $("#lineGrade").append(option)
            $("#lineGrade").val(0)
            queryListForRun(0)
        }
    })
}

//获取告警策略
function queryListForRun(lineGrade){
    let title = '<span  class=\'fr font12\' ><span class=\'info\'><span  class=\'inB bg-info smallBlock\'></span> 完整性≥{{1}}</span><span class=\'warn\'> <span class=\'inB bg-warn smallBlock\'></span> 60%≤完整性<{{2}} </span><span class=\'error\'> <span class=\'inB bg-error smallBlock\'></span> 完整性<60%</span></span>'

    let html  = title.replace("{{1}}",'90%').replace("{{2}}",'90')
    $.ajax({
        type: "get",
        url: "/pqs9900/inStrategy/queryListForRun",
        dataType: 'json',
        success: function (data) {
            let da =  data.body
            if(da.length!=0){
                da.forEach(function (item,index) {
                    if(item.dicLeave == lineGrade){
                        html = title.replace("{{1}}",item.integrityValue+'%').replace("{{2}}",item.integrityValue+'%')
                        $("#charTitle").empty()
                        $("#charTitle").append(html)
                        lineGradeInte = item.integrityValue
                    }
                })
            }

        }
    })
}

$("#infomation").click(function () {
    layer.open({
        type: 2,
        title: '告警策略查看',
        maxmin : false,
        shadeClose: true, //点击遮罩关闭层
        area : ['100%' , '100%'],
        content : '/pqs9900/business/terminalrunstrategy',
        scrollbar : false

    });
})
