<?php

namespace app\controller;

use app\extend\IFlytek\Xfyun\Speech\TtsClient;
use support\Request;
use Webman\Container;
use Webman\Push\Api;

class IndexController
{
    private $app_id = '2eda6c2e';

    private $api_key = '12ec1f9d113932575fc4b114a2f60ffd';

    private $api_secret = 'MDEyMzE5YTc5YmQ5NjMwOTU1MWY4N2Y2';


    private $ttsConfig = [
        'aue' => 'lame',
        'sfl' => 1,
        'vcn' => 'x4_lingxiaoyao_en'
    ];

    public function index(Request $request)
    {
        return json(['code' => 0, 'msg' => 'ok']);

    }

    public function view(Request $request)
    {
        return view('index/view', ['name' => 'webman']);
    }

    public function json(Request $request)
    {
        return json(['code' => 0, 'msg' => 'ok']);
    }

    public function push(Request $request){
        $parmas=$request->get('name');
        $api = new Api(
            // webman下可以直接使用config获取配置,非webman环境需要手动写入相应配置
            'http://127.0.0.1:3232',
            config('plugin.webman.push.app.app_key'),
            config('plugin.webman.push.app.app_secret')
        );
        // 给订阅 user-1 的所有客户端推送 message 事件的消息
        $api->trigger('user-1', 'message', [
            'from_uid' => 1,
            'content'  => $parmas
        ]);
        return json(['code' => 0, 'msg' => 'ok']);
    }

    public function tts(Request $request){
        $text = $request->post('data');
        $pattern = "/[\x{4e00}-\x{9fa5}\d]+/u";
        if( preg_match($pattern, $text)){
            $name = time() . rand(1, 100000) . '.mp3';
            $tts = new TtsClient($this->app_id, $this->api_key, $this->api_secret, $this->ttsConfig);
            file_put_contents(public_path('tts') . '/' . $name, $tts->request($text)->getBody()->getContents());
            return json(['code' => 0, 'msg' => 'ok','data'=>['mp3'=>'https://chat.lihaink.cn/tts/' . $name]]);
        }
        return json(['code' => 0, 'msg' => 'ok']);

    }

}