const cron = require('cron');
const config = require('../config');
const nodemailer = require('nodemailer');
const moment  = require("moment");
const CronJob = cron.CronJob;
const _ = require('lodash');
const db = require('../db');
const fs = require('fs');
const path = '/Users/liusong/';
const job = new CronJob({
	cronTime: '45 23 18 * * 0-6',
	onTick: function () {
		taskGo();
	},
	start: false
});

let date = moment().add(-1,'days').format('YYYYMMDD');
const statsTask = require('./tasks/statisticsTask');

async function taskGo () {
  console.dir('begin go');
  let start = ( end = date );
  let timeQs = getTimeRange({ start, end, key:'updateTimestamp', type: 'millisecond' });
  let qs = _.clone(timeQs);
  /*
  let taskQuery = _.clone(timeQs);
  let callTaskQuery = getTimeRange({ start, end, key:'startTime', type: 'millisecond' });
  let recognitionsQuery = _.clone(timeQs);
  */
  await statsHandler(qs,date);
}

async function statsHandler(query,date) {
  const dailyStats = await db.getCollection('dailyStats');
  const arrs = await statsTask(query);
  const txt = 'stats_' + date + '.log';
  let pv = 0;
  let uid = 0;
  let pubObject = {};
  arrs.forEach( async x => {
    if(date === x._id.date) {
      let uniqUid = (x.value.uids = typeof(x.value.uids) == 'string' ? 1 : _.uniq(x.value.uids).length);
      if(pubObject[ x._id.pubID ]) {
        pubObject[ x._id.pubID ].pv += x.value.pv;
        pubObject[ x._id.pubID ].uid += uniqUid;
      } else {
        pubObject[ x._id.pubID ] = { pv : x.value.pv, uid: uniqUid };
      }
      let data = {
        date: x._id.date,
        slotID: x._id.slotID,
        pubID: x._id.pubID,
        pv: x.value.pv,
        uid: uniqUid
      };
      pv += data.pv;
      uid += data.uid;
      let rep = await dailyStats.insert(data);
      console.dir(rep);
      if(rep.result && rep.result.ok && rep.ops && rep.ops.length){
        log(txt, '插入一条记录: ' + rep.ops[0]._id );
      } else {
        log(txt, '插入失败: ' + rep );
      }
    } else {
      log(txt, '筛选错误: ' + date + 'diff' + x._id.date);
    }
  });
  Object.keys(pubObject).forEach( async (pubID) => {
    let slotID = 'all';
    let rep = await dailyStats.insert( _.merge(pubObject[pubID], { pubID, slotID ,date }) );
    if(rep.result && rep.result.ok && rep.ops && rep.ops.length){
      log(txt, '插入一条记录: slotID = all ' + rep.ops[0]._id );
    } else {
      log(txt, '插入失败: ' + rep );
    }
  });
  let rep = await dailyStats.insert({
    pv,
    uid,
    pubID: 'all',
    slotID: 'all',
    date
  });
  if(rep.result && rep.result.ok && rep.ops && rep.ops.length){
    log(txt, '插入一条记录: pubID= all ; slotID = all ' + rep.ops[0]._id );
  } else {
    log(txt, '插入失败: ' + rep );
  }
  console.log('完成');
}

function log(txt, info){
  fs.appendFile(path + txt, info + '\n',function(){
      console.log(date + ':' + info);
  });
}

function getTimeRange({ start, end, type, key}) {
  if(/^[0-9]{8}$/.test(start) && /^[0-9]{8}$/.test(end) ) {
     if(type === 'millisecond') {
     return { [ key ]: { '$gt': parseInt(moment(start,'YYYYMMDD').startOf('day').format('x')), '$lte': parseInt(moment(end,'YYYYMMDD').endOf('day').format('x')) } };
    } else {
     return { [ key ]: { '$gt': moment(start,'YYYYMMDD').startOf('day').toDate(), '$lte': moment(end,'YYYYMMDD').endOf('day').toDate() } };
    }
  } else {
    if(type === 'millisecond') {
     return { [ key ]: { '$gt': parseInt(moment().add(-7,'days').startOf('day').format('x')), '$lte': parseInt(moment().endOf('day').format('x')) } };
    } else {
     return { [ key ]: { '$gt': moment().add(-7,'days').startOf('day').toDate(), '$lte': moment().endOf('day').toDate() } };
    }
  }
}

module.exports.start = function () { 
	job.start();
};