let picWavesData;
let picNumbers = 0;

$(document).ready(function () {
    let idea;
    let indexes = $("#eventIndex").val();
    $.ajax({
        type: "POST",
        url: "/pqs9200/area/getWaveDataCompare",
        dataType: "json",
        data: {
            indexes: indexes
        },
        beforeSend: function () {
            idea = ityzl_SHOW_LOAD_LAYER();
        },
        success: function (data) {
            if (data.code === 500) {
                layer.msg("没有事件的波形文件", {
                    icon: 5,
                    time: 3000
                });
                initWaves(null);
            } else {
                picNumbers = data.body.length;
                initWaves(data.body);
            }
            //***********关闭loading
            ityzl_CLOSE_LOAD_LAYER(idea);
        }
    });
});

/**
 * 处理多个事件波形
 * @param waveDatas 多个波形数据
 */
function initWaves(waveDatas) {
    picWavesData = [];
    if (picNumbers > 0) {
        for (let i = 0; i < picNumbers; i++) {
            let wp = waveDatas[i];
            if (null !== wp) {
                let isOpen = wp.openTri;
                let time = wp.time, type = wp.waveType, severity = wp.yzd, iPhasic;
                iPhasic = wp.iPhasic;
                if (iPhasic === 0) {
                    iPhasic = 1;
                }
                let eventValue = wp.eventValue, persistTime = wp.persistTime, lineName = wp.lineName,
                    subName = wp.subName;
                //严重度为负，事件为暂升事件
                if (severity < 0) {
                    severity = "/";
                    type = "/";
                }
                //筛选数据 *****start
                //RMS最小值横、纵坐标、相别名称
                let rmsvFirstX = 0, rmsvFirstY = 0, firstZhou = 'a';
                //每个波形对应的最大最小值
                let ifmax, ifmin, rfmax, rfmin;
                let shunshiFA = [], shunshiFB = [], shunshiFC = [], rmsFA = [], rsmFB = [], rmsFC = [];
                let aTitle = "", bTitle = "", cTitle = "";
                let shunData = wp.sunData;
                if (shunData.length > 0) {
                    let rmsData = wp.rmsData;
                    let xishu = Number(wp.pt) / 1000;
                    for (let titleI = 1; titleI <= iPhasic; titleI++) {
                        switch (titleI) {
                            case 1:
                                aTitle = wp.a;
                                break;
                            case 2:
                                bTitle = wp.b;
                                break;
                            case 3:
                                cTitle = wp.c;
                                break;
                        }
                    }


                    //给瞬时赋个初始值
                    if (shunData.length > 0) {
                        if (shunData[0][1] !== undefined) {
                            ifmax = shunData[0][1] * xishu;
                            ifmin = shunData[0][1] * xishu;
                        }
                    }
                    //给RMS付个初始值
                    if (rmsData.length > 0) {
                        if (rmsData[0][1] !== undefined) {
                            rfmax = rmsData[0][1] * xishu;
                            rfmin = rmsData[0][1] * xishu;
                            rmsvFirstY = rmsData[0][1] * xishu;
                            rmsvFirstX = rmsData[0][0];
                        }
                    }


                    //瞬时值--同时还需要获取出瞬时值的一次、二次的最大最小值
                    for (let shun = 0; shun < shunData.length; shun++) {
                        if (shunData[shun][1] === undefined) {
                            break;
                        }
                        let shunFirstA, shunFirstB, shunFirstC;
                        //根据波形数据相的数量来筛选数据
                        switch (iPhasic) {
                            case 1:
                                shunFirstA = shunData[shun][1] * xishu;
                                shunshiFA.push([shunData[shun][0], shunFirstA]);
                                ifmax = ifmax > shunFirstA ? ifmax : shunFirstA;
                                ifmin = ifmin < shunFirstA ? ifmin : shunFirstA;
                                break;
                            case 2:
                                shunFirstA = shunData[shun][1] * xishu;
                                shunFirstB = shunData[shun][2] * xishu;
                                shunshiFA.push([shunData[shun][0], shunFirstA]);
                                shunshiFB.push([shunData[shun][0], shunFirstB]);
                                ifmax = getMaxTwo(ifmax, shunFirstA, shunFirstB);
                                ifmin = getMinOpen(ifmin, shunFirstA, shunFirstB);
                                break;
                            case 3:
                                shunFirstA = shunData[shun][1] * xishu;
                                shunFirstB = shunData[shun][2] * xishu;
                                shunFirstC = shunData[shun][3] * xishu;
                                shunshiFA.push([shunData[shun][0], shunFirstA]);
                                shunshiFB.push([shunData[shun][0], shunFirstB]);
                                shunshiFC.push([shunData[shun][0], shunFirstC]);
                                ifmax = getMax(ifmax, shunFirstA, shunFirstB, shunFirstC);
                                //如果接线方式是V
                                if (isOpen) {
                                    ifmin = getMinOpen(ifmin, shunFirstA, shunFirstC);
                                } else {
                                    ifmin = getMin(ifmin, shunFirstA, shunFirstB, shunFirstC);
                                }
                                break;
                        }
                    }

                    //RMS值--同时还需要获取出RMS值的一次、二次的最大最小值
                    for (let rms = 0; rms < rmsData.length; rms++) {
                        if (rmsData[rms][1] === undefined) {
                            break;
                        }
                        let rmsFirstA, rmsFirstB, rmsFirstC;
                        //根据波形数据相的数量来筛选数据
                        switch (iPhasic) {
                            case 1:
                                rmsFirstA = rmsData[rms][1] * xishu;
                                rmsFA.push([rmsData[rms][0], rmsFirstA]);
                                rfmax = rfmax > rmsFirstA ? rfmax : rmsFirstA;
                                rfmin = rfmin < rmsFirstA ? rfmin : rmsFirstA;
                                if (rfmin < rmsvFirstY) {
                                    rmsvFirstY = rfmin;
                                    firstZhou = "a";
                                    rmsvFirstX = rmsData[rms][0];
                                }
                                break;
                            case 2:
                                rmsFirstA = rmsData[rms][1] * xishu;
                                rmsFirstB = rmsData[rms][2] * xishu;
                                rmsFA.push([rmsData[rms][0], rmsFirstA]);
                                rsmFB.push([rmsData[rms][0], rmsFirstB]);
                                rfmax = getMaxTwo(rfmax, rmsFirstA, rmsFirstB);
                                rfmin = getMinOpen(rfmin, rmsFirstA, rmsFirstB);
                                if (rfmin < rmsvFirstY) {
                                    rmsvFirstY = rfmin;
                                    if (rfmin === rmsFirstA) {
                                        firstZhou = "a";
                                    } else if (rfmin === rmsFirstB) {
                                        firstZhou = "b";
                                    }
                                    rmsvFirstX = rmsData[rms][0];
                                }

                                break;
                            case 3:
                                rmsFirstA = rmsData[rms][1] * xishu;
                                rmsFirstB = rmsData[rms][2] * xishu;
                                rmsFirstC = rmsData[rms][3] * xishu;
                                rmsFA.push([rmsData[rms][0], rmsFirstA]);
                                rsmFB.push([rmsData[rms][0], rmsFirstB]);
                                rmsFC.push([rmsData[rms][0], rmsFirstC]);
                                rfmax = getMax(rfmax, rmsFirstA, rmsFirstB, rmsFirstC);
                                if (isOpen) {
                                    rfmin = getMinOpen(rfmin, rmsFirstA, rmsFirstC);
                                } else {
                                    rfmin = getMin(rfmin, rmsFirstA, rmsFirstB, rmsFirstC);
                                }
                                if (rfmin < rmsvFirstY) {
                                    rmsvFirstY = rfmin;
                                    if (rfmin === rmsFirstA) {
                                        firstZhou = "a";
                                    } else if (rfmin === rmsFirstB) {
                                        firstZhou = "b";
                                    } else {
                                        firstZhou = "c";
                                    }
                                    rmsvFirstX = rmsData[rms][0];
                                }
                                break;
                        }
                    }
                }


                //瞬时一次值最大最小值
                let instantF = {};
                let RMSF = {};
                let RMSFMinDetail = {};
                let shunshiF = {};
                let RMSFWave = {};
                let title = {};
                let waveMateInfo = {};
                //三相名称
                title.aTitle = aTitle;
                title.bTitle = bTitle;
                title.cTitle = cTitle;
                //每个波形对应的三相数据
                shunshiF.shunshiFA = shunshiFA.slice(0);
                shunshiF.shunshiFB = shunshiFB.slice(0);
                shunshiF.shunshiFC = shunshiFC.slice(0);
                RMSFWave.rmsFA = rmsFA.slice(0);
                RMSFWave.rmsFB = rsmFB.slice(0);
                RMSFWave.rmsFC = rmsFC.slice(0);
                //赋值对应的最大最小值
                instantF.max = ifmax;
                instantF.min = ifmin;
                RMSF.max = rfmax;
                RMSF.min = rfmin;
                //精确到小数位2位
                rmsvFirstY = rmsvFirstY.toFixed(5);
                RMSFMinDetail.rmsvFirstX = rmsvFirstX;
                RMSFMinDetail.rmsvFirstY = rmsvFirstY;
                RMSFMinDetail.firstZhou = firstZhou;
                //波形事件的元数据信息
                waveMateInfo.time = time;
                waveMateInfo.type = type;
                waveMateInfo.severity = severity;
                waveMateInfo.isOpen = isOpen;
                waveMateInfo.eventValue = eventValue;
                waveMateInfo.persistTime = persistTime;
                waveMateInfo.lineName = lineName;
                waveMateInfo.subName = subName;
                waveMateInfo.iPhasic = iPhasic;
                picWavesData.push(new waveData(instantF, RMSF, RMSFMinDetail, shunshiF, RMSFWave, title, waveMateInfo));
            } else {
                picWavesData.push(null)
            }
        }
    }
    //处理完后，开始画图
    drawPics();
}

