<?php

namespace app\queue\redis;

use Webman\RedisQueue\Consumer;

class Sms implements Consumer
{
    // 要消费的队列名
    public $queue = 'Sms';

    // 连接名，对应 plugin/webman/redis-queue/redis.php 里的连接`
    public $connection = 'default';

    // 消费
    public function consume($data)
    {
        \support\Log::channel('mail')->alert("开始发送短信:".json_encode($data));
        $body = '';
        if($data['body']){
            $body = $data['body'];
        }else{
            $body = $this->getTemplate($data);
        }
        $url = 'http://api.smsbao.com/sms?u=aisiaisi8899&p='.md5('Aaa123123').'&m='.$data['mobile'].'&c='.urlencode($body);
        $statusStr = array(
            "0" => "短信发送成功",
            "-1" => "参数不全",
            "-2" => "服务器空间不支持,请确认支持curl或者fsocket，联系您的空间商解决或者更换空间！",
            "30" => "密码错误",
            "40" => "账号不存在",
            "41" => "余额不足",
            "42" => "帐户已过期",
            "43" => "IP地址限制",
            "50" => "内容含有敏感词"
        );
        try {
            $res = get($url);
            log_alert($res.$statusStr[$res]);
            \support\Log::channel('mail')->alert($data['email']."短信已经发送");
        } catch (\Throwable $th) {
            \support\Log::channel('mail')->alert('发送短信出错:'.$th->getMessage());
            \support\Log::channel('mail')->alert(json_encode($data));
        }
                
        // 无需反序列化
        //var_export($data); // 输出 ['to' => 'tom@gmail.com', 'content' => 'hello']
    }
    function getTemplate($data){
        $str = '【问析科技】验证码:{$code},该验证码在30分钟内输入有效,若非您本人操作请尽快修改登录密码';
        foreach($data as $k=>$v){
            $str = str_replace('{$'.$k.'}',$v,$str);
        }
        return $str ;
    }
    // 消费失败回调
    /* 
    $package = [
        'id' => 1357277951, // 消息ID
        'time' => 1709170510, // 消息时间
        'delay' => 0, // 延迟时间
        'attempts' => 2, // 消费次数
        'queue' => 'send-mail', // 队列名
        'data' => ['to' => 'tom@gmail.com', 'content' => 'hello'], // 消息内容
        'max_attempts' => 5, // 最大重试次数
        'error' => '错误信息' // 错误信息
    ]
    */
    public function onConsumeFailure(\Throwable $e, $package)
    {
        echo "consume failure\n";
        echo $e->getMessage() . "\n";
        // 无需反序列化
        //var_export($package); 
    }
}