<?php

namespace App\Crontab;

use EasySwoole\Crontab\JobInterface;
use App\Com\SmtpSend;
use EasySwoole\EasySwoole\Config;
use App\Models\WarningBody;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\DbManager;

class XcxWarningCrontab implements JobInterface
{
    public function jobName(): string
    {
        // 定时任务的名称
        return 'XcxWarningCrontab';
    }

    public function crontabRule(): string
    {
        // 定义执行规则 根据 Crontab 来定义
        // 这里是每分钟执行 1 次
        return '*/1 * * * *';
    }

    public function run()
    {
        //定时任务的执行逻辑
        $xcx_warn_set = Config::getInstance()->getConf('XCX_WARNING');
        //获取需要发送邮件的警告日志
        $this->processWarning();
        //发送邮件
        //$smtp = new SmtpSend();
        //$smtp->send($xcx_warn_set['accept_email'],'福利商城小程序关键节点告警信息','这是一份测试邮件，请勿回复');
    }

    //获取警告信息发送并处理发送结果
    protected function processWarning()
    {
        $where = ' xwb.`send_status` <> 2 and xwb.`create_time`>'.(time()-3600);    //1个小时内未发送和发送失败的消息
            $que_sql = "SELECT xwb.`id`,xwb.`member_id`,xwb.`mobile`,xwb.`create_time`,xwb.`type`,xwb.`ip`,xwb.`url`,xwb.`param`,xwt.`desc` as type_desc
            FROM ims_superdesk_shop_xcx_warning_body xwb 
            LEFT JOIN ims_superdesk_shop_xcx_warning_type AS xwt ON xwb.`type` = xwt.`id`
            WHERE {$where};
            ";
        $queryBuild = new QueryBuilder();
        $queryBuild->raw($que_sql);
        $res_data = DbManager::getInstance()->query($queryBuild, true, 'default')->toArray();
        $formatData = $this->formatMessage($res_data['result']);
        //发送邮件同时更新日志状态
        $this->send_mail($formatData);
    }

    /**
     * 获取需要发送的日志记录，每10条记录合成一份邮件内容
     * @param $warn_msg 未发送的警告记录
     * @return Array [content]邮件内容 [warn_id]数组，包含邮件里对应日志记录的ID
     *
     */
    protected function formatMessage($warn_msg){
        $msg_count = (int)(count($warn_msg)/10);
        if(count($warn_msg)%10>0){$msg_count++;}
        $formatData = Array();
        for($i=0;$i<$msg_count;$i++){
            $start_index = $i*10;
            $end_index = $i*10+9;
            $tmp_content = '';
            $tmp_warn_id = Array();
            for($j=$start_index;$j<=$end_index;$j++){
                if(!empty($warn_msg[$j])){
                    $tmp_content .= "<br>用户ID：{$warn_msg[$j]['member_id']}<br>
                    手机号：{$warn_msg[$j]['mobile']}<br>
                    时间：" . date("Y-m-d H:i:s",$warn_msg[$j]['create_time']) . "<br>
                    内容：{$warn_msg[$j]['type_desc']}<br>
                    IP：{$warn_msg[$j]['ip']}<br>
                    URL：{$warn_msg[$j]['url']}<br>
                    参数：{$warn_msg[$j]['param']}<br><br>";
                    $tmp_warn_id[] = $warn_msg[$j]['id'];
                }
            }
            $formatData[] = ['content'=>$tmp_content,'warn_id'=>$tmp_warn_id];
        }
        return $formatData;
    }


    //发送邮件更新日志状态
    protected function send_mail($formatData){
        //定时任务的执行逻辑
        $xcx_warn_set = Config::getInstance()->getConf('XCX_WARNING');
        $smtp = new SmtpSend();
        foreach($formatData as $value){
            $is_send = $smtp->send($xcx_warn_set['accept_email'],'福利商城小程序关键节点告警信息',$value['content']);
            //批量更新状态
            $status = $is_send?2:3;
            $res = WarningBody::create()->update([
                'send_status' => $status
            ], $value['warn_id']);
        }
    }


    public function onException(\Throwable $throwable)
    {
        // 捕获 run 方法内所抛出的异常
    }
}