/**
 * titleName:图表的名称 定义二维数组放波形数据 一次值：
 * totalwaveFA、totalwaveFB、totalwaveFC 二次值：
 * totalwaveSA、totalwaveSB、totalwaveSC 一次值RMS：
 * totalRMSFA、totalRMSFB、totalRMSFC 二次值:
 * totalRMSSA、totalRMSSB、totalRMSSC定义数组存放配置 echartBXFXOption:
 * echartRMSOption:RMS配置 echartBXFXObj: echartRMSObj:echarts图表对象 time:事件发生时间
 * arrGuid:存放选中的guid
 */
var arrGuid = [];
var titleName = [];
var titleTime = [];
var titleIndex = [];
var titlePt = [];
var totalwaveFA = [];
var totalwaveFB = [];
var totalwaveFC = [];
var totalwaveSA = [];
var totalwaveSB = [];
var totalwaveSC = [];
var totalRMSFA = [];
var totalRMSFB = [];
var totalRMSFC = [];
var totalRMSSA = [];
var totalRMSSB = [];
var totalRMSSC = [];
var echartBXFXOption = [];
var echartRMSOption = [];
var tabIndex = 0;
var offset = 0;

var layer = null;
layui.use(['layer'], function () {
    layer = layui.layer
});

function addItems(id, name) {
    var divDom = document.getElementById("picList");
    addEles(divDom, id, name);
}

function addEles(obj, id, name) {
    var checkBoxDom = document.createElement("input");
    checkBoxDom.setAttribute("type", "checkbox");
    checkBoxDom.setAttribute("id", 'checkBox_' + id);
    var strongDom = document.createElement('strong');
    strongDom.innerHTML = '<p style="display:inline; margin-left:5px;margin-top:-3px;">'
        + name + '</p>';
    obj.appendChild(checkBoxDom);
    obj.appendChild(strongDom);

    $('#checkBox_' + id).prop("checked", true);

    $('#checkBox_' + id).change(function () {
        if ($('#checkBox_' + id).is(':checked')) {
            $('#rms_' + id).show();
            $('#bxfx_' + id).show();
            picTotals++;
        } else {
            if (picTotals == 2) {
                $('#checkBox_' + id).prop("checked", true);
                layer.msg('请至少保留一组对比图表!');
                return;
            }

            $('#rms_' + id).hide();
            $('#bxfx_' + id).hide();
            picTotals--;
        }
    });
}

$(function () {
    // 新增checkbox数据
    $('.float-close').click(function () {
        $('.float-news').animate({
            right: '-450px'
        }, 300, function () {
            $('.float-open').delay(50).animate({
                right: '-2px'
            }, 300);
        });
    });

    $('.open-btn').click(function () {
        $('.float-open').animate({
            right: '-70px'
        }, 100, function () {
            $('.float-news').delay(50).animate({
                right: '0px'
            }, 300);
        });
    });

    function drawOnCanvas(arrayPic, name) {
        var canvas = document.getElementById("canvasipal");
        var Gc = canvas.getContext("2d");
        var j = 0;

        for (var i = 0; i < arrayPic.length; i++) {
            var drawImg = new Image();
            drawImg.src = arrayPic[i];
            drawImg.onload = function () {
                Gc.drawImage(this, 0, j * 450, 2000, 450);
                j++;

                if (j == arrayPic.length) {
                    canvasToImageIpal(name, 'png');
                }
            };
        }

    }

    $('#screenPic').on('click', function () {
        var arrayPic = [];
        var picName = '瞬时波形';
        var canvas = document.getElementById("canvasipal");
        canvas.height = 450 * offset;

        if (tabIndex == 0) {
            picName = '瞬时波形';

            for (var i = 0; i < offset; i++) {
                var charData = $('#bxfx_' + i.toString()).highcharts().getSVG();
                var href = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(charData)));
                arrayPic.push(href);
            }


        } else if (tabIndex == 1) {
            picName = 'RMS波形';

            for (var i = 0; i < offset; i++) {
                var charData = $('#rms_' + i.toString()).highcharts().getSVG();
                var href = 'data:image/svg+xml;base64,' + window.btoa(unescape(encodeURIComponent(charData)));
                arrayPic.push(href);
            }
        }

        drawOnCanvas(arrayPic, picName);
    });

    /**
     * 选择一次值、二次值的时候，变更图形
     */
    $("#interval").change(function () {
        var v = $(this).val();
        echartBXFXOption = [];
        echartRMSOption = [];

        if (v == "one") {
            Draw(1);
        } else {
            Draw(2);
        }
    });

    $('#myTab').find('li').click(function () {
        tabIndex = $(this).index();
    });
});

/**
 * 根据GUID读取波形文件
 *
 * @param arrayGuid
 * @param time
 * @returns
 */
var tabId = -1;
var picId = -1;
var addtabId = -1;
var addpicId = -1;
var guid = '';
var layerId = -1;

function getaddData(arrayGuid, id1, id2, id3, id4) {
    layerId = SHOW_LOAD_LAYER(layer);

    $.ajax({
        type: 'POST',
        dataType: "json",
        data: {
            arrayGuid: JSON.stringify(arrayGuid)
        },
        url: '/pqs9200/advanced/drawPicByGuid',
        success: function (data) {
            arrGuid = arrayGuid.slice(0);
            guid = arrayGuid[0].indexEventAss;
            addtabId = id3;
            addpicId = id4;
            tabId = id1;
            picId = id2;

            processData(data);
        },
        error: function () {
            CLOSE_LOAD_LAYER(layer, layerId);
            layer.msg("查询失败！");
        }
    });
}

var templateBxfxId = [];
var templateRmsId = [];
var picTotals = 0;
//瞬时一次值最大最小值
var arrinstantF = [];
var arrinstantS = [];
var arrRMSF = [];
var arrRMSS = [];

function processData(data) {
    if (data.code != 0) {
        CLOSE_LOAD_LAYER(layer, layerId);
        layer.msg("查询失败！");
        return;
    }

    /**
     * 删除已经处理过的template元素
     */
    for (var l = 0; l < templateBxfxId.length; l++) {
        $('#' + templateBxfxId[l]).remove();
        $('#' + templateRmsId[l]).remove();
    }

    templateBxfxId = [];
    templateRmsId = [];

    while (offset < data.object.length) {
        var templateBxfx = document.querySelector('#bxfx_template');
        var templateRms = document.querySelector('#rms_template');

        templateBxfx.content.querySelector('.bxfx').id = 'bxfx_'
            + offset.toString();
        templateBxfxId.push('bxfx_' + offset.toString());
        templateRms.content.querySelector('.rms').id = 'rms_'
            + offset.toString();
        templateRmsId.push('rms_' + offset.toString());

        $('#sjbx').append(templateBxfx.content.cloneNode(true));
        $('#rms').append(templateRms.content.cloneNode(true));

        // 一次值事件波形
        var waveFA = new Array();
        var waveFB = new Array();
        var waveFC = new Array();
        // 二次值事件波形
        var waveSA = new Array();
        var waveSB = new Array();
        var waveSC = new Array();
        // 一次值RMS波形
        var RMSFA = new Array();
        var RMSFB = new Array();
        var RMSFC = new Array();
        // 二次值RMS波形
        var RMSSA = new Array();
        var RMSSB = new Array();
        var RMSSC = new Array();

        var instantF = new Object();
        var instantS = new Object();
        var RMSF = new Object();
        var RMSS = new Object();

        //波形的总体数据
        var shunData, rmsData;
        var pt;

        /**
         * 拼接暂降类型
         */
        for (var le = 0; le < arrGuid.length; le++) {
            if (arrGuid[le].indexEventDetail === data.object[offset].picIndex) {
                var strName = '监测点：' + arrGuid[le].namePoint + ' 发生时刻：'
                    + arrGuid[le].strTime + ' 暂降类型：' + arrGuid[le].sagType;
                titleName.push(strName);
                titleTime.push(arrGuid[le].strTime);
                titleIndex.push(data.object[offset].picIndex);
                titlePt.push(data.object[offset].stringPt);
                addItems(offset, arrGuid[le].strTime);
                break;
            }
        }

        //处理事件波形
        var wp = data.object[offset].waveData;

        if (null != wp) {
            shunData = wp.sunData;
            rmsData = wp.rmsData;
            pt = Number(wp.pt) / 1000;

            var ifmax, ifmin, ismax, ismin, rfmax, rfmin, rsmax, rsmin;
            //给瞬时付个初始值
            if (shunData.length > 0) {
                ifmax = shunData[0][1] * pt;
                ifmin = shunData[0][1] * pt;
                ismax = shunData[0][1];
                ismin = shunData[0][1];
            }
            //给RMS付个初始值
            if (rmsData.length > 0) {
                rfmax = rmsData[0][1] * pt;
                rfmin = rmsData[0][1] * pt;
                rsmax = rmsData[0][1];
                rsmin = rmsData[0][1];
            }
            //瞬时值--同时还需要获取出瞬时值的一次、二次的最大最小值
            for (var shun = 0; shun < shunData.length; shun++) {
                var shunFirstA = shunData[shun][1] * pt;
                var shunFirstB = shunData[shun][2] * pt;
                var shunFirstC = shunData[shun][3] * pt;
                waveFA.push([shunData[shun][0], shunFirstA]);
                waveFB.push([shunData[shun][0], shunFirstB]);
                waveFC.push([shunData[shun][0], shunFirstC]);
                ifmax = getMax(ifmax, shunFirstA, shunFirstB, shunFirstC);
                ifmin = getMin(ifmin, shunFirstA, shunFirstB, shunFirstC);

                var shunSecondA = shunData[shun][1];
                var shunSecondB = shunData[shun][2];
                var shunSecondC = shunData[shun][3];
                waveSA.push([shunData[shun][0], shunSecondA]);
                waveSB.push([shunData[shun][0], shunSecondB]);
                waveSC.push([shunData[shun][0], shunSecondC]);
                ismax = getMax(ismax, shunSecondA, shunSecondB, shunSecondC);
                ismin = getMin(ismin, shunSecondA, shunSecondB, shunSecondC);
            }

            //RMS值--同时还需要获取出RMS值的一次、二次的最大最小值
            for (var rms = 0; rms < rmsData.length; rms++) {
                var rmsFirstA = rmsData[rms][1] * pt;
                var rmsFirstB = rmsData[rms][2] * pt;
                var rmsFirstC = rmsData[rms][3] * pt;
                RMSFA.push([rmsData[rms][0], rmsFirstA]);
                RMSFB.push([rmsData[rms][0], rmsFirstB]);
                RMSFC.push([rmsData[rms][0], rmsFirstC]);
                rfmax = getMax(rfmax, rmsFirstA, rmsFirstB, rmsFirstC);
                rfmin = getMin(rfmin, rmsFirstA, rmsFirstB, rmsFirstC);

                var rmsSecondA = rmsData[rms][1];
                var rmsSecondB = rmsData[rms][2];
                var rmsSecondC = rmsData[rms][3];
                RMSSA.push([rmsData[rms][0], rmsSecondA]);
                RMSSB.push([rmsData[rms][0], rmsSecondB]);
                RMSSC.push([rmsData[rms][0], rmsSecondC]);
                rsmax = getMax(rsmax, rmsSecondA, rmsSecondB, rmsSecondC);
                rsmin = getMin(rsmin, rmsSecondA, rmsSecondB, rmsSecondC);
            }
            //赋值对应的最大最小值
            instantF.max = ifmax;
            instantF.min = ifmin;
            instantS.max = ismax;
            instantS.min = ismin;
            RMSF.max = rfmax;
            RMSF.min = rfmin;
            RMSS.max = rsmax;
            RMSS.min = rsmin;

            instantF.picIndex = data.object[offset].picIndex;
            instantS.picIndex = data.object[offset].picIndex;
            RMSF.picIndex = data.object[offset].picIndex;
            RMSS.picIndex = data.object[offset].picIndex;


            arrinstantF.push(instantF);
            arrinstantS.push(instantS);
            arrRMSF.push(RMSF);
            arrRMSS.push(RMSS);

            waveFA = waveFA.slice(0);
            waveFB = waveFB.slice(0);
            waveFC = waveFC.slice(0);
            RMSFA = RMSFA.slice(0);
            RMSFB = RMSFB.slice(0);
            RMSFC = RMSFC.slice(0);

            waveSA = waveSA.slice(0);
            waveSB = waveSB.slice(0);
            waveSC = waveSC.slice(0);
            RMSSA = RMSSA.slice(0);
            RMSSB = RMSSB.slice(0);
            RMSSC = RMSSC.slice(0);
        }

        /**
         * 添加数据到二维数组
         */
        totalwaveFA.push(waveFA);
        totalwaveFB.push(waveFB);
        totalwaveFC.push(waveFC);
        totalwaveSA.push(waveSA);
        totalwaveSB.push(waveSB);
        totalwaveSC.push(waveSC);
        totalRMSFA.push(RMSFA);
        totalRMSFB.push(RMSFB);
        totalRMSFC.push(RMSFC);
        totalRMSSA.push(RMSSA);
        totalRMSSB.push(RMSSB);
        totalRMSSC.push(RMSSC);

        offset++;
    }

    picTotals = offset;
    Draw(1);
    CLOSE_LOAD_LAYER(layer, layerId);
}


//根据多个值的比较返回其中最大值
function getMax(temp, tempA, tempB, tempC) {
    temp = temp > tempA ? temp : tempA;
    temp = temp > tempB ? temp : tempB;
    temp = temp > tempC ? temp : tempC;
    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;
}

/**
 * 绘图
 *
 * @param type
 * @returns
 */
function Draw(type) {
    if (type == 1) {
        for (var j = 0; j < titleName.length; j++) {
            for (var i = 0; i < arrinstantF.length; i++) {
                if (0 === totalwaveFA[j].length || arrinstantF[i] === undefined) {
                    initWave('bxfx_' + j, [], [],
                        [], titleName[j], 'kV', titleTime[j], titleIndex[j], titlePt[j], 0, 0);
                    initRms('rms_' + j, [], [], [],
                        titleName[j], 'kV', 0, 0);
                    break;
                } else if (titleIndex[j] === arrinstantF[i].picIndex) {
                    initWave('bxfx_' + j, totalwaveFA[j], totalwaveFB[j],
                        totalwaveFC[j], titleName[j], 'kV', titleTime[j], titleIndex[j], titlePt[j], arrinstantF[i], arrinstantS[i]);
                    initRms('rms_' + j, totalRMSFA[j], totalRMSFB[j], totalRMSFC[j],
                        titleName[j], 'kV', arrRMSF[i], arrRMSS[i]);
                    break;
                }
            }
        }
    } else if (type == 2) {
        for (var j = 0; j < titleName.length; j++) {
            for (var i = 0; i < arrinstantF.length; i++) {
                if (0 === totalwaveSA[j].length || arrinstantF[i] === undefined) {
                    initWave('bxfx_' + j, [], [],
                        [], titleName[j], 'V', titleTime[j], titleIndex[j], titlePt[j], 0, 0);
                    initRms('rms_' + j, [], [], [],
                        titleName[j], 'V', 0, 0);
                    break;
                } else if (titleIndex[j] === arrinstantF[i].picIndex) {
                    initWave('bxfx_' + j, totalwaveSA[j], totalwaveSB[j],
                        totalwaveSC[j], titleName[j], 'V', titleTime[j], titleIndex[j], titlePt[j], arrinstantF[i], arrinstantS[i]);
                    initRms('rms_' + j, totalRMSSA[j], totalRMSSB[j], totalRMSSC[j],
                        titleName[j], 'V', arrRMSF[i], arrRMSS[i]);
                    break;
                }
            }
        }
    }
}

