/**
 * Created by zhang on 2019/4/16.
 */

module.exports = {
    setOnlineTimes:setOnlineTimes,
    getOnlineInfo:getOnlineInfo,
    getTimeString:getTimeString,
};

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

async function getOnlineInfo(filter) {
    let datas = [];
    let logs = await logs_model.find(filter, null, { sort: {_id: -1}});
    let less = 0;
    for(let l of logs){
        let d = getTimeString(l.online_times);
        let online_times = d.s;
        less += d.less;
        if(online_times!=""){
            datas.push({dateString:l.dateString,dateTime:l.online_times,online_times:online_times})
        }
    }
    if(datas.length>1){//大于2个才把不够1分钟的累积到最后一条记录
        let last =  datas[datas.length - 1];
        last.online_times = getTimeString(last.dateTime + less).s;
    }

    return datas;
}


async function setOnlineTimes(userList,condition){
    for(let u of userList){
        let filter = {'userID':u._id.toString()};
        if(u.latest_used) filter["compilationID"] = u.latest_used;
        if(condition.latest_login && condition.latest_login == ""){
            let startTime = condition.latest_login['$gte']; //- 24*60*60*1000 //往前推一天  {'$gte': startTime, '$lt': endTime}latest_login
            filter['dateTime'] = {'$gte': startTime, '$lt':  condition.latest_login['$lt']}
        }

        let result =  await logs_model.aggregate([
            {$match: filter},
            {$group: {_id: "$userID", total: {$sum: "$online_times"}}}
        ]);
        u._doc.filter = JSON.stringify(filter);
        if(result.length > 0)  u._doc.online_times = getTimeString(result[0].total).s;
        u._doc.online_list = await this.getOnlineInfo(filter);
        u._doc.all_online_times = getTimeString(u.all_online_times).s;
    }
}


function getTimeString(times) {
    let s = "",perHour = 1000 * 60 * 60,perMin = 1000 * 60,perDay = 24*perHour;
    let day = parseInt(times/perDay);
    let hour = parseInt(parseInt(times % perDay) / perHour);
    let min = parseInt((times % perHour)/perMin);
    let less =  (times % perHour)%perMin;//不够一分钟的时间
    if(day > 0) s = s+`${day}天`;
    if(hour > 0) s = s+`${hour}小时`;
    if(min > 0)  s= s+`${min}分钟`;
    return {s:s,less:less}
}
