<?php
declare (strict_types = 1);
namespace app\index\controller;
use think\Request;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use think\facade\Db;

class Sms
{
    /**
     *发送短信验证码
     * @return \think\Response
     */
    public function send_code()
    {
        $phone = input('phone');
        $code  = rand(1111,9999);

        $client = self::create_client("LTAIxA5ICmxNh3zp", "IE7rCvCxCZgSg1avuNgBMkL3HfIq0H");
        $sendSmsRequest = new SendSmsRequest([
            "phoneNumbers"  => $phone,
            "signName"      => "联发科技",
            "templateCode"  => "SMS_81080007",
            "templateParam" => json_encode(['code'=>$code])
        ]);
        $response = $client->sendSms($sendSmsRequest);

        if($response->body->message == 'OK'){
            Db::name('storage')->where('storage_type','smsCode')->where('storage_key',$phone)->delete();

            $data['storage_type']    = 'smsCode';
            $data['storage_key']     = $phone;
            $data['storage_value']   = $code;
            $data['storage_addtime'] = time();
            Db::name('storage')->insert($data);

            return success('发送成功');
        } else {
            return error('发送失败，失败原因：'.$response->body->message);
        }
    }

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Dysmsapi Client
     */
    public static function create_client($accessKeyId, $accessKeySecret){
        $config = new Config([
            "accessKeyId" => $accessKeyId,
            "accessKeySecret" => $accessKeySecret
        ]);
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }
}