<?php

declare(strict_types=1);

namespace App\Job;

use Hyperf\AsyncQueue\Job;
use App\Service\ALiSmsService;
use Hyperf\Utils\ApplicationContext;

class ExampleJob extends Job
{
    /**
     * 任务执行失败后的重试次数，即最大执行次数为 $maxAttempts+1 次
     *
     * @var int
     */
    protected $maxAttempts = 2;

    public $params;

    private $redisClient;

    public function __construct($params)
    {
        // 这里最好是普通数据，不要使用携带 IO 的对象，比如 PDO 对象
        $this->params = $params;
    }

    public function handle()
    {
        /*
         *  @$data  队列消费数据
         *  @$sms 实例化发短信类
         *  @$template_param 配置参数
//       *  @$caturt @$container 实例化redis
         * */
        $data = $this->params;
        $sms = new ALiSmsService();
        $caturt = new ApplicationContext();
        $container = $caturt->getContainer();
        $this->redisClient = $container->get(\Redis::class);
//        判断redis是否有当前已发送信息
        if (!$this->redisClient->get($data['typedevicenum'])) {
            $template_param = ['cphone' => $data['phone'], 'position' => '您的设备尾号为' . $data['devicenum'], 'alarm' => '离线'];
            $params = array(
                'SignName' => '泽宏云',
                'AccessKeyId' => 'LTAI2xiZNF3iV2aV',
                'TemplateCode' => 'SMS_169897307',
                'PhoneNumbers' => $data['phone'],
                'TemplateParam' => json_encode($template_param, JSON_UNESCAPED_UNICODE),
                'RegionId' => 'cn-beijing',
            );
            $accessKeySecret = 'bprEWwn1M0xgglRQCQEMYSPiYctDk4';
            $response = $sms->sendSms($accessKeySecret, $params);
            if ($response['Message'] == 'OK' && $response['Code'] == 'OK') {
                $redisdata = ['data'=>$data,'sendSms'=>$response,'time'=>time()];
                $this->redisClient->set($data['typedevicenum'], json_encode($redisdata));
            }
        }

    }

}