/**
 * @param id
 * @returns 获取高级算法数据
 */
var layerId = -1;

var maxytmp = filterXSS($("#maxy").val());
var minytmp = filterXSS($("#miny").val());
var timetmp = filterXSS($("#time").val());
var pttmp = filterXSS($("#pt").val());
var maxy = maxytmp * 1.5;
var miny = minytmp * 1.5;
var time = timetmp;
var pt = pttmp;
var color;

$(document).ready(function() {
    getThemeColor();
});
/**
 * @增加事件是否调用高级算法
 * @已调用：直接从文件获取需要展示的信息
 * @未调用：调用高级算法dll，更新数据库数据并保存文件
 */
function analysis(eventIndex) {
    layerId = ityzl_SHOW_LOAD_LAYER();
    $.ajax({
        type: 'POST',
        dataType: "json",
        data: {
            eventIndex: eventIndex
        },
        url: '/pqs9200/area/analysis',
        success: function (data) {
            ityzl_CLOSE_LOAD_LAYER(layerId);
            processData(data);
        },
        error: function () {
            ityzl_CLOSE_LOAD_LAYER(layerId);
            layer.msg("高级分析失败！");
        }
    });
}

/**
 *
 * @param data
 * @returns 处理数据 获取X轴坐标的最大最小值 将初始位置设为分段位置的Y值 将结束位置设为分段位置的X值
 */
