<?php
/**
 * Created by PhpStorm.
 * User: ty01
 * Date: 2022/3/22
 * Time: 17:43
 */

// This file is auto-generated, don't edit it. Thanks.
namespace app\api\controller\huaweicloud;

use app\common\controller\Api;
use app\common\helper\HttpHelper;
use think\Db;
use think\Request;

header('Content-type:text/html; Charset=utf-8');
date_default_timezone_set('PRC');

class Base extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $hwyvoice_app_key;
    protected $hwyvoice_app_secret;
    protected $hwyvoice_base_url;
    protected $hwyvoice_access_token;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->hwyvoice_app_key = config("site.hwyvoice_app_key");//华为云语音通知接口app_key
        $this->hwyvoice_app_secret = config("site.hwyvoice_app_secret");//华为云语音通知接口app_secret
        $this->hwyvoice_base_url = config("site.hwyvoice_base_url");//华为云语音通知接口域名
        $hwyvoice_access_token =$this->getHwyVoiceAccessToken();
        $this->hwyvoice_access_token = $hwyvoice_access_token;
    }

    /**
     * 1、获取AccessToken(C1 系统配置类接口鉴权方式)
     */
    public function getHwyVoiceAccessToken()
    {
        $access_token = Db::name("hwy_access_token")->where("type", "voice")->find();
        if (empty($access_token) || empty($access_token['access_token']) || $access_token['over_time'] <= time()) {
            //access_token失效

            //获取新的access_token
            $url = $this->hwyvoice_base_url."/apigovernance/api/oauth/tokenByAkSk";
            $param = [
                "app_key"=>$this->hwyvoice_app_key,
                "app_secret"=>$this->hwyvoice_app_secret
            ];
            $param = json_encode($param,true);
            $header = [
                "Content-type:application/json",
                "X-Token-Expire:600"
            ];
            $res = $this->send_post($url, $param,$header);
            $res = json_decode($res, true);
            $expries = $res['Expires']?$res['Expires']:600;

            $new_token = $res['AccessToken'];
            if (!empty($new_token)) {
                $time = time();
                $update_data = [
                    "access_token" => $new_token,
                    "over_time" => $time + $expries,
                    "type" => "voice",
                    "updatetime" => $time
                ];
                if (!empty($access_token)) {
                    //更新
                    Db::name("hwy_access_token")->where("id", $access_token['id'])->update($update_data);
                } else {
                    //新增
                   Db::name("hwy_access_token")->insertGetId($update_data);
                }
            }
        } else {
            $access_token = $access_token['access_token'];
        }
        return $access_token;
    }

    /**
     * 2、查询语音通知的录音文件(queryVoiceNotificationRecording)
     */
    public function queryVoiceNotificationRecording(){

        $url = $this->hwyvoice_base_url."/apiaccess/rest/voiceNotification/v1/queryVoiceNotificationRecording";
        $param = [
            "reqBody"=>[
//                "offset"=>0,//起始游标,即分页查询时的起始记录行号。首次查询传入“0”。后续查询其他分页时传入该分页的第一条记录的序号。返回记录中第一条记录序号为“0”,后续依次排序。例如每页为50条录,查询第二页时应传入“50”。不传时默认0,无最大值限制
//                "limit"=>"100",//分页查询时的每页记录数,正整数,不传时默认100,最大值100,传入超过100的值也会转换为100
//                "type"=>0,//录音文件类型 0:音频,2:text文本
            ]
        ];
        $param = json_encode($param,true);
        $header = [
            "Content-type:application/json",
            "X-APP-Key:".$this->hwyvoice_app_key,
            "Authorization:Bearer ".$this->hwyvoice_access_token
        ];
        $res = $this->send_post($url, $param,$header);
        $res = json_decode($res, true);
        dump($res);die;
    }

    /**
     * 3、创建语音通知(V1.0.0)(createVoiceNotification)
     */

    public function createVoiceNotification(){
        $url = $this->hwyvoice_base_url."/apiaccess/rest/voiceNotification/v1/createVoiceNotification";
        $param = [
            "reqBody"=>[
                "voiceContent"=>"$"."云南预警发布中心~"."$"."红河州气象台2023年04月14日17时30分继续发布强对流黄色预警:预计未来12小时,全州13县市将出现雷电活动,并伴有短时强降水、大风、局地冰雹等强对流天气,请注意防范。"."$",
//                "callerPresent"=>"False",//用户侧主叫显示号码,用户看到的主叫号码
                "called"=>18987495413,//被叫号码
                "callBackUrl"=>get_root_url()."/api/huaweicloud/base/callBackUrl",
            ]
        ];

        $param = json_encode($param,true);
        $header = [
            "Content-type:application/json",
            "X-APP-Key:".$this->hwyvoice_app_key,
            "Authorization:Bearer ".$this->hwyvoice_access_token
        ];
        dump($url);
        dump($param);
        dump($header);
        $res = $this->send_post($url, $param,$header);
        $res = json_decode($res, true);
        dump($res);die;
    }

    /**
     * callBackUrl
     */
    public function callBackUrl(){
        $param = $this->request->param("");
        file_put_contents("kevin_voice_notify.log",date("Y-m-d H:i:s").json_encode($param,JSON_UNESCAPED_UNICODE).PHP_EOL,FILE_APPEND);
    }


    // 发送 POST 请求的函数
    function send_post($url, $post_data,$header=[])
    {
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => $header?$header:'Content-type:application/json',
                'content' => $post_data,
                'timeout' => 60
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }

}