<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/23/023
 * Time: 14:26
 */

namespace console\controllers;


use backend\helpers\MailHelper;
use backend\models\Config;
use backend\models\MailRecord;

class SendMailJobController extends BaseJobController
{
    public function actionRun()
    {
        date_default_timezone_set('Asia/Shanghai');
        $this->outLog("Job start " . date('Y-m-d H:i:s'));
        
        $cacheRun = $this->redis->get('SendMailJob');

        if (!$cacheRun) {
            
            $this->outLog("Auto send email,".date('Y-m-d H:i:s'));
            
            $config = Config::find()->asArray()->limit(1)->one();
            
            // 开始
            $this->redis->set('SendMailJob', true);
            $list = MailRecord::find()->where(['status' => 0])->limit(100)->asArray()->all();
            if (!empty($list)) {
                foreach ($list as $item) {
                    MailHelper::sendButNotSaveRecord($item['subject'], $item['receiver'], $config['smtp_from_mail'], $item['content']);
                    $this->outLog('Auto send email end,'.date('Y-m-d H:i:s'));
                    $model = MailRecord::findOne(['id' => $item['id']]);
                    $model->status = 1;
                    $model->save();
                }
            }
            
            $this->redis->set('SendMailJob', false);
            $this->outLog("Job end, " . date('Y-m-d H:i:s'));
        }
    }
}
