<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<c:set var="ctx" value="${pageContext.request.contextPath}"/>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport"
          content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <title>贡献度计算</title>
    <link rel="stylesheet" href="${ctx}/css/plugin/metroStyle/metroStyle.css">
    <link rel="stylesheet" href="${ctx}/css/plugin/bootstrap/bootstrap.min.css">
    <link rel="stylesheet" href="${ctx}/css/plugin/datatables/datatables.bootstrap.css">
    <link rel="stylesheet" href="${ctx}/js/plugin/layui/css/layui.css" media="all">
    <link rel="stylesheet" href="${ctx}/css/plugin/bootstrapSwitch/bootstrap-switch.min.css">
    <link rel="stylesheet" href="${ctx}/css/plugin/fontawesome/font-awesome.min.css">
    <link rel="stylesheet" href="${ctx}/css/plugin/mulitiCheckbox/hsCheckData.css">
    <link rel="stylesheet" href="${ctx}/css/plugin/dateSlider/dateSlider.css">
    <link rel="stylesheet" href="${ctx}/css/plugin/datatimepicker/bootstrap-datetimepicker.css">
    <link rel="stylesheet" href="${ctx}/css/plugin/datatables/datatables.bootstrap.css">
    <link rel="stylesheet" href="${ctx}/css/basic.css">
    <style>
        #tree, #leftContainer {
            overflow-y: auto;
        }

        body {
            overflow-y: hidden;
        }
        .layui-table td, .layui-table th {
            position: relative;
            padding: 8px;
            line-height: 1.4;
            font-size: 12px;
        }
        .nav-tabs > li > a {
            line-height: 0;
        }
        #resContainer {
            overflow: hidden;
        }
        #limitDiv {
            z-index: 1;
            right: 20px;
        }
        #limitValue {
            width: 80px;
        }
        .form_datetime {
            width: 85px !important;
        }
        .timeContent {
            padding: 0 !important;
        }
        .time {
            margin-top: 15px;
        }
        /*针对低分辨率*/
        @media screen and (max-width: 1400px) {
            #excute {
                margin-left: 0px;
            }

            #endLabel {
                margin-left: 0px;
            }
        }
        /*针对高分辨率*/
        @media screen and (min-width: 1400px) {
            #excute {
                margin-left: 15px;
            }

            #endLabel {
                margin-left: 15px;
            }
        }
        .together {
            margin-top: 20px;
        }
        .glyphicon-check {
            top: 3px;
            right: 20px;
            color: #696969
        }
        .notActive {
            color: #696969;
        }
        .activeCheck {
            color: #006565;
        }
        .table > tbody > tr > td, .table > tbody > tr > th, .table > tfoot > tr > td, .table > tfoot > tr > th, .table > thead > tr > td, .table > thead > tr > th {
            padding: 5px;
        }
        #dynamicPic, #tableDiv {
            padding: 0px !important;
        }
        .ui-rangeSlider-label-value {
            font-size: 8px !important;
        }
        .highcharts-tooltip {
            z-index: 999;
        }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div id="leftContainer" class="col-sm-2 col-md-2 mt5">
            <div id="search">
                <input class="localInput" id="searchValue" type="text" placeholder="请输入关键词" autocomplete="off"
                       oninput="valueChange(this.value)"/>
                <button class="btn btn-primary ml5" onclick="searchNode(searchValue.value)">搜索</button>
            </div>
            <div id="tree" class="ztree">
            </div>
        </div>
        <div class="col-sm-10 col-md-10 mt5">
            <div class="fr">
                <label>所选监测点：</label>
                <span id="monitorInfo">暂未选中监测点</span>
            </div>
            <div class="clearBoth">
                <label>谐波类型：</label>
                <input type="checkbox" checked id="type"/>
                <label class="ml15">谐波次数：</label>
                <div id="times" class="vermiddle">
                </div>
                <label class="ml15">负荷数据：</label>
                <select class="localInput" id="userDataList">
                    <option value="暂无用采数据">暂无用采数据</option>
                </select>
                <button id="uploadData" type="button" class="btn btn-primary ml15">
                    <i class='fa fa-plus-square'></i>新增
                </button>
                <button id="confirm" type="button" class="btn btn-primary ml15">确定</button>
            </div>
            <div class="none" id="mainContainer">
                <ul class="nav nav-tabs mt10" id="resTab"></ul>
                <div class="tab-content pdt5">
                    <div class="tab-pane active" id="resContainer">
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-sm-4 col-md-4 timeContent mt5">
                                    <label>起始时间：</label>
                                    <input class="localInput form_datetime con" type="text" id="startTime"
                                           autocomplete="off">
                                    <label id="endLabel">截止时间：</label>
                                    <input class="localInput form_datetime con" type="text" id="endTime"
                                           autocomplete="off">
                                    <button id="excute" type="button" class="btn btn-primary">执行</button>
                                </div>
                                <div class="col-sm-8 col-md-8 time">
                                    <%--时间横轴--%>
                                    <div class="div-inline mt15">
                                        <div class="dateSlider div-inline" id="dateSlider" style="height: 50px">&nbsp;
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="together disnone pa" id="limitDiv">
                            <div class="disnone" id="limit">
                                <div class="div-inline">
                                    <label>限值：</label>
                                    <input class="localInput con" type="text" id="limitValue" autocomplete="off" readonly>
                                    <i class="glyphicon glyphicon glyphicon-check notActive" id="limitValueI"></i>
                                </div>
                                <div class="div-inline">
                                    <label class="ml">时间点一：</label>
                                    <input class="localInput  con" type="text" id="limitStartTime"
                                           autocomplete="off" readonly>
                                    <i class="glyphicon glyphicon glyphicon-check notActive" id="limitStartTimeI"></i>
                                </div>
                                <div class="div-inline">
                                    <label class="ml">时间点二：</label>
                                    <input class="localInput  con" type="text" id="limitEndTime"
                                           autocomplete="off" readonly>
                                    <i class="glyphicon glyphicon glyphicon-check notActive" id="limitEndTimeI"></i>
                                </div>
                            </div>
                            <button id="dynamicData" type="button" class="btn btn-primary fr ml10">生成动态谐波责任数据</button>
                            <button id="responsibilityData" type="button" class="btn btn-primary disnone ml10 fr">生成谐波责任指标</button>
                        </div>
                        <div id="harmonicHistoryData" class="together width100"></div>
                        <div class="container-fluid disnone" id="dynamicDiv">
                            <div class="row">
                                <div class="col-sm-6 col-md-6" id="dynamicPic"></div>
                                <div class="col-sm-6 col-md-6" id="tableDiv">
                                    <table id="responsibilityTable" class="table table-striped table-bordered dataTable no-footer">
                                        <thead>
                                        <tr>
                                            <th>用户名(用户号)</th>
                                            <th>责任数据(%)</th>
                                        </tr>
                                        </thead>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<input type="hidden" id="lineIndex">
