<?php
namespace App\Http\Controllers;

use App\Models\tg_groups;
use App\Models\tg_group_users;
use App\Models\tg_Msg;
use App\Models\TgGroups;
use App\Models\TgGroupUsers;
use App\Models\TgMsg;
use App\Services\TgApi;
use App\Services\TgComm;
use App\Services\UserFun;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class TgController extends Controller
{
    public function Msg($token,Request $request)
    {
        // 立即回应 Telegram（避免超时）
//        response()->json(['ok' => true])->send();
//        flush(); // 立即把回应送出

        // 接着执行后续处理（异步逻辑、写 log、存数据库等）
        $data = $request->all();
//        return $data;
        // $data = '{"update_id": 250041637, "message_date": 1746710794, "message_text": "@winchen1688 +2000", "message_chat_id": -4661252768, "message_from_id": 5909523353, "message_chat_type": "group", "message_chat_title": "一路发测试群", "message_message_id": 8, "message_from_is_bot": false, "message_from_username": "winchen1688", "message_from_last_name": "阿江", "message_entities_0_type": "mention", "message_from_first_name": "流浪的", "message_entities_0_length": 12, "message_entities_0_offset": 0, "message_from_language_code": "zh-hans", "message_chat_all_members_are_administrators": true, "message_chat_accepted_gift_types_unique_gifts": false, "message_chat_accepted_gift_types_limited_gifts": false, "message_chat_accepted_gift_types_unlimited_gifts": false, "message_chat_accepted_gift_types_premium_subscription": false}';
        $msg = UserFun::Json2Arr($data);  //将JSON转换成一維扁平陣列
        $msg['token'] = $token;
        $tgmsg = TgMsg::storeFromWebhookJson($msg); //写入对话消息
        $UserResponse = TgApi::GetChatMember($msg);  //获取用户资料
        $TgGroupUsers = TgGroupUsers::updateOrCreateFromTelegram($UserResponse['raw'], $msg['message_chat_id']); //更新用户资料
        $chatResponse = TgApi::GetChatInfo($msg);  //获取群资料
        $chatModel = TgGroups::updateOrCreateFromTelegram($chatResponse['result']);  //更新写入群资料
        $isComm = TgComm::TgComm($msg);   //判断是不是指令之一
        if ($isComm['ok']) {     //如果是指令进行指令的处理
            $botMsg = TgComm::{'comm_' . $isComm['id']}($msg);
//            if ($botMsg) {
//
//            }
        }
    }

}
