/**
 * Created by zhang on 2019/4/12.
 */
module.exports = {
    saveOnlineTime:saveOnlineTime
};

let mongoose = require("mongoose");
import moment from "moment";
let logs_model = mongoose.model("online_logs");

async function saveOnlineTime(req) {
    let online_times = 0;
    let end = + new Date();
    try {
        let interval_time = 10 * 60 *1000;
        let start = req.session.online_start_time;
        if(start === undefined) return req.session.online_start_time ==end;
        online_times =  end - start;
        //1秒内只记一次就好
        if(online_times < 500) return;//如果间隔太短，则忽略
        if(online_times > interval_time ){//如果间隔超过有效时长，则不累加这次时长，从头开始算
            req.session.online_start_time = end;
            return
        }
        if(!req.session.sessionUser||!req.session.sessionCompilation) return;
        let dataString = moment(end).format('YYYY-MM-DD');
        let condition = {userID:req.session.sessionUser.id,compilationID:req.session.sessionCompilation._id,dateString:dataString};
        let record = await logs_model.findOne(condition);
        if(record){ //如果找到，则累加
            await logs_model.update(condition,{$inc:{'online_times' : online_times }});
        }else {//如果没找到，则新增一条记录
            condition["online_times"] = online_times;
            let today = moment(dataString).toDate();
            condition["dateTime"] = +today;
            await logs_model.create(condition);
        }
    }catch (e){
        console.log("统计登录时间错误，online_times值："+online_times);
        console.log(e)
    }
    req.session.online_start_time = end;
}