<?php
declare (strict_types=1);
namespace library\utils\Sms;
// +----------------------------------------------------------------------
// | [ WE CAN DO IT MORE SIMPLE  ]
// +----------------------------------------------------------------------
// | Copyright (c) 2018-2020 rights reserved.
// +----------------------------------------------------------------------
// | Author: TABLE ME
// +----------------------------------------------------------------------
// | Date: 2020-08-31 15:18
// +----------------------------------------------------------------------

use app\model\api\SmsSend;
use app\model\api\SmsTpl;
use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Ic\V20190307\Models\SendSmsResponse;
use TencentCloud\Sms\V20190711\Models\SendSmsRequest;
use TencentCloud\Sms\V20190711\SmsClient;

class TencentSms {

    /**
     * 转义的模板信息[短信]
     */
    function SmsTplParm($content) {
        $data = func_get_args();
        foreach ($data[1] as $k => $v) {
            $content = str_replace('{' . $k . '}', $v, $content);
        }
        return $content;
    }

    /**
     * 发送模板的数据
     * @param type $tpl
     * @param type $code
     */
    function SmsSendTmplete($tel, $code,$sassid, $array = []) {
        $sData = SmsTpl::where("code",$code)->find();
        $r = false;
        $error = '';
        $req = null;
        if (!empty($sData)) {
            $req = $this->SmsSend($tel, $code, $array);
            if (!empty($req['Code'])  && $req['Code'] == 'OK') {
                $r = true;
            } else {
                $error = $req['Message'];
            }
            $datax['mobile'] = $tel;
            $datax['content'] = $this->SmsTplParm($sData['content'], $array);
            $datax['time'] = time();
            $datax['code'] = $code;
            $datax['sassid'] = $sassid;
            if ($r) {
                $datax['is_success'] = 1;
            } else {
                $datax['is_success'] = -1;
                $datax['error'] = $error;
            }
            ( new SmsSend)->insert($datax);
        }
        return $req;
    }


    /**
     * 发送短信
     * @param $tel
     * @param $code
     * @param $array
     */
    public function SmsSend($tel,$code,$array) {

        try {
            $config      = config('SMS');
            $cred        = new Credential($config['SecretId'], $config['SecretKey']);
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("sms.tencentcloudapi.com");
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            $client = new SmsClient($cred, "", $clientProfile);
            $req    = new SendSmsRequest();
            $params = [
                'TemplateID'     => $code,
                'SmsSdkAppid'    => $config['SmsAppId'],
                'Sign'           => $config['Sign'],
                'PhoneNumberSet' => ['+86' . $tel],
            ];
            ksort($array);
            $params["TemplateParamSet"] = [];
            foreach ($array as $v) {
                $params["TemplateParamSet"][] = $v;
            }
            $req->fromJsonString(json_encode($params));
            $resp = $client->SendSms($req);
            $data = json_decode($resp->toJsonString(),true);
            if($data['SendStatusSet'][0]['Code'] == 'Ok') {
                return ['Code'=>'OK','Message'=>'ok'];
            } else {
                return ['Code'=>'NO','Message'=>$data['SendStatusSet'][0]['Code']];
            }
        }catch(TencentCloudSDKException $e) {
            return ['Code'=>'no','Message'=>$e->getMessage()];
        }


    }


    private function fetchContent($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "x-sdk-client" => "php/2.0.0"
        ));
        if(substr($url, 0,5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        $rtn = curl_exec($ch);

        if($rtn === false) {
            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
        }
        curl_close($ch);
        return $rtn;
    }


}