<?php

namespace Application\Service\Extension\Sms;

use Application\Common\RedisEnum;
use Application\Service\Extension\Laminas;

class SmsApplication
{
    protected $url;
    protected $userid;	//企业ID
    protected $account; //改为实际账户名
    protected $password; //改为实际短信发送密码
    protected $mobile;	//接受的手机号，多个手机号用英文‘,’分割

    public function __construct()
    {
        $config = Laminas::$app->getConfig()['sms'];
        $this->url = $config['url'];
        $this->userid = $config['userid'];
        $this->account = $config['account'];
        $this->password = $config['password'];
        $this->sign = $config['sign'];
    }

    /**
     * 生成验证码
     * @return false|string
     */
    public static function generateVerifyCode(int $length = 4): string
    {
        $const = array();
        $consts = 'bcdfghjkmnpqrstwxyz1234567890';
        for ($x = 0; $x < $length * 2; $x++)
        {
            $const[$x] = substr($consts, mt_rand(0, strlen($consts)-1), 1);
        }
        $randomString = implode('', $const);
        //only display 4 str
        return substr($randomString, 0, $length);
    }

    /**
     * 发送短信验证码
     * @param string $mobile 手机号码
     * @param string|null $verifyCode 验证码, 默认生成一个4位长度的随机字符串
     * @return array code => 验证码(4gs3), content => 短信发送内容(您登录的验证码为:4gs3,有效期为5分钟，请您注意保管。【医科恩】)
     * @throws \Exception
     */
    public function send(string $mobile, string $verifyCode = null)
    {
        $this->mobile = $mobile;
        if (!$verifyCode) {
            $verifyCode = self::generateVerifyCode();
        }

        //将生成的验证码发送给用户
        $mobileMes = "您登录的验证码为:{$verifyCode},有效期为5分钟，请您注意保管。【{$this->sign}】";
        $result = json_decode($this->https_post($mobileMes), true);

        if ($result['returnstatus'] == 'Success' && $result['successCounts'] == 1) {
            $back['code'] = $verifyCode;
            $back['content'] = $mobileMes;
            $back['error'] = 0;
            $back['message'] = "短信发送成功";
            return $back;
        }

        throw new \Exception("短信发送失败。");
    }

    //curl -> post提交信息
    protected function https_post($mobileMes)  {
        $body=array(
            'action'=>'send',
            'userid'=>$this->userid,
            'account'=>$this->account,
            'password'=>$this->password,
            'mobile'=>$this->mobile,
            'extno'=>'',
            'content'=>$mobileMes,
            'sendtime'=>''
        );

        $ch=curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->url);
        if($body){
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        }
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }
}