const cron = require('cron');
const nodemailer = require('nodemailer');
const Schedule = require('../db/mongo/tao-schedule');
const Kouling = require('../db/mongo/tao-kouling');
const Log = require('../db/mongo/tao-log');
const tao = require('./tao');
const _ = require('lodash');
const moment = require('moment');
const controller = require('./controller');
const max = 10000;
var CronJob = cron.CronJob;
var job = new CronJob({
  cronTime: '0 */2 * * * *',
  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 {
        //let tkls = await Kouling.find({status:'use'}).populate('link','title target').limit(1000);
        // 查询进行中计划
	    let schedules = await Schedule.find({status:'use'}).limit(500);
      if(schedules.length == 0) console.log(' 更新结束  无任务');
      else
        schedules.forEach( async item => {
			       let schedule = item.toJSON()._id;
             var qd = item.toJSON().qd;
             var tasks_schedules = [];
             var tasks_schedule_koulings = [];

             if(item.final && item.final < moment().format('x')){
                tasks_schedules.push(Kouling.update({status:'use',schedule:schedule},{$set:{status:'disable'}},{multi:true}));
                tasks_schedule_koulings.push(Schedule.update({_id:schedule},{$set:{status:"disable"}},{multi:true}));
             }
            // console.dir(schedule);
            // 查询计划内 超过20000 请求 淘口令
            //console.dir({times:{$gte:10},status:'use',schedule:schedule});
            let logs = await Log.find({times:{$gte:max},schedule:schedule,status:{$ne:'disable'}}).populate('link','title target pic').limit(1000);
            var tasks_new = [];
            var tasks_old = [];
            var tasks_log = [];
            logs.forEach( item => {
                item = item.toJSON();
                //console.dir(item);
                if(item.link && item.link.title && item.link.target && item.times >= max){
                   var data = {
                     title:item.link.title,
                     target:item.link.target,
                     schedule:item.schedule,
                     link:item.link,
                     status:'use',
                     qd:qd,
                     pic:item.link.pic
                   }
                   tasks_new.push(controller.createTbkl(data));
                   tasks_old.push(Kouling.update({info:item.key,status:{$ne:'disable'}},{$set:{status:'disable'}},{multi:true}));
                   tasks_log.push(Log.update({_id:item._id},{$set:{status:'disable'}}));
                } 
            });
            if(tasks_schedule_koulings.length && tasks_schedules.length){
              var tasks_schedule_koulings_arr = await Promise.all(tasks_schedule_koulings);
              var tasks_schedules_arr = await Promise.all(tasks_schedules);
              console.log('更新计划 结束 影响' + tasks_schedules_arr.length + '条数据');
              console.log('更新计划相关口令 影响' + tasks_schedule_koulings_arr.length + '条数据');
            }
            if(tasks_new.length&&tasks_old.length&&tasks_log.length){
                var oldArrs = await Promise.all(tasks_old)
                var logArrs = await Promise.all(tasks_log);
                var newArrs = await Promise.all(tasks_new);
                console.log('删除老口令 结束 影响' + oldArrs.length + '条数据');
                console.log('更新log数据 影响' + logArrs.length + '条数据');
                console.log('增加新口令 结束 影响' + newArrs.length + '条数据');
                console.log(' 更新计划'+ item._id +'结束  有任务');
            }
            else{
                console.log(' 更新结束 '+  item._id +' 无任务');
            }
		});
		
	} catch (err) {
		console.dir(err);
		console.dir('更新异常 =====>');
		let mailList = 'liusong@goyoo.com';
		sendMail(mailList, err.toString());
	}
}

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