const cron = require('cron');
const nodemailer = require('nodemailer');
const Schedule = require('../db/mongo/tao-schedule');
const Data = require('../db/mongo/tao-data');
const Log = require('../db/mongo/tao-log');
const Click = require('../db/mongo/tao-log-click');
const _ = require('lodash');
const moment = require('moment');
const controller = require('./controller');
var CronJob = cron.CronJob;
var job = new CronJob({
  cronTime: '00 01 00 * * 0-6',
  onTick: function() {
    tbklTask();
  },
  start: false,
});

async function sendMail(email,body) {
    var smtpTransport = nodemailer.createTransport({
        auth: {
            user: "liusong@goyoo.com",
            pass: "323609zhang"
        },
        host: 'smtp.exmail.qq.com',
        port: 465
    });
    var mailOptions = {
        from: "liusong@goyoo.com",
        to: email, //发给谁
        subject: '淘口令后台定时任务错误', //主题
        text: body
    };
    smtpTransport.sendMail(mailOptions, function (err, response) {
        if (!err) {
            console.log('发送邮件成功');
        } else {
            console.log('发送邮件失败，请重试');
        }
    });
}
async function tbklTask () {
	console.log('定时更新开始 =====> ');
	try {
      var date = moment().add(-1,'days').format('YYYYMMDD');
      var logDate = moment().add(-1,'days').toDate();
      var list = await Log.aggregate([
        {
          $match:{
            "date": date
          }
        },
        {
          $group:{
            _id: "$schedule",
            sum:{ $sum:"$times" }
          }
        }
      ]);
      var clicks = await Click.aggregate([
        {
          $match:{
            "date": date
          }
        },
        {
          $group:{
            _id: "$qd",
            sum:{ $sum:"$times" }
          }
        }
      ]);
      var qd2clicks = {};
      clicks.forEach( async item => {
        //schedule = schedule.toJSON();
        //var schedule = _tasks.push(Schedule.findById(item._id));
        qd2clicks[item._id] = item.sum;
        console.dir(item);
      });
      
      var qd2schedule = {};
      var sum2schedule = {};
      var _tasks = []
      list.forEach( async item => {
        //schedule = schedule.toJSON();
        var schedule = _tasks.push(Schedule.findById(item._id));
        sum2schedule[item._id] = item.sum;
        console.dir(item)
      });
      Promise.all(_tasks).then(function(arr){
          arr.forEach(function(item){
              if(item){
                var schedule = item.toJSON();
                console.dir('schedule in in ')
                if(qd2schedule[schedule.qd] && qd2schedule[schedule.qd].length )
                  qd2schedule[schedule.qd] = qd2schedule[schedule.qd].concat({schedule:item._id,times:sum2schedule[schedule._id]}) 
                else
                  qd2schedule[schedule.qd] =  [{schedule:item._id,times:sum2schedule[schedule._id]}];
              }
              else{
                console.dir(item);
              }
          });
          console.dir(qd2schedule);
          var tasks = [];
          for(var k in qd2schedule){
            var qd = k;
            var total = 0;
            for(var j in qd2schedule[k]){
                  total += qd2schedule[k][j].times;
            }
            //var total = qd2schedule[k].reduce(function(a,b){ return a.times + b.times},{times:0});
            //console.dir({qd:qd,schedules:qd2schedule[k],date:logDate,times:total});
            var data = new Data({qd:qd,schedules:qd2schedule[k],date:logDate,times:total,click_times:qd2clicks[qd]});
            tasks.push(data.save());
          }
          Promise.all(tasks).then(function(arr){
              console.log('插入完成');
          });
      });
	} catch (err) {
		console.dir(err);
		console.dir('更新异常 =====>');
		let mailList = 'liusong@goyoo.com';
		sendMail(mailList, err.toString());
	}
}

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