var rowNum = 0;
var totalTime = 0;  // 心跳记录的总时长 秒
var rsCount = 0;
var rs = "";
var intv = "";
var intvTime = 1000;     //数据处理间隔时间 毫秒
var preHrTime = 0;    //上次心率数据处理时间 毫秒
var rowData = {         //原始记录的当前行数据 每隔3-4秒一条数据
    hr_timestamp: 0,
    hr_value: 0,
};
var adjustRowData = {         //校正后的当前行数据 每隔 intvTime 一条数据
    hr_timestamp: 0,
    hr_value: 0,
};

var hrAverage = 0;
var hrAverageArr = [];
var charData = [];
var xAxisData = [];

var dom_rowNum = "";
var dom_totalTime = "";
var dom_hrValue = "";
var dom_endFlag = "";          //endFlag 0:未开始 1:已开始 2:已结束 
var dom_spIntensity = "";
var dom_spIntensityLevelString= "";
var dom_areaHr = "";

function csvInit() {
    resetData();
    dom_rowNum = $("#rowNum");
    dom_totalTime = $("#totalTime");
    dom_hrValue = $("#hrValue");
    dom_endFlag = $("#endFlag");
    dom_spIntensity = $("#spIntensity");
    dom_spIntensityLevelString = $("#spIntensityLevelString");
    dom_areaHr = $("#areaHr");
}

function resetData() {
    $("#hrValue").text("--");
    $("#rowNum").val(0);
    $("#totalTime").val(0);
    $("#rsCount").val(0);
    $("#endFlag").val(0);
    preHrTime = 0;
    charData.length = 0;
    xAxisData.length = 0;
}

function loadCsvFile(csvfile) {
    $.ajax({
        url: csvfile,
        dataType: 'text',
    }).done(successFunction);
}

function successFunction(data) {
    data = data.trim();
    rs = data.split(/\r?\n|\r/);
    rsCount = rs.length;
    $("#rsCount").val(rsCount);
    console.log("rsCount " + rsCount);

    getDataTotalTime();     //秒
    dom_totalTime.val(totalTime);

    getXAxisData();
    dealData();
}

function getDataTotalTime() {
    let firstCell = rs[0].split(',');
    let lastCell = rs[rsCount-1].split(',');
    totalTime = lastCell[0] - firstCell[0];
    // console.log("firstCell: " + firstCell);
    // console.log("lastCell: " + lastCell);
    console.log("[getDataTotalTime] totalTime: " + totalTime);
}

//计算平均心率
function getHrAverage(hr) {
    if (hrAverageArr.length >= 5) {
        hrAverageArr.shift();       //删除数组的第一个元素
    }
    hrAverageArr.push(hr);
    hrAverage = Math.round(sumArr(hrAverageArr) / hrAverageArr.length);
    // console.log("hrAverage: " + hrAverage);
    return hrAverage;
}

//获取图表的X轴数据集
function getXAxisData() {
    let count = Math.ceil(totalTime * 1000 / intvTime);    //向上取整

    xAxisData = getArrRange(0, count);
    console.log("[getXAxisData] xAxisData count: " + count);
    // console.log("xAxisData: " + xAxisData);
}

function getRowCell() {
    let rowCells = rs[rowNum].split(',');
    rowData.hr_timestamp = rowCells[0];
    rowData.hr_value = rowCells[2];
}

function dealData() {
    (async function() {
        console.log("[dealData] start " + new Date());
        dom_endFlag.val(1);

        let i = 0;
        while (rowNum < rsCount) {
            // console.log('[dealData]['+ i +'] rowNum: '+ rowNum +' ' + new Date());

            if (preHrTime > 0) {
                if (preHrTime >= rowData.hr_timestamp) {
                    rowNum++;
                    if (rowNum < rsCount) {
                        getRowCell();
                    }

                    adjustRowData.hr_timestamp = preHrTime;     //使用校正后的时间戳
                    adjustRowData.hr_value = rowData.hr_value;
                }
                else {  // 小于最新记录的时间戳，仍然显示上次的心率
                    adjustRowData.hr_timestamp = preHrTime;     //仅更新时间戳
                    // adjustRowData.hr_value = rowData.hr_value;
                }
            }
            else {  //首次加载数据
                getRowCell();
                preHrTime = parseFloat(rowData.hr_timestamp);

                adjustRowData.hr_timestamp = rowData.hr_timestamp;
                adjustRowData.hr_value = rowData.hr_value;
            }
            // console.log("preHrTime: "+preHrTime + " adjustRowData.hr_timestamp: " + adjustRowData.hr_timestamp + " rowData.hr_timestamp: " + rowData.hr_timestamp);

            // 使用校正后的数据
            let hr = adjustRowData.hr_value;
            sportInfo = getSportInfo(intvTime, hr);   //cle.js
            
            getHrAverage(hr);
            charData.push(hrAverage);   //加载平均心率
            // charData.push(hr);   //加载心率
            // charData.push(Math.round(sportInfo.ei));    //加载EI

            dispData();
            
            await sleep(intvTime);
            preHrTime = parseFloat(preHrTime) + (intvTime / 1000);

            // console.log("[dealData]["+ i +"] adjustRowData.hr_value: " + adjustRowData.hr_value + " rowData.hr_value: " + rowData.hr_value + " " + new Date());
            i++;
        }

        dom_endFlag.val(2);
        dom_hrValue.text("--");
        console.log("[dealData] finished " + new Date());
    })();
}

function dispData() {
    dom_rowNum.val(rowNum);
    dom_hrValue.text(adjustRowData.hr_value);
    dom_spIntensity.text(sportInfo.intensity);
    dom_spIntensityLevelString.text(sportInfo.intensityLevelString);
    dom_areaHr.css("background-color", sportInfo.intensityLevelColor);

    dispStyle();
    dispChart();
}

function dispChart() {
    // console.log("charData: " + charData);

    var option = {
        xAxis: {
            data: xAxisData,
            show: false
        },
        yAxis: {
            // show: false
        },
        series: [{
            data: charData,
        }]
    };

    myChart.setOption(option); 
}

function dispStyle() {   
    var class_hrValue = '';
    if (sportInfo.intensity <= 30) {
        class_hrValue = 'slowJump';
    } else if (sportInfo.intensity > 30 && sportInfo.intensity <= 90) {
        class_hrValue = 'normalJump';
    } else if (sportInfo.intensity > 90) {
        class_hrValue = 'fastJump';
    }
    else {
        class_hrValue = '';
    }
    // console.log("class_hrValue: " + class_hrValue);

    dom_hrValue.removeClass();  //removeClass没有参数,则移除所有的Class
    dom_hrValue.addClass(class_hrValue);
}