function processData(data) {
    if (data.length == 0) {
        ityzl_CLOSE_LOAD_LAYER(layerId);
        return;
    }

    var scatter = [];
    var m = [];
    var p = [];
    var q = [];
    var xpoint = [];

    for (var i = 0; i < data.evt_buf[0].SEG_T_num; i++) {
        var value = [];
        value.push(data.smp_x[data.evt_buf[0].SEG_T_idx[i]].toString());
        value.push(miny);
        scatter.push(value);
        xpoint.push(data.smp_x[data.evt_buf[0].SEG_T_idx[i]].toString());

        var yvalue = [];
        yvalue.push(data.smp_x[data.evt_buf[0].SEG_T_idx[i]].toString());
        yvalue.push(maxy);

        var nvalue = [];
        nvalue.push(data.smp_x[data.evt_buf[0].SEG_T_idx[i]].toString());
        nvalue.push(null);
        m.push(value);
        m.push(yvalue);
        m.push(nvalue);
    }

    // var p = Math.max.apply(Math,t);//取暂降点最大Y值
    var point = [];
    var pointmin = [];
    for (var i = 0; i < data.evt_buf[0].SEG_T_num; i++) {
        var value = [];
        var value1 = [];
        value.push((data.smp_x[data.evt_buf[0].SEG_T_idx[i]]));
        value.push(maxy);
        value.push(miny);
        point.push(value);

        value1.push((data.smp_x[data.evt_buf[0].SEG_T_idx[i]]));
        value1.push(miny);
        pointmin.push(value1);

    }

    for (var i = 0; i < point.length; i = i + 1) {
        var tmp = [];
        if (i % 2 == 0) {
            p.push(point[i]);
        } else {
            p.push(point[i]);
            p.push(tmp);
        }
    }

    var xa = [];
    var xb = [];
    var xc = [];
    var trige;

    // 抽取数据
    var a = data.smp_a.slice(0, data.smp_len);
    var b = data.smp_b.slice(0, data.smp_len);
    var c = data.smp_c.slice(0, data.smp_len);
    var x = data.smp_x.slice(0, data.smp_len);

    for (var n = 0; n < x.length; n++) {
        var ax = [];
        ax.push(x[n]);
        ax.push(a[n]);
        xa.push(ax);

        var bx = [];
        bx.push(x[n]);
        bx.push(b[n]);
        xb.push(bx);

        var cx = [];
        cx.push(x[n]);
        cx.push(c[n]);
        xc.push(cx);
    }
    if(data.qvvr_utbl_info != null){
    	trige = data.qvvr_utbl_info[0].trigTime[0]

        // 绘图
        drawPicUtbl(scatter, m, p, xa, xb, xc, trige);
    }else{
        // 绘图
        drawPic(scatter, m, p, xa, xb, xc);
    }

    var jsonData = '[';
    for (var i = 0; i < data.evt_buf.length; i++) {
        if (i == data.evt_buf.length - 1) {
            jsonData += '["' + (i + 1) + '","' + data.evt_buf[i].POW_a.toFixed(2) + '","'
                + data.evt_buf[i].POW_b.toFixed(2) + '","'
                + data.evt_buf[i].POW_c.toFixed(2) + '","';
            jsonData += (data.evt_buf[i].Voltagechange_Va / 1000).toFixed(5) + '","'
                + (data.evt_buf[i].Voltagechange_Vb / 1000).toFixed(5) + '","'
                + (data.evt_buf[i].Voltagechange_Vc / 1000).toFixed(5) + '","';
            jsonData += (data.evt_buf[i].angle_diff_an[0] + data.evt_buf[i].angle_diff_ap[0]).toFixed(2) + '","'
                + (data.evt_buf[i].angle_diff_bn[0] + data.evt_buf[i].angle_diff_bp[0]).toFixed(2) + '","'
                + (data.evt_buf[i].angle_diff_cn[0] + data.evt_buf[i].angle_diff_cp[0]).toFixed(2) + '","';
            jsonData += (data.evt_buf[i].SEG_T_num + 1) + '","';
            jsonData += (data.evt_buf[i].bph_max_value[0]).toFixed(2) + '","'
                + (judge(data.sagType[0], 1)) + '","' + (judge(data.sagReason[0], 2)) + '"]';
        } else {
            jsonData += '["' + (i + 1) + '","' + data.evt_buf[i].POW_a.toFixed(2) + '","'
                + data.evt_buf[i].POW_b.toFixed(2) + '","'
                + data.evt_buf[i].POW_c.toFixed(2) + '","';
            jsonData += (data.evt_buf[i].Voltagechange_Va / 1000).toFixed(5) + '","'
                + (data.evt_buf[i].Voltagechange_Vb / 1000).toFixed(5) + '","'
                + (data.evt_buf[i].Voltagechange_Vc / 1000).toFixed(5) + '","';
            jsonData += (data.evt_buf[i].angle_diff_an[0] + data.evt_buf[i].angle_diff_ap[0]).toFixed(2) + '","'
                + (data.evt_buf[i].angle_diff_bn[0] + data.evt_buf[i].angle_diff_bp[0]).toFixed(2) + '","'
                + (data.evt_buf[i].angle_diff_cn[0] + data.evt_buf[i].angle_diff_cp[0]).toFixed(2) + '","';
            jsonData += (data.evt_buf[i].SEG_T_num + 1) + '","';
            jsonData += (data.evt_buf[i].bph_max_value[0]).toFixed(2) + '","'
                + (judge(data.sagType[0], 1)) + '","' + (judge(data.sagReason[0], 2)) + '"],';
        }
    }
    jsonData += ']';
    var info = $.parseJSON(jsonData);

    var u3min = (data.evt_buf[0].u3_min[0]).toFixed(2);
    var table = $('#analysisTab').DataTable({
        scrollX: false,
        lengthChange: false,
        destroy: true,
        searching: false,
        info: false,
        paging: false,
        language: {
            url: '/pqs9200/json/chine.json'
        },
        data: info
    });

    if(data.power_before_buf != null){
        var jsonData1 = '[["' + data.power_before_buf[0].fundP[0].toFixed(2) + '","'
    	    + data.power_before_buf[0].fundP[1].toFixed(2) + '","'
    	    + data.power_before_buf[0].fundP[2].toFixed(2) + '","'
        	+ data.power_before_buf[0].fundP[3].toFixed(2) + '","'
        	+ data.power_before_buf[0].fundP[4].toFixed(2) + '","';
        jsonData1 += data.power_before_buf[0].fundQ[0].toFixed(2) + '","'
    	    + data.power_before_buf[0].fundQ[1].toFixed(2) + '","'
    	    + data.power_before_buf[0].fundQ[2].toFixed(2) + '","'
    		+ data.power_before_buf[0].fundQ[3].toFixed(2) + '","'
    		+ data.power_before_buf[0].fundQ[4].toFixed(2) + '","';
        jsonData1 += data.power_before_buf[0].fundS[0].toFixed(2) + '","'
    	    + data.power_before_buf[0].fundS[1].toFixed(2) + '","'
    	    + data.power_before_buf[0].fundS[2].toFixed(2) + '","'
    		+ data.power_before_buf[0].fundS[3].toFixed(2) + '","'
    		+ data.power_before_buf[0].fundS[4].toFixed(2) + '"]]';
        var info1 = $.parseJSON(jsonData1);

        document.getElementById('tab1').style.display = 'block';
        var table1 = $('#analysisTab1').DataTable({
            scrollX: false,
            lengthChange: false,
            destroy: true,
            searching: false,
            info: false,
            paging: false,
            language: {
                url: '/pqs9200/json/chine.json'
            },
            data: info1
        });
    }else{
        document.getElementById('tab1').style.display = 'none';
    }

    if(data.power_after_buf != null){
        var jsonData2 = '[["' + data.power_after_buf[0].fundP[0].toFixed(2) + '","'
    	    + data.power_after_buf[0].fundP[1].toFixed(2) + '","'
    	    + data.power_after_buf[0].fundP[2].toFixed(2) + '","'
        	+ data.power_after_buf[0].fundP[3].toFixed(2) + '","'
        	+ data.power_after_buf[0].fundP[4].toFixed(2) + '","';
        jsonData2 += data.power_after_buf[0].fundQ[0].toFixed(2) + '","'
    	    + data.power_after_buf[0].fundQ[1].toFixed(2) + '","'
    	    + data.power_after_buf[0].fundQ[2].toFixed(2) + '","'
    		+ data.power_after_buf[0].fundQ[3].toFixed(2) + '","'
    		+ data.power_after_buf[0].fundQ[4].toFixed(2) + '","';
        jsonData2 += data.power_after_buf[0].fundS[0].toFixed(2) + '","'
    	    + data.power_after_buf[0].fundS[1].toFixed(2) + '","'
    	    + data.power_after_buf[0].fundS[2].toFixed(2) + '","'
    		+ data.power_after_buf[0].fundS[3].toFixed(2) + '","'
    		+ data.power_after_buf[0].fundS[4].toFixed(2) + '"]]';
        var info2 = $.parseJSON(jsonData2);

        document.getElementById('tab2').style.display = 'block';
        var table2 = $('#analysisTab2').DataTable({
            scrollX: false,
            lengthChange: false,
            destroy: true,
            searching: false,
            info: false,
            paging: false,
            language: {
                url: '/pqs9200/json/chine.json'
            },
            data: info2
        });
    }else{
        document.getElementById('tab2').style.display = 'none';
    }

    if(data.qvvr_direction_info != null){
    	var trig_time = data.qvvr_direction_info[0].trigTime[0] + "-"
    		+ data.qvvr_direction_info[0].trigTime[1] + "-"
    		+ data.qvvr_direction_info[0].trigTime[2] + " "
    		+ data.qvvr_direction_info[0].trigTime[3] + ":"
    		+ data.qvvr_direction_info[0].trigTime[4] + ":"
    		+ data.qvvr_direction_info[0].trigTime[5] + "."
    		+ data.qvvr_direction_info[0].trigTime[6];
        var jsonData3 = '[["' + trig_time + '","'
        	+ data.qvvr_direction_info[0].qvvrBeforeRms[0].toFixed(2) + '","'
    	    + data.qvvr_direction_info[0].qvvrBeforeRms[1].toFixed(2) + '","'
    	    + data.qvvr_direction_info[0].qvvrBeforeRms[2].toFixed(2) + '","'
        	+ data.qvvr_direction_info[0].qvvrBeforeRms[3].toFixed(2) + '","'
        	+ data.qvvr_direction_info[0].qvvrBeforeRms[4].toFixed(2) + '","'
        	+ data.qvvr_direction_info[0].qvvrBeforeRms[5].toFixed(2) + '","';
        jsonData3 += data.qvvr_direction_info[0].qvvrBeforeZk[0].toFixed(2) + '","'
    	    + data.qvvr_direction_info[0].qvvrBeforeZk[1].toFixed(2) + '","'
    	    + data.qvvr_direction_info[0].qvvrBeforeZk[2].toFixed(2) + '","'
    		+ data.qvvr_direction_info[0].qvvrBeforeZk[3].toFixed(2) + '","'
    		+ data.qvvr_direction_info[0].qvvrBeforeZk[4].toFixed(2) + '","'
    		+ data.qvvr_direction_info[0].qvvrBeforeZk[5].toFixed(2) + '","';
        jsonData3 += data.qvvr_direction_info[0].qvvrOccurRms[0].toFixed(2) + '","'
		    + data.qvvr_direction_info[0].qvvrOccurRms[1].toFixed(2) + '","'
		    + data.qvvr_direction_info[0].qvvrOccurRms[2].toFixed(2) + '","'
			+ data.qvvr_direction_info[0].qvvrOccurRms[3].toFixed(2) + '","'
			+ data.qvvr_direction_info[0].qvvrOccurRms[4].toFixed(2) + '","'
			+ data.qvvr_direction_info[0].qvvrOccurRms[5].toFixed(2) + '","';
        jsonData3 += data.qvvr_direction_info[0].qvvrOccurZk[0].toFixed(2) + '","'
		    + data.qvvr_direction_info[0].qvvrOccurZk[1].toFixed(2) + '","'
		    + data.qvvr_direction_info[0].qvvrOccurZk[2].toFixed(2) + '","'
			+ data.qvvr_direction_info[0].qvvrOccurZk[3].toFixed(2) + '","'
			+ data.qvvr_direction_info[0].qvvrOccurZk[4].toFixed(2) + '","'
			+ data.qvvr_direction_info[0].qvvrOccurZk[5].toFixed(2) + '","';
        var posinfo = "";
        if(data.qvvr_direction_info[0].qvvrPosInfo[0] == "Upper"){
        	posinfo = "上游";
        }else if(data.qvvr_direction_info[0].qvvrPosInfo[0] == "Lower"){
        	posinfo = "下游";
        }else{
        	posinfo = "未知";
        }
        jsonData3 += posinfo + '"]]';
        var info3 = $.parseJSON(jsonData3);

        document.getElementById('tab3').style.display = 'block';
        var table3 = $('#analysisTab3').DataTable({
            scrollX: false,
            lengthChange: false,
            destroy: true,
            searching: false,
            info: false,
            paging: false,
            language: {
                url: '/pqs9200/json/chine.json'
            },
            data: info3
        });
    }else{
        document.getElementById('tab3').style.display = 'none';
    }
}