/**
 * echarts 波形图配置
 *
 * @param xdata
 * @param adata
 * @param bdata
 * @param cdata
 * @param title
 * @param unit
 *            区分单位
 * @returns
 */
function initWave(divId, adata, bdata, cdata, title, unit, time, picIndex, pt, instantF, instantS) {
    var scatter = [];
    var max;

    if (adata.length > 0 && unit == 'kV') {
        scatter = [['0', instantF.min]];
        max = instantF.max;
    } else if (adata.length > 0 && unit == 'V') {
        scatter = [['0', instantS.min]];
        max = instantS.max;
    }

    Highcharts.stockChart(divId, {
        tooltip: {
            crosshairs: true,
        },
        title: {
            text: title,
            floating: false,
            margin: 3,
            style: {fontSize: "14px"}
        },
        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>时刻：' + this.x + 'ms</b>';
                $.each(this.points, function () {
                    s += '<br/>' + this.series.name + ': ' +
                        this.y.toFixed(2) + unit;
                });
                return s;
            },
            shared: true
        },
        rangeSelector: {
            enabled: false,
        },
        //导航器各项属性设置
        navigator: {
            margin: 1,
            xAxis: {
                labels: {
                    formatter: function () {
                        return this.value;
                    }
                }
            },
            series: [{
                data: adata
            }, {
                data: bdata
            }, {
                data: cdata
            }],
        },
        scrollbar: {
            enabled: false
        },
        credits: false,
        colors: [yellow, green, red],
        xAxis: {
            title: {
                text: 'ms',
                enabled: true,
                align: 'high'
            },
            labels: {
                formatter: function () {
                    return this.value;
                }
            }
        },
        yAxis: {
            title: {
                align: 'high',
                offset: 0,
                text: unit,
                rotation: 0,
                y: -10
            },
            max: max,
            min: max * -1,
            opposite: false
        },
        legend: {
            align: 'left',
            verticalAlign: 'top',
            enabled: true
        },
        series: [{
            marker: {
                symbol: 'circle'
            },
            name: 'A相',
            data: adata
        }, {
            marker: {
                symbol: 'circle'
            },
            name: 'B相',
            data: bdata
        }, {
            marker: {
                symbol: 'circle'
            },
            name: 'C相',
            data: cdata
        }, {
            type: 'scatter',
            name: '暂降触发点',
            marker: {
                symbol: 'url(/pqs9200/images/point.png)',
                width: 16,
                height: 16
            },
            data: scatter
        }
        ],
    });
}