/**
 * 绘制对比波形
 * */
function drawPics() {
    //清除之前增加的div
    $("#wave ~ .bx").remove();
    $("#rms ~ .bx").remove();
    if (picNumbers === 0) {
        layer.msg("没有事件的波形文件", {icon: 5, time: 3000});
    } else {
        for (let picCount = 0; picCount < picNumbers; picCount++) {
            //创建瞬时波形和RMS波形的DIV
            let height = $(window).height() - 25;
            let picHeight;
            if (picNumbers === 1) {
                picHeight = height;
            } else if (picNumbers > 1) {
                picHeight = height * 0.5;
            }
            let waveId = 'wave' + picCount;
            let rmsId = 'rms' + picCount;
            let newDivShunshi = $("<div class='bx' id='" + waveId + "'></div>");
            let newDivRms = $("<div class='bx' id='" + rmsId + "'></div>");
            $("#instance").append(newDivShunshi);
            $("#RMSD").append(newDivRms);
            $("#" + waveId).css("height", picHeight);
            $("#" + rmsId).css("height", picHeight);
            let isvisible = false;
            let cu = [], rmscu = [], title, max, min;
            let a = "", b = "", c = "";
            let adata = [], bdata = [], cdata = [];
            let radata = [], rbdata = [], rcdata = [];
            let rmsvX = 0, rmsvY = 0, zhou = 0;
            let colors = [];
            //当前循环的事件数据
            let tempWaveData = picWavesData[picCount];
            let show = true;
            if (tempWaveData == null) {
                cu = [];
                rmscu = [];
                title = '该事件暂无波形图';
            } else if(tempWaveData.shunshiF.shunshiFA.length===0){
                title = '变电站名称：' + tempWaveData.waveMateInfo.subName + ' 监测点名称：' + tempWaveData.waveMateInfo.lineName + ' 发生时刻：' + tempWaveData.waveMateInfo.time + ' 暂降幅值：' + tempWaveData.waveMateInfo.eventValue + '% 持续时间：' + tempWaveData.waveMateInfo.persistTime + "s";
                cu = [];
                rmscu = [];
            } else {
                title = '变电站名称：' + tempWaveData.waveMateInfo.subName + ' 监测点名称：' + tempWaveData.waveMateInfo.lineName + ' 发生时刻：' + tempWaveData.waveMateInfo.time + ' 暂降幅值：' + tempWaveData.waveMateInfo.eventValue + '% 持续时间：' + tempWaveData.waveMateInfo.persistTime + "s";
                if (Number(tempWaveData.waveMateInfo.eventValue) <= 90) {
                    isvisible = true;
                }
                if (tempWaveData.waveMateInfo.isOpen) {
                    show = false;
                }
                switch (tempWaveData.waveMateInfo.iPhasic) {
                    case 1:
                        a = tempWaveData.title.aTitle;
                        cu = [['0', tempWaveData.instantF.min]];
                        rmscu = [['0', tempWaveData.RMSF.min]];
                        max = tempWaveData.instantF.max;
                        min = tempWaveData.instantF.min;
                        adata = tempWaveData.shunshiF.shunshiFA;
                        radata = tempWaveData.RMSFWave.rmsFA;
                        rmsvX = tempWaveData.RMSFMinDetail.rmsvFirstX;
                        rmsvY = tempWaveData.RMSFMinDetail.rmsvFirstY;
                        zhou = tempWaveData.RMSFMinDetail.firstZhou;

                        colors.push(yellow);
                        colors.push("#fff");
                        colors.push("#fff");
                        break;
                    case 2:
                        a = tempWaveData.title.aTitle;
                        b = tempWaveData.title.bTitle;
                        cu = [['0', tempWaveData.instantF.min]];
                        rmscu = [['0', tempWaveData.RMSF.min]];
                        max = tempWaveData.instantF.max;
                        min = tempWaveData.instantF.min;
                        adata = tempWaveData.shunshiF.shunshiFA;
                        bdata = tempWaveData.shunshiF.shunshiFB;
                        radata = tempWaveData.RMSFWave.rmsFA;
                        rbdata = tempWaveData.RMSFWave.rmsFB;
                        rmsvX = tempWaveData.RMSFMinDetail.rmsvFirstX;
                        rmsvY = tempWaveData.RMSFMinDetail.rmsvFirstY;
                        zhou = tempWaveData.RMSFMinDetail.firstZhou;

                        colors.push(yellow);
                        colors.push(green);
                        colors.push("#fff");
                        break;
                    case 3:
                        a = tempWaveData.title.aTitle;
                        b = tempWaveData.title.bTitle;
                        c = tempWaveData.title.cTitle;
                        cu = [['0', tempWaveData.instantF.min]];
                        rmscu = [['0', tempWaveData.RMSF.min]];
                        max = tempWaveData.instantF.max;
                        min = tempWaveData.instantF.min;
                        adata = tempWaveData.shunshiF.shunshiFA;
                        bdata = tempWaveData.shunshiF.shunshiFB;
                        cdata = tempWaveData.shunshiF.shunshiFC;
                        radata = tempWaveData.RMSFWave.rmsFA;
                        rbdata = tempWaveData.RMSFWave.rmsFB;
                        rcdata = tempWaveData.RMSFWave.rmsFC;
                        rmsvX = tempWaveData.RMSFMinDetail.rmsvFirstX;
                        rmsvY = tempWaveData.RMSFMinDetail.rmsvFirstY;
                        zhou = tempWaveData.RMSFMinDetail.firstZhou;

                        colors.push(yellow);
                        colors.push(green);
                        colors.push(red);
                        break;
                }
            }

            Highcharts.stockChart(waveId, {
                title: {
                    text: title,
                    floating: true,
                    style: {fontSize: "14px"},
                    y: -12
                },
                chart: {
                    type: 'spline',
                    events: {
                        load: function () {
                            if (show) {
                                this.series[1].show();
                            } else {
                                this.series[1].hide();
                            }
                        }
                    },
                    spacingTop: 30
                },
                plotOptions: {
                    series: {
                        animation: false
                    }
                },
                exporting: {
                    enabled: false
                },
                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 () {
                            s += '<br/>' + this.series.name + ': ' +
                                this.y.toFixed(2) + 'kV';
                        });
                        return s;
                    },
                    enabled: true,
                    shared: true
                },
                rangeSelector: {
                    enabled: false
                },
                //导航器各项属性设置
                navigator: {
                    margin: 1,
                    height: 15,
                    xAxis: {
                        labels: {
                            formatter: function () {
                                return this.value;
                            }
                        }
                    },
                    series: [{
                        data: adata
                    }, {
                        data: bdata
                    }, {
                        data: cdata
                    }]
                },
                scrollbar: {
                    enabled: false
                },
                credits: false,
                colors: colors,
                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
                    },
                    showLastLabel: true,
                    max: max,
                    min: min,
                    opposite: false
                },
                legend: {
                    align: 'left',
                    verticalAlign: 'top',
                    enabled: true,
                    itemDistance: 5
                },
                series: [{
                    marker: {
                        symbol: 'circle'
                    },
                    name: a,
                    data: adata
                }, {
                    marker: {
                        symbol: 'circle'
                    },
                    name: b,
                    data: bdata,
                    showInLegend: show
                }, {
                    marker: {
                        symbol: 'circle'
                    },
                    name: c,
                    data: cdata
                }, {
                    type: 'scatter',
                    name: '暂降触发点',
                    marker: {
                        symbol: 'url(/pqs9200/images/point.png)',
                        width: 16,
                        height: 16
                    },
                    data: cu
                }
                ],
            });
            //绘制RMS波形图
            Highcharts.stockChart(rmsId, {
                plotOptions: {
                    series: {
                        animation: false
                    }
                },
                title: {
                    text: title,
                    floating: true,
                    style: {fontSize: "14px"},
                    y: -12
                },
                chart: {
                    type: 'spline',
                    events: {
                        load: function () {
                            if (show) {
                                this.series[1].show();
                            } else {
                                this.series[1].hide();
                            }
                        }
                    },
                    spacingTop: 30
                },
                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 () {
                            s += '<br/>' + this.series.name + ': ' +
                                this.y.toFixed(2) + 'kV';
                        });
                        return s;
                    },
                    shared: true
                },
                rangeSelector: {
                    enabled: false,
                },
                exporting: {
                    enabled: false
                },
                //导航器各项属性设置
                navigator: {
                    margin: 1,
                    height: 15,
                    xAxis: {
                        labels: {
                            formatter: function () {
                                return this.value;
                            }
                        }
                    },
                    series: [{
                        data: radata
                    }, {
                        data: rbdata
                    }, {
                        data: rcdata
                    }]

                },
                scrollbar: {
                    enabled: false
                },
                credits: false,
                colors: colors,
                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
                    },
                    showLastLabel: true,
                    opposite: false
                },
                legend: {
                    align: 'left',
                    verticalAlign: 'top',
                    enabled: true,
                    itemDistance: 5
                },
                series: [{
                    marker: {
                        symbol: 'circle'
                    },
                    name: a,
                    data: radata,
                    id: 'a'
                }, {
                    marker: {
                        symbol: 'circle'
                    },
                    name: b,
                    data: rbdata,
                    showInLegend: show,
                    id: 'b'
                }, {
                    marker: {
                        symbol: 'circle'
                    },
                    name: c,
                    data: rcdata,
                    id: 'c'
                }, {
                    type: 'scatter',
                    name: '暂降触发点',
                    marker: {
                        symbol: 'url(/pqs9200/images/point.png)',
                        width: 16,
                        height: 16
                    },
                    data: rmscu
                }, {
                    type: 'flags',
                    color: '#34c0e2',
                    name: '最小暂降幅值',
                    cursor: 'pointer',
                    visible: isvisible,
                    showInLegend: isvisible,
                    data: [{
                        x: rmsvX,
                        title: rmsvY
                    }],
                    onSeries: zhou,
                    shape: 'flag'
                }
                ]
            });
        }
    }
}