function initTable(data, $width) {
    layui.use('table', function () {
        var table = layui.table;
        table.render({
            elem: '#analysisTab',
            data: data,
            height: 150,
            cols: [[ // 标题栏
                {
                    field: 'name',
                    title: '事件名称',
                    width: $width * 0.5,
                    align: 'center'
                }, {
                    field: 'result',
                    title: '事件结果',
                    width: $width * 0.45,
                    align: 'center'
                }]],
            skin: 'line,row' // 表格风格
            ,
            page: false // 是否显示分页
            ,
            limit: data.length
        });
    });
}

/**
 * @param xV
 * @param yV
 * @param xMin
 * @param xMax
 * @returns 绘图
 */
function drawPic(scatter, m, p, a, b, c) {
    var cu = [['0', miny / 1.5]];
    var height = $(window).height();
    height = height - 125;
    var $analysis = $("#analysis");
    $analysis.eq(0).css("height", height);

    var title = '发生时刻：' + time + ' PT变比：' + pt;

    Highcharts.stockChart('analysis', {
        title: {
            text: title,
            floating: true,
            style: {fontSize: "14px"},
            y: -12
        },
        chart: {
            spacingTop: 30
        },
        //导出选中背景色
        navigation: {
            menuItemHoverStyle: {
                background: color,
                color: "#ffffff"
            },
        },
        tooltip: {
            borderColor: grey,
            backgroundColor: 'rgba(105,105,105,0.7)',
            style: {
                color: 'white',
                fontSize: "15px",
                padding: 10,
            },
            formatter: function () {
                var s = '<b>时刻：' + this.x + 'ms</b>';
                $.each(this.points, function () {
                    if (this.series.name === '跳变期') {

                    } else {
                        s += '<br/>' + this.series.name + ': ' +
                            this.y.toFixed(2) + 'kV';
                    }
                });
                return s;
            },
            shared: true
        },
        rangeSelector: {
            enabled: false,
        },
        //导航器各项属性设置
        navigator: {
            margin: 1,
            xAxis: {
                labels: {
                    formatter: function () {
                        return this.value;
                    }
                }
            },
            series: [{
                type: 'spline',
                data: a
            }, {
                type: 'spline',
                data: b
            }, {
                type: 'spline',
                data: c
            }]
        },
        scrollbar: {
            enabled: false
        },
        credits: false,
        colors: [grey, yellow, green, red],
        xAxis: {
            title: {
                text: 'ms',
                enabled: true,
                align: 'high'
            },
            labels: {
                formatter: function () {
                    return this.value;
                }
            }
        },
        yAxis: {
            title: {
                align: 'high',
                offset: 0,
                text: 'kV',
                rotation: 0,
                y: -10
            },
            max: maxy,
            min: miny,
            opposite: false
        },
        legend: {
            align: 'left',
            verticalAlign: 'top',
            enabled: true,
            symbolRadius: 0
        },
        series: [{
            type: 'arearange',
            name: '跳变期',
            data: p
        }, {
            type: 'spline',
            marker: {
                symbol: 'circle'
            },
            name: 'A相',
            data: a
        }, {
            type: 'spline',
            marker: {
                symbol: 'circle'
            },
            name: 'B相',
            data: b
        }, {
            type: 'spline',
            marker: {
                symbol: 'circle'
            },
            name: 'C相',
            data: c
        }, {
            type: 'scatter',
            name: '暂降触发点',
            marker: {
                symbol: 'url(/pqs9200/images/point.png)',
                width: 16,
                height: 16
            },
            data: cu
        }
        ]
    });
}
function drawPicUtbl(scatter, m, p, a, b, c, trige) {
    var cu = [['0', miny / 1.5]];
    var trigeTime =  [[trige, miny / 1.5]];
    var height = $(window).height();
    height = height - 125;
    var $analysis = $("#analysis");
    $analysis.eq(0).css("height", height);

    var title = '发生时刻：' + time + ' PT变比：' + pt;

    Highcharts.stockChart('analysis', {
        title: {
            text: title,
            floating: true,
            style: {fontSize: "14px"},
            y: -12
        },
        chart: {
            spacingTop: 30
        },
        //导出选中背景色
        navigation: {
            menuItemHoverStyle: {
                background: color,
                color: "#ffffff"
            },
        },
        tooltip: {
            borderColor: grey,
            backgroundColor: 'rgba(105,105,105,0.7)',
            style: {
                color: 'white',
                fontSize: "15px",
                padding: 10,
            },
            formatter: function () {
                var s = '<b>时刻：' + this.x + 'ms</b>';
                $.each(this.points, function () {
                    if (this.series.name === '跳变期') {

                    } else {
                        s += '<br/>' + this.series.name + ': ' +
                            this.y.toFixed(2) + 'kV';
                    }
                });
                return s;
            },
            shared: true
        },
        rangeSelector: {
            enabled: false,
        },
        //导航器各项属性设置
        navigator: {
            margin: 1,
            xAxis: {
                labels: {
                    formatter: function () {
                        return this.value;
                    }
                }
            },
            series: [{
                type: 'spline',
                data: a
            }, {
                type: 'spline',
                data: b
            }, {
                type: 'spline',
                data: c
            }]
        },
        scrollbar: {
            enabled: false
        },
        credits: false,
        colors: [grey, yellow, green, red],
        xAxis: {
            title: {
                text: 'ms',
                enabled: true,
                align: 'high'
            },
            labels: {
                formatter: function () {
                    return this.value;
                }
            }
        },
        yAxis: {
            title: {
                align: 'high',
                offset: 0,
                text: 'kV',
                rotation: 0,
                y: -10
            },
            max: maxy,
            min: miny,
            opposite: false
        },
        legend: {
            align: 'left',
            verticalAlign: 'top',
            enabled: true,
            symbolRadius: 0
        },
        series: [{
            type: 'arearange',
            name: '跳变期',
            data: p
        }, {
            type: 'spline',
            marker: {
                symbol: 'circle'
            },
            name: 'A相',
            data: a
        }, {
            type: 'spline',
            marker: {
                symbol: 'circle'
            },
            name: 'B相',
            data: b
        }, {
            type: 'spline',
            marker: {
                symbol: 'circle'
            },
            name: 'C相',
            data: c
        }, {
            type: 'scatter',
            name: '暂降触发点',
            marker: {
                symbol: 'url(/pqs9200/images/point.png)',
                width: 16,
                height: 16
            },
            data: cu
        }, {
            type: 'scatter',
            name: '暂降突变点',
            marker: {
                symbol: 'url(/pqs9200/images/point.png)',
                width: 16,
                height: 16
            },
            data: trigeTime
        }
        ]
    });
}
function judge(data, type) { //1-类型：其他  2-原因：其他
    return (data == null ? (type == 1 ? '其他' : '其他') : data);
}

//获取主题颜色
function getThemeColor() {
    $.ajax({
        type: "POST",
        url: "/pqs9200/theme/getThemeInfo",
        async: false,
        dataType: 'json',
        success: function (data) {
            color = data.body.value;
        }
    })
}