/**
 * ehcarts RMS配置
 *
 * @param xdata
 * @param adata
 * @param bdata
 * @param cdata
 * @param title
 * @param unit
 *            增加单位区分
 * @returns
 */
function initRms(divId, adata, bdata, cdata, title, unit, RMSF, RMSS) {
    var scatter = [];

    if (adata.length > 0 && unit == 'kV') {
        scatter = [['0', RMSF.min]];
    } else if (adata.length > 0 && unit == 'V') {
        scatter = [['0', RMSS.min]];
    }

    Highcharts.stockChart(divId, {
        tooltip: {
            crosshairs: true,
        },
        title: {
            text: title,
            floating: false,
            margin: 3,
            style: {fontSize: "14px"}
        },
        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>时刻：' + this.x + 'ms</b>';
                $.each(this.points, function () {
                    s += '<br/>' + this.series.name + ': ' +
                        this.y.toFixed(2) + unit;
                });
                return s;
            },
            shared: true
        },
        rangeSelector: {
            enabled: false,
        },
        //导航器各项属性设置
        navigator: {
            margin: 1,
            xAxis: {
                labels: {
                    formatter: function () {
                        return this.value;
                    }
                }
            },
            series: [{
                data: adata
            }, {
                data: bdata
            }, {
                data: cdata
            }]

        },
        scrollbar: {
            enabled: false
        },
        credits: false,
        colors: [yellow, green, red],
        xAxis: {
            title: {
                text: 'ms',
                enabled: true,
                align: 'high'
            },
            labels: {
                formatter: function () {
                    return this.value;
                }
            }
        },
        yAxis: {
            title: {
                align: 'high',
                offset: 0,
                text: unit,
                rotation: 0,
                y: -10
            },
            opposite: false
        },
        legend: {
            align: 'left',
            verticalAlign: 'top',
            enabled: true
        },
        series: [{
            marker: {
                symbol: 'circle'
            },
            name: 'A相',
            data: adata
        }, {
            marker: {
                symbol: 'circle'
            },
            name: 'B相',
            data: bdata
        }, {
            marker: {
                symbol: 'circle'
            },
            name: 'C相',
            data: cdata
        }, {
            type: 'scatter',
            name: '暂降触发点',
            marker: {
                symbol: 'url(/pqs9200/images/point.png)',
                width: 16,
                height: 16
            },
            data: scatter
        }
        ],
    });
}

function saveResult() {
    /**
     * 更新数据库数据
     */
    var obj = new Object();
    var arr = [];
    obj.arrGuid = arrGuid;
    obj.strGuid = guid;
    arr.push(obj);

    $.ajax({
        type: 'POST',
        data: {
            condition: JSON.stringify(arr)
        },
        url: '/pqs9200/advanced/addNormalization',
        success: function (data) {
            parent.layer.close(tabId);
            parent.layer.close(picId);
            parent.layer.close(addtabId);
            parent.layer.close(addpicId);
        },
        error: function () {
            layer.msg("加入归一化处理失败！");
        }
    });
}

function getAnalysis(time, pt, picIndex, instantS) {
    var $alertMsg = layer.msg('高级分析<Br\>&nbsp&nbsp&nbsp正在处理....', {
        icon: 16,
        shade: 0.01,
        time: 0
    });

    parent.layer.open({
        type: 2,
        title: '高级分析',
        maxmin: false,
        shadeClose: true, // 点击遮罩关闭层
        area: ['100%', '100%'],
        content: 'analysis?maxy=' + instantS.max + '&miny=' + instantS.min + '&time=' + time + '&pt=' + pt,
        scrollbar: false,
        success: function (layero, index) {
            $(layero).find("iframe")[0].contentWindow.analysis(picIndex);
            if ($alertMsg != -1) {
                layer.close($alertMsg);
            }
        }
    });
}