<input type="hidden" id="responsibilityDataIndex">
</body>
<script src="${ctx}/js/plugin/jquery/jquery.min.js"></script>
<script src="${ctx}/js/plugin/jquery-ui/jquery-ui.js"></script>
<script src="${ctx}/js/plugin/bootstrap/bootstrap.min.js"></script>
<script src="${ctx}/js/plugin/layui/layer.js"></script>
<script src="${ctx}/js/plugin/ztree/jquery.ztree.core.js"></script>
<script src="${ctx}/js/plugin/layui/layui.js"></script>
<script src="${ctx}/jspJS/utils/loading.js"></script>
<script src="${ctx}/js/plugin/bootstrapSwitch/bootstrap-switch.min.js"></script>
<script src="${ctx}/js/plugin/mulitiCheckbox/hsCheckData.js"></script>
<script src="${ctx}/js/plugin/dateSlider/DateSlider.js"></script>
<script src="${ctx}/js/plugin/bootstrap/bootstrap-datetimepicker.js"></script>
<script src="${ctx}/js/plugin/bootstrap/bootstrap-datetimepicker.zh-CN.js"></script>
<script src="${ctx}/js/plugin/highcharts/highstock.js"></script>
<script src="${ctx}/js/plugin/highcharts/exporting.js"></script>
<script src="${ctx}/js/plugin/highcharts/highchart-ZH.js"></script>
<script src="${ctx}/js/plugin/highcharts/no-data-to-display.js"></script>
<script src="${ctx}/js/plugin/datatables/datatables.jquery.js"></script>
<script src="${ctx}/js/plugin/datatables/datatables.bootstrap.js"></script>
<script src="${ctx}/jspJS/utils/judgeAjaxStatus.js"></script>
<script src="${ctx}/js/color.js"></script>
<script src="${ctx}/jspJS/utils/timeControl.js"></script>
<script src="${ctx}/jspJS/responsibility/tree.js"></script>
<script src="${ctx}/jspJS/responsibility/counts.js"></script>
<script>
    /**
     * 将页面中的元素通过jquery选择器获取到，返回的是$元素的集合，可通过eq(i)来指定具体的元素，通常是eq(0)
     * */
    //历史谐波波形
    var $harmonicHistoryData = $("#harmonicHistoryData").eq(0);
    //动态数据波形图
    var $dynamicPic = $("#dynamicPic").eq(0);
    //责任量化表格
    var $tableDiv = $("#tableDiv").eq(0);
    //负荷开关元素
    var $type = $("#type").eq(0);
    //谐波次数元素
    var $times = $('#times').eq(0);
    //用采数据上传按钮
    var $uploadData = $("#uploadData").eq(0);
    //用采列表元素
    var $userDataList=$("#userDataList").eq(0);
    //右侧数据内容的整个实体
    var contentBody_list;
    //window的高度
    var tableHeight;
    //初始化历史谐波波形、动态数据波形、责任量化表格的高度
    $(function () {
        var height = $(window).height();
        $harmonicHistoryData.css("height", (height - 150) / 2);
        $dynamicPic.css("height", (height - 150) / 2);
        $tableDiv.css("height", (height - 150) / 2);
        tableHeight=(height - 150) / 2-35;
        //获取用采数据列表
        getUserDataList();
    });

    /**
     * 干扰源类型开关部分，默认为谐波电压
     * */
    var tiggleValue = "vol";
    $type.bootstrapSwitch({
        onText: "谐波电压",      // 设置ON文本
        offText: "谐波电流",    // 设置OFF文本
        onColor: "primary",// 设置ON文本颜色     (info/success/warning/danger/primary)
        offColor: "primary",  // 设置OFF文本颜色        (info/success/warning/danger/primary)
        size: "small",    // 设置控件大小,从小到大  (mini/small/normal/large)
        handleWidth: "60",//设置控件宽度
        // 当开关状态改变时触发
        onSwitchChange: function (event, state) {
            if (state === true) {
                tiggleValue = "vol";
            } else {
                tiggleValue = "ele";
            }
        }
    });

    /**
     * 谐波次数选择模块初始化定义
     * */
    $times.hsCheckData({
        isShowCheckBox: true, //默认为false
        minCheck: 1,//默认为0，不限最少选择个数
        maxCheck: 5,//默认为0，不限最多选择个数
        data: timesData
    });

    /**
     * 用采数据上传，或者已经上传判断数据存在与否
     * */
    function getUserDataList(){
        $.ajax({
            type:"post",
            url:"/pqs9000/responsibility/getUserDataList",
            dataType:'json',
            success:function (data) {
                $userDataList.empty();
                if(data.code===500){
                    //异常获取用采列表或者用采列表为空
                    $userDataList.append("<option value='暂无用采数据'>暂无用采数据</option>");
                }else{
                    //拼接用采数据列表
                    for(var i=0;i<data.body.length;i++){
                        $userDataList.append("<option value='"+data.body[i].excelIndex+"' startTime='"+data.body[i].startTime+"' endTime='"+data.body[i].endTime+"'>"+data.body[i].excelName+"</option>");
                    }
                }
            }
        })
    }

    $uploadData.on("click", function () {
        parent.layer.open({
            type: 2,
            title: '用采数据列表',
            maxmin : false,
            area : ['100%' , '100%'],
            content: '/pqs9000/responsibility/userDataList',
            scrollbar: false,
            end:function () {
                getUserDataList();
            }
        });
    })
    /**
     *  用采数据加载完毕后，点击确定按钮，根据用户选择的谐波次数，展示内容
     *  需要做几个前置判断
     *  1：是否已经确定监测点
     *  2：是否勾选谐波次数
     *  3：用采数据上传是否正常
     */

    $("#confirm").on("click", function () {
        //先将之前的导航栏清空,以及之前的数据情空***start
        $("#resTab").empty();
        hiddenHistoryData();
        hiddenLimitDiv();
        hiddenDynamicData();
        hiddenDynamicDiv();
        contentBody_list = [];
        //先将之前的导航栏清空,以及之前的数据情空****end
        var times = $("#times").attr("data-id");
        var lineIndex = $("#lineIndex").val();
        var userData=$userDataList.val();
        //模拟测试，给固定的谐波次数
        if (lineIndex === "") {
            layer.msg('请选择需要查看的监测点', {icon: 2, time: 2000});
        }else if (times === undefined) {
            layer.msg('请选择需要查看的谐波次数', {icon: 2, time: 2000});
        }else if(userData==="暂无用采数据"){
            layer.msg('请选择负荷数据', {icon: 2, time: 2000});
        }else {
            //根据用户选择的次数生成对应的nav导航
            times = times.split("-");
            $("#resTab").append("<li class='active'><a class='navtab' href='#resContainer' data-toggle='tab' id='" + times[0] + "次谐波'>" + times[0] + "次谐波</a></li>")
            if (times.length > 1) {
                for (var t = 1; t < times.length; t++) {
                    $("#resTab").append("<li><a class='navtab' href='#resContainer' data-toggle='tab' id='" + times[t] + "次谐波'>" + times[t] + "次谐波</a></li>")
                }
            }
            //获取负荷数据的起始时间和截止时间，默认给定时间窗口为1个星期
            var startTime=$userDataList.find("option:selected").attr("startTime");
            var endTime=$userDataList.find("option:selected").attr("endTime");
            //创建时间轴
            createTime(startTime,endTime);
            //控制起始时间和截止时间的最大最小值
            initDateTime(new Date(Number(startTime)), new Date(Number(endTime)));

        }
    })
    //****************************时间处理start
    var dateSilderObj;
    //起始时间、截止时间输入框控件
    function initDateTime(startTime, endTime) {
        $('.form_datetime').datetimepicker({
            minView: "month", //选择日期后，不会再跳转去选择时分秒
            language: 'zh-CN',
            format: 'yyyy-mm-dd',
            todayBtn: false,//今日按钮
            autoclose: 1,
            startDate: startTime,
            endDate: endTime
        });
    }

    //监听起始时间和截止时间
    $("#startTime").on("change", function () {
        reSetTime();
    })
    $("#endTime").on("change", function () {
        reSetTime();
    })
    //重新赋值（选中区域）
    function reSetTime() {
        var startTime = $("#startTime").val();
        var endTime = $("#endTime").val();
        startTime = startTime.split("-");
        endTime = endTime.split("-");
        dateSilderObj.dateRangeSlider("values", new Date(startTime[0], Number(startTime[1] - 1), startTime[2]), new Date(endTime[0], Number(endTime[1] - 1), endTime[2]));
    }
    //创建时间横轴提供用户选择时间节点
    //月份定义
    var Months = ["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"];
    function createTime(startTime,endTime) {
        $("#dateSlider").empty();
        var date = $("<div id='date' />").appendTo($("#dateSlider"));//渲染日期组件
        dateSilderObj = date.dateRangeSlider({
            arrows: false,//是否显示左右箭头
            bounds: {min: new Date(2014, 1, 1), max: new Date(2050, 11, 31)},//最大 最少日期
            defaultValues: {min: new Date(2017, 3, 8), max: new Date(2050, 5, 23)}//默认选中区域
            , scales: [{
                first: function (value) {
                    return value;
                },
                end: function (value) {
                    return value;
                },
                next: function (val) {
                    var next = new Date(val);
                    return new Date(next.setMonth(next.getMonth() + 1));
                },
                label: function (val) {
                    return Months[val.getMonth()];
                },
                format: function (tickContainer, tickStart, tickEnd) {
                    tickContainer.addClass("myCustomClass");
                }
            }]
        });//日期控件
        //重新赋值（整个时间轴）
        dateSilderObj.dateRangeSlider("bounds", new Date(Number(startTime)), new Date(Number(endTime)));
        //重新赋值（选中区域）
        dateSilderObj.dateRangeSlider("values", new Date(Number(startTime)), new Date(Number(startTime)+24*60*60*1000*6));
        $("#startTime").val(startTime)
        $("#endTime").val(endTime)
        //拖动完毕后的事件
        dateSilderObj.bind("valuesChanged", function (e, data) {
            var val = data.values;
            var stime = val.min.getFullYear() + "-" + (val.min.getMonth() + 1) + "-" + val.min.getDate();
            var etime = val.max.getFullYear() + "-" + (val.max.getMonth() + 1) + "-" + val.max.getDate();
            $("#startTime").val(stime)
            $("#endTime").val(etime)
        });
        //显示展示内容
        $("#mainContainer").removeClass("none");

    }
    //*************************时间处理end

    //******************获取历史谐波数据start
    /**
     * 获取历史谐波数据需要3个参数
     * 1：监测点索引
     * 2：起始时间、截止时间
     * 3：确定谐波电流还是电压
     * 4：谐波次数确定
     */
    $("#excute").on("click", function () {
        var lineIndex = $("#lineIndex").val();
        var startTime = $("#startTime").val();
        var endTime = $("#endTime").val();
        var type = tiggleValue;
        var time = getTime();
        var historyLodingIndex;
        $.ajax({
            url: "/pqs9000/responsibility/historyData",
            type: "post",
            beforeSend: function () {
                historyLodingIndex = ityzl_SHOW_LOAD_LAYER();
            },
            dataType: "json",
            data: {
                lineIndex: lineIndex,
                startTime: startTime,
                endTime: endTime,
                type: type,
                time: time
            },
            success: function (data) {
                if (data.code === 200) {
                    contentBody_list[time] = {};
                    contentBody_list[time].historyData = data.body.historyData;
                    contentBody_list[time].overlimit = data.body.overlimit;
                    contentBody_list[time].startTime = startTime;
                    contentBody_list[time].endTime = endTime;
                    setGloableHighCharts(data.message);
                    initHarmonicHistory(data.body.historyData,data.body.overlimit);
                } else if(data.code === 501){
                    setGloableHighCharts(data.message);
                    initHarmonicHistory(data.body);
                } else {
                    layer.msg(data.message, {icon: 2, time: 2000});
                }
                clearValue();
                clearObjectValue(time)
                //清除动态数据和责任数据
                clearResponsibilityData(time);
                displayDynamicData();
                hiddenResponsibilityData();
                //***********关闭loading
                ityzl_CLOSE_LOAD_LAYER(historyLodingIndex);
            }
        })
    })

    //*************************hisgstock全局属性配置start
    function setGloableHighCharts(msg){
        Highcharts.setOptions({
            global: {
                useUTC: false
            },
            lang: {
                noData:msg
            }
        });
    }
    //*************************hisgstock全局属性配置end

    //根据历史谐波数据绘制波形图
    var chart = null;
    function initHarmonicHistory(data,overlimitValue) {
        //显示按钮和图片区域
        if (data === undefined | data.length === 0) {
            hiddenDynamicData();
            hiddenLimitDiv();
        } else {
            displayDynamicData();
            displayLimitDiv();
        }
        displayHistoryData();
        var picData = [];
        //组装数据
        if (data.length > 0) {
            for (var i = 0; i < data.length; i++) {
                picData.push([data[i].time, data[i].value]);
            }
        }
        //组装完数据开始画图
        //绘制瞬时波形图
        Highcharts.stockChart('harmonicHistoryData', {
            chart: {
                type: 'spline',
            },
            tooltip: {
                borderColor: grey,
                backgroundColor: 'rgba(105,105,105,0.7)',
                style: {
                    color: 'white',
                    fontSize: "15px",
                    padding: 10
                },
                formatter: function () {
                    var s = '<b>时刻：'
                        + Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x)
                        + '</b>';
                    //获取是电压 还是 电流，以及谐波次数作为提示
                    var unit;
                    if (tiggleValue === "vol") {
                        unit = "谐波电压";
                    } else {
                        unit = "谐波电流";
                    }
                    var time = $("#mainContainer li[class='active'] a").text();
                    time = time.replace("次谐波", "");
                    time = time.replace(/(^\s*)|(\s*$)/g, '');
                    unit = time + "次" + unit;
                    if (this.y === 0) {
                        s += '<br/>' + unit + ': ' + 0;
                    } else {
                        s += '<br/>' + unit + ': ' + this.y.toFixed(3);
                    }
                    return s;
                },
                shared: true
            },
            rangeSelector: {
                enabled: false,
            },
            chart: {
                events: {
                    //点击事件，根据选中情况赋值
                    click: function (e) {
                        //寻找到哪个check处于激活状态
                        var $checkEle = $("#limitDiv .activeCheck");
                        var length = $checkEle.length;
                        if (length === 1) {
                            var xValue = Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', e.xAxis[0].value);
                            var yValue = e.yAxis[0].value.toFixed(4);
                            var idTemp = $checkEle.eq(0).attr("id");
                            var time = getTime();
                            switch (idTemp) {//
                                case "limitValueI":
                                    $("#limitValue").val(yValue);
                                    drawLimitValue(time, yValue);
                                    break;
                                case "limitStartTimeI":
                                    $("#limitStartTime").val(xValue);
                                    drawLimitStartTime(time, xValue);
                                    break;
                                case "limitEndTimeI":
                                    $("#limitEndTime").val(xValue);
                                    drawLimitEndTime(time, xValue);
                                    break;
                            }
                        }

                    }
                }
            },
            //导航器各项属性设置
            navigator: {
                enabled: false
            },
            scrollbar: {
                enabled: false
            },
            exporting: false,
            credits: false,
            xAxis: {
                labels: {
                    step: 2
                },
                type: 'datetime',
            },
            yAxis: {
                showLastLabel: true,//显示纵坐标最大值，highstock默认不显示最大值，即默认为false
                opposite: false
            },
            series: [{
                data: picData,
                events: {
                    //点击事件，根据选中情况赋值
                    click: function (e) {
                        //寻找到哪个check处于激活状态
                        var $checkEle = $("#limitDiv .activeCheck");
                        var length = $checkEle.length;
                        if (length === 1) {
                            var xValue = Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', e.point.x);
                            var yValue = e.point.y.toFixed(4);
                            var idTemp = $checkEle.eq(0).attr("id");
                            var time = getTime();
                            switch (idTemp) {//
                                case "limitValueI":
                                    $("#limitValue").val(yValue);
                                    drawLimitValue(time, yValue);
                                    break;
                                case "limitStartTimeI":
                                    $("#limitStartTime").val(xValue);
                                    drawLimitStartTime(time, xValue);
                                    break;
                                case "limitEndTimeI":
                                    $("#limitEndTime").val(xValue);
                                    drawLimitEndTime(time, xValue);
                                    break;
                            }
                        }

                    }
                }
            }],
            noData: {
                style: {
                    fontWeight: 'bold',
                    fontSize: '15px',
                    color: '#303030'
                }
            }
        }, function (c) {
            chart = c;
        });
        chart.yAxis[0].addPlotLine({
            value: overlimitValue,
            dashStyle: 'Solid',
            width: 1,
            color: '#006565',
            id: 'yAxis0'
        });
    }

    //绘制限值
    function drawLimitValue(time, limitValue) {
        chart.yAxis[0].removePlotLine('yAxis1');
        contentBody_list[time].limitValue = limitValue;
        chart.yAxis[0].addPlotLine({
            value: limitValue,
            dashStyle: 'dash',
            width: 1,
            color: '#A52a2a',
            id: 'yAxis1'
        });
    }

    //绘制时间点1
    function drawLimitStartTime(time, limitStartTime) {
        chart.xAxis[0].removePlotLine("xAxis1");
        contentBody_list[time].limitStartTime = limitStartTime;
        chart.xAxis[0].addPlotLine({
            value: getTimeDate(limitStartTime),
            dashStyle: 'dash',
            width: 1,
            color: '#A52a2a',
            id: 'xAxis1'
        });
    }

    //绘制时间点2
    function drawLimitEndTime(time, limitEndTime) {
        chart.xAxis[0].removePlotLine("xAxis2");
        contentBody_list[time].limitEndTime = limitEndTime;
        chart.xAxis[0].addPlotLine({
            value: getTimeDate(limitEndTime),
            dashStyle: 'dash',
            width: 1,
            color: '#A52a2a',
            id: 'xAxis2'
        });
    }

    //******************获取历史谐波数据end


    //*********************右边内容end

    //监听图标点击事件
    $(".glyphicon-check").on("click", function () {
        if($(this).hasClass("activeCheck")){
            $(".glyphicon-check").removeClass("activeCheck");
            $(".glyphicon-check").addClass("notActive");
        }else{
            $(".glyphicon-check").removeClass("activeCheck");
            $(".glyphicon-check").addClass("notActive");
            $(this).addClass("activeCheck");
        }

    })

    //将所有的限值都置为灰色
    function noActiveLimit(){
        $(".glyphicon-check").removeClass("activeCheck");
        $(".glyphicon-check").addClass("notActive");
    }

    //监听tab的切换，更新页面内容
    $("#mainContainer").on("click", ".navtab", function () {
        var time = $(this).text();
        time = time.replace("次谐波", "");
        time = time.replace(/(^\s*)|(\s*$)/g, '');
        //判断当前次数是否有数据内容，有的话画图，没有的话，隐藏图表区
        var historyData;
        try {
            historyData = contentBody_list[time].historyData;
            //根据当前tab的时间重置
            var startTime = contentBody_list[time].startTime;
            var endTime = contentBody_list[time].endTime;
            $("#startTime").val(startTime);
            $("#endTime").val(endTime);
            //时间轴更新
            reSetTime();
            //画图
            initHarmonicHistory(historyData);
            //处理限值
            dealLimitValue(time);
        } catch (e) {
            //隐藏
            hiddenDynamicData();
            hiddenHistoryData();
            hiddenLimitDiv();
        }
        try {
            //处理动态数据和责任数据
            var picData = contentBody_list[time].picData;
            //表格图数据
            var responsibilityData = contentBody_list[time].responsibilityData;
            displayResponsibilityData();
            hiddenDynamicData();
            initBasePic();
            initDynamicPic(picData);
            initTable(responsibilityData);
            displayDynamicDiv();
        } catch (e) {
            displayDynamicData();
            hiddenResponsibilityData();
            hiddenDynamicDiv();
        }
    })

    //点击切换的时候针对限值的处理
    function dealLimitValue(time) {
        try {
            var limitValue = contentBody_list[time].limitValue;
            if (limitValue === undefined) {
                //执行操作后，将其置为未定义，也不做处理
                $("#limitValue").val(undefined);
            } else {
                //针对有效值来绘制限值标示线
                drawLimitValue(time, limitValue);
                $("#limitValue").val(limitValue);
            }
        } catch (e) {
            //暂时没有选择限值。不做处理
            $("#limitValue").val(undefined);
        }
        try {
            var limitStartTime = contentBody_list[time].limitStartTime;
            if (limitStartTime === undefined) {
                //执行操作后，将其置为未定义，也不做处理
                $("#limitStartTime").val(undefined);
            } else {
                //针对有效值来绘制限值标示线
                drawLimitStartTime(time, limitStartTime);
                $("#limitStartTime").val(limitStartTime);
            }
        } catch (e) {
            //暂时没有选择限值。不做处理
            $("#limitStartTime").val(undefined);
        }
        try {
            var limitEndTime = contentBody_list[time].limitEndTime;
            if (limitEndTime === undefined) {
                //执行操作后，将其置为未定义，也不做处理
                $("#limitEndTime").val(undefined);
            } else {
                //针对有效值来绘制限值标示线
                drawLimitEndTime(time, limitEndTime);
                $("#limitEndTime").val(limitEndTime);
            }
        } catch (e) {
            //暂时没有选择限值。不做处理
            $("#limitEndTime").val(undefined);
        }
    }

    //点击【生成动态谐波数据】按钮画图，此入口需要将cal_flag置为1，根据harm_data和p_data计算结果
    //动态责任数据波形变量
    var chartDynamic = null;
    $("#dynamicData").on("click", function () {
        var lineIndex = $("#lineIndex").val();
        var startTime = $("#startTime").val();
        var endTime = $("#endTime").val();
        var type = tiggleValue;
        var time = getTime();
        var dynamicIndex0;
        var userData=$userDataList.val();
        $.ajax({
            url: "/pqs9000/responsibility/getDynamicData",
            type: "post",
            data:{
              time:time,
              startTime:startTime,
              endTime:endTime,
              type:type,
              lineIndex:lineIndex,
              userDataIndex:userData,
              calFlag:0
            },
            dataType: "json",
            beforeSend: function () {
                dynamicIndex0 = ityzl_SHOW_LOAD_LAYER();
            },
            success: function (data) {
                if(data.code===200){
                    //后台数据获取正常，进行页面画图以及表格展示
                    var picData = data.body.datas;
                    //去画图
                    //先去初始化图形基础信息
                    initBasePic();
                    //根据后台返回的数据绘制波形图
                    initDynamicPic(picData);
                    contentBody_list[time].picData = picData;
                    //表格图数据
                    var responsibilityData = data.body.responsibilities;//是个集合对象，可以直接填入table中
                    $("#responsibilityDataIndex").val(data.body.responsibilityDataIndex);
                    initTable(responsibilityData);
                    contentBody_list[time].responsibilityData = responsibilityData;
                    displayDynamicDiv();
                    hiddenDynamicData();
                    displayResponsibilityData();
                }else if(data.code===500){
                    layer.msg('后台数据获取异常', {icon: 2, time: 2000});
                }else{
                    layer.msg(data.message, {icon: 2, time: 2000});
                }

                ityzl_CLOSE_LOAD_LAYER(dynamicIndex0);
            }
        })
    });


    //点击【生成谐波责任指标】按钮画图，此入口需要将cal_flag置为1，根据限值时间区间，FKdata、HKdata、harm_data、harm_mk调用程序接口
    $("#responsibilityData").on("click", function () {
        var startTime = $("#startTime").val();
        var endTime = $("#endTime").val();
        var time = getTime();
        var dynamicIndex0;
        //3个限值获取
        var limitValue=$("#limitValue").val();
        limitValue=limitValue.replace(/(^\s*)|(\s*$)/g, '');
        if(limitValue===""){
            limitValue=0;
        }
        var limitStartTime=$("#limitStartTime").val();
        limitStartTime=limitStartTime.replace(/(^\s*)|(\s*$)/g, '');
        var limitEndTime=$("#limitEndTime").val();
        limitEndTime=limitEndTime.replace(/(^\s*)|(\s*$)/g, '');
        var responsibilityIndex=$("#responsibilityDataIndex").val();
        $.ajax({
            url: "/pqs9000/responsibility/getResponsibilityData",
            type: "post",
            data:{
                time:time,
                startTime:startTime,
                endTime:endTime,
                limitValue:limitValue,
                limitStartTime:limitStartTime,
                limitEndTime:limitEndTime,
                responsibilityIndex:responsibilityIndex
            },
            dataType: "json",
            beforeSend: function () {
                dynamicIndex0 = ityzl_SHOW_LOAD_LAYER();
            },
            success: function (data) {
                if(data.code===200){
                    //后台数据获取正常，进行页面画图以及表格展示
                    var picData = data.body.datas;
                    //去画图
                    //先去初始化图形基础信息
                    initBasePic();
                    //根据后台返回的数据绘制波形图
                    initDynamicPic(picData);
                    contentBody_list[time].picData = picData;
                    //表格图数据
                    var responsibilityData = data.body.responsibilities;//是个集合对象，可以直接填入table中
                    initTable(responsibilityData);
                    contentBody_list[time].responsibilityData = responsibilityData;
                    displayDynamicDiv();
                    hiddenDynamicData();
                    displayResponsibilityData();
                }else if(data.code===500){
                    layer.msg('后台数据获取异常', {icon: 2, time: 2000});
                }else{
                    layer.msg(data.message, {icon: 2, time: 2000});
                }
                ityzl_CLOSE_LOAD_LAYER(dynamicIndex0);
            }
        })
    })


    //初始化动态责任图形基础信息
    function  initBasePic() {
        //绘制瞬时波形图
        Highcharts.stockChart('dynamicPic', {
            chart: {
                type: 'spline',
            },
            tooltip: {
                borderColor: grey,
                backgroundColor: 'rgba(105,105,105,0.7)',
                style: {
                    color: 'white',
                    fontSize: "10px",
                    padding: 10,
                },
                formatter: function () {
                    var s = '<b>时刻：'
                        + Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x)
                        + '</b>';
                    //获取是电压 还是 电流，以及谐波次数作为提示
                    $.each(this.points, function () {
                        s += '<br/>' + this.series.name + ': ' +
                            this.y.toFixed(4);
                    });
                    return s;
                },
                shared: true
            },
            rangeSelector: {
                enabled: false,
            },
            //导航器各项属性设置
            navigator: {
                enabled: false
            },
            scrollbar: {
                enabled: false
            },
            exporting: false,
            credits: false,
            xAxis: {
                labels: {
                    step: 2
                },
                type: 'datetime',
                dateTimeLabelFormats: {
                    second: '%H:%M:%S',
                    minute: '%H:%M',
                    hour: '%H:%M',
                    day: '%m-%d',
                    week: '%m-%d',
                    month: '%Y-%m',
                    year: '%Y'
                },
            },
            yAxis: {
                showLastLabel: true,//显示纵坐标最大值，highstock默认不显示最大值，即默认为false
                // allowDecimals: false,
                opposite: false
            },
            series: [],
            noData: {
                style: {
                    fontWeight: 'bold',
                    fontSize: '15px',
                    color: '#303030'
                }
            }
        }, function (c) {
            chartDynamic = c;
        });
    }

    //绘制动态相关责任图形
    function initDynamicPic(picData) {
        if(picData!==null&picData.length>=1){
            for (var i=0;i<picData.length;i++){
                var data=assembleData(picData,i);
                var name=picData[i].customerName;
                chartDynamic.addSeries({
                    name: name,
                    type: 'spline',
                    data: data
                }, false);
            }
            chartDynamic.redraw(); //刷新
        }
    }
    //根据索引返回指定动态责任数据
    function assembleData(data, i) {
        var picData = [];
        for (var j = 0; j < data[i].timeDatas.length; j++) {
            var value= data[i].valueDatas[j];
            if(value===0){
                value=0.0;
            }
            picData.push([data[i].timeDatas[j], value])
        }
        return picData;
    }
    //填充用户责任量化表格
    function initTable(responsibilityData) {
        console.log(responsibilityData)
        $("#responsibilityTable").DataTable({
            data: responsibilityData,
            autoWidth: false,
            order: [[1,"desc"]],
            columnDefs: [
                {"width": "70%", "targets": 0},
                {"width": "30%", "targets": 1},
            ],
            paging: false,
            lengthChange: false,
            searching: false,
            destroy: true,
            scrollY: tableHeight,
            info: false,
            pageLength: 100,
            language: {
                url: '/pqs9000/json/chine.json',
            },
            columns: [
                {data: 'customerName'},
                {data: 'responsibilityData',
                    render:function (data, type, full, meta) {
                       if(isNaN(data)){
                           return "数据不充足，无法统计";
                       }else{
                            return data;
                       }
                    }}
            ],
        })
    }



    //显示和隐藏【生成动态谐波数据】按钮
    function displayDynamicData() {
        $("#dynamicData").removeClass("disnone")
        $("#dynamicData").addClass("div-inline")
    }

    function hiddenDynamicData() {
        $("#dynamicData").removeClass("div-inline")
        $("#dynamicData").addClass("disnone")
    }


    //显示和隐藏【历史谐波数据波形图】
    function displayHistoryData() {
    }

    function hiddenHistoryData() {
        $("#harmonicHistoryData").empty()
    }

    //显示和隐藏【限值输入的三个框】
    function displayLimitDiv() {
        $("#limitDiv").removeClass("disnone")
        $("#limitDiv").addClass("block")
    }

    function hiddenLimitDiv() {
        $("#limitDiv").removeClass("block")
        $("#limitDiv").addClass("disnone")
    }

    //显示和隐藏【动态谐波数据以及责任表格区域】
    function displayDynamicDiv() {
        $("#dynamicDiv").removeClass("disnone")
        $("#dynamicDiv").addClass("block")
    }

    function hiddenDynamicDiv() {
        $("#dynamicDiv").removeClass("block")
        $("#dynamicDiv").addClass("disnone")
    }



    //显示和隐藏【生成谐波责任指标】按钮
    function displayResponsibilityData() {
        $("#responsibilityData").removeClass("disnone")
        $("#responsibilityData").addClass("block")
        $("#limit").removeClass("disnone")
        $("#limit").addClass("div-inline")
    }

    function hiddenResponsibilityData() {
        $("#responsibilityData").removeClass("block")
        $("#responsibilityData").addClass("disnone")
        $("#limit").removeClass("div-inline")
        $("#limit").addClass("disnone")
    }


    //将字符串日期转为毫秒数
    function getTimeDate(time) {
        return Date.parse(new Date(time));
    }

    //清空限值元素的所有数据
    function clearValue() {
        $("#limitValue").val(undefined);
        $("#limitStartTime").val(undefined);
        $("#limitEndTime").val(undefined);
    }

    //清空谐波次内对象的限值
    function clearObjectValue(time) {
        try{
            contentBody_list[time].limitValue =undefined;
            contentBody_list[time].limitStartTime = undefined;
            contentBody_list[time].limitEndTime = undefined;
        }catch (e) {
            //不做操作，可能是第一次查询数据
        }

    }

    //清空动态数据和责任数据同时隐藏对应的内容
    function clearResponsibilityData(time) {
        try{
            contentBody_list[time].picData = undefined;
            contentBody_list[time].responsibilityData = undefined;
            hiddenDynamicDiv();
        }catch (e) {
            //不做操作，可能是第一次查询数据
        }
    }

    //获取当前导航栏次数
    function getTime() {
        var time = $("#mainContainer li[class='active'] a").text();
        time = time.replace("次谐波", "");
        time = time.replace(/(^\s*)|(\s*$)/g, '');
        return time;
    }


</script>
</html>
