<?php

namespace App\Notification;

use App\Util;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Request;
use Longman\TelegramBot\Entities\Update;
use Longman\TelegramBot\Exception\TelegramException;
use Longman\TelegramBot\Telegram;

class TelegramBot
{
    const api_key=':';
    const username='';
    public $telegram;
    public function __construct(){
        try {
            $telegram = new Telegram(self::api_key, self::username);

            $mysql=['host' => env('DB_MYSQL_HOST', '172.31.18.221'),
                'port' => env('DB_MYSQL_PORT', '3306'),
                'database' => 'telegram',
                'user' => env('DB_MYSQL_USERNAME'),
                'password' => env('DB_MYSQL_PASSWORD'),  ];
            $telegram->enableMySql($mysql);

            $this->telegram=$telegram;
////            $result = $this->telegram->setWebhook("https://".$_SERVER["HTTP_HOST"]."/api/telehook");
//            $allowed_updates = [
//                Update::TYPE_MESSAGE,
//                Update::TYPE_CHANNEL_POST,
//                // etc.
//            ];
//            $this->telegram->handleGetUpdates(['allowed_updates' => $allowed_updates]);
//            if ($result->isOk()) {
//                echo $result->getDescription();
//                Util::WriteLog('telegram', $result->getDescription());
//            }


        }catch (TelegramException $e){
            Util::WriteLog('telegram','error:'.$e->getMessage());
        }
    }
    public function handle(){
        try {
            return $this->telegram->handle();
        }catch (TelegramException $e){
            Util::WriteLog('telegram',$e);
        }
    }
    public function sendMsg($str){
        if(env('TELE_SENDOUT')){
            $url=env('TELE_SENDOUT');
            $client = new Client();
            $client->post( $url , [
                'form_params' => ['str'=>$str], // 传递 POST 数据
            ]);
            return;
        }
        $str=substr($str,0,4000);
        try {
            \Longman\TelegramBot\Request::sendToActiveChats(
                'sendMessage', // Callback function to execute (see Request.php methods)
                ['text' => $str], // Param to evaluate the request
                [
                    'groups'      => true,
                    'supergroups' => true,
                    'channels'    => false,
                    'users'       => false,
                ]
            );
        }catch (\Exception $e){
            Util::WriteLog('telegram',$e->getMessage());
        }
    }
    public function sendMsgWithEnv($str){
        if(is_array($str))$str=json_encode($str);

        $url=$_SERVER['REQUEST_SCHEME'].$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'].'?'.http_build_query(Request::all());
        $env = env('APP_ENV');//](".$url.")

        $str=$str."\n".'#### url:' . Request::getRequestUri()  . "\n" .
        '#### params:' . json_encode(Request::all()) . "\n".(new \Exception())->getTraceAsString() ;
        $this->sendMsg($env .":". $str);

    }
    public function sendProgramNotify($compName="",$str="",$contentArr=[]){
        $env = env('APP_ENV');
        $this->sendMsg($env . " $compName 异常 ###\n [$str]\n".json_encode($contentArr,JSON_PRETTY_PRINT));
    }

    /**
     * @var TelegramBot
     */
    static private $_default=null;

    /**
     * @return TelegramBot
     */
    static public function getDefault(){
        if(!isset(self::$_default)||self::$_default==null)self::$_default=new TelegramBot();
        return self::$_default;
    }
}
