<?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='8489593650:AAEioF92HCRDd-mnDpTo-6imc_bdi1My1II';
    const username='@uswinBot';
    public $telegram;
    public function __construct(){
        try {
            $telegram = new Telegram(self::api_key, self::username);

            $mysql=['host' => env('DB_MYSQL_HOST', '127.0.0.1'),
                '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 {
            $update = json_decode(file_get_contents('php://input'), true);

            Util::WriteLog('telegram_update', json_encode($update, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));
            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());
        }
    }

    /**
     * 定向发到「重要通知」群（.env：TELEGRAM_IMPORTANT_CHAT_IDS，逗号分隔多个 chat_id）。
     * 与 sendMsg 的 sendToActiveChats 不同：不依赖 telegram 库里的活跃会话表。
     */
    public function sendImportantMsg($str)
    {
        $str = substr((string) $str, 0, 4000);
        if ($str === '' || empty($this->telegram)) {
            return;
        }
        foreach ($this->importantChatIds() as $chatId) {
            try {
                \Longman\TelegramBot\Request::sendMessage([
                    'chat_id' => $chatId,
                    'text'    => $str,
                ]);
            } catch (\Exception $e) {
                Util::WriteLog('telegram', 'important chat_id=' . $chatId . ' ' . $e->getMessage());
            }
        }
    }

    /** 老群广播 + 重要群各发一份（关键告警用） */
    public function sendMsgAndImportant($str)
    {
        $this->sendMsg($str);
        $this->sendImportantMsg($str);
    }

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

    /**
     * @return int[]
     */
    private function importantChatIds()
    {
        $raw = env('TELEGRAM_IMPORTANT_CHAT_IDS', '');
        if ($raw === null || $raw === '') {
            return [];
        }
        $parts = preg_split('/\s*,\s*/', (string) $raw, -1, PREG_SPLIT_NO_EMPTY);
        $ids = [];
        foreach ($parts as $p) {
            if (is_numeric($p)) {
                $ids[] = (int) $p;
            }
        }
        return $ids;
    }

    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;
    }
}