//波形总体数据构造函数
function waveData(instantF, RMSF, RMSFMinDetail, shunshiF, RMSFWave, title, waveMateInfo) {
    /*瞬时一次值最大最小值*/
    this.instantF = instantF;

    /*RMS一次值最大最小值*/
    this.RMSF = RMSF;

    /*RMS一次值最小值具体的X Y周的位置，已经具体的相别*/
    this.RMSFMinDetail = RMSFMinDetail;

    /*瞬时值一次值3相详细数据*/
    this.shunshiF = shunshiF;

    /*RMS一次值3相详细数据*/
    this.RMSFWave = RMSFWave;

    /*三相名称*/
    this.title = title;

    /*波形的元数据信息*/
    this.waveMateInfo = waveMateInfo;
}


//根据多个值的比较返回其中最大值
function getMax(temp, tempA, tempB, tempC) {
    temp = temp > tempA ? temp : tempA;
    temp = temp > tempB ? temp : tempB;
    temp = temp > tempC ? temp : tempC;
    return temp;
}

//根据多个值的比较返回其中最大值
function getMaxTwo(temp, tempA, tempB) {
    temp = temp > tempA ? temp : tempA;
    temp = temp > tempB ? temp : tempB;
    return temp;
}

//根据多个值的比较返回其中最小值
function getMin(temp, tempA, tempB, tempC) {
    temp = temp < tempA ? temp : tempA;
    temp = temp < tempB ? temp : tempB;
    temp = temp < tempC ? temp : tempC;
    return temp;
}

function getMinOpen(temp, tempA, tempB) {
    temp = temp < tempA ? temp : tempA;
    temp = temp < tempB ? temp : tempB;
    return temp;
}