const cron = require('cron');
const UserAuth = require('../db/mongo/user-auto-auth');
const UserAuthLog = require('../db/mongo/user-auto-used-log');
const nodemailer = require('nodemailer');
const _ = require('lodash');
const moment = require('moment');

var CronJob = cron.CronJob;
var job = new CronJob({
  cronTime: '00 00 00 * * 0-6',
  onTick: function() {
    clearUserAuths();
  },
  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 clearUserAuths () {
	console.log('定时更新开始 =====> ');
	try {
		let userAuths = await UserAuth.find({}).limit(500);
		userAuths.forEach( async item => {
			let log = item.toJSON();
            if(moment(log['updatedAt']).format('YYYYMMDD') !== moment().format('YYYYMMDD')){
               let auth = new UserAuthLog(_.omit(log, ['_id', 'createdAt', 'updatedAt']));
               await auth.save();  
            }else{
                console.log('skip job');
            }
		});

		let data = {
			'$set':{
				used: 0
			}
		};
		await UserAuth.update({}, data, {multi:true});
	} catch (err) {
		console.dir(err);
		console.dir('更新异常 =====>');
		let mailList = 'liusong@goyoo.com';
		sendMail(mailList, err.toString());
	}
	console.log(' 更新结束 ');
}

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