<?php
namespace App\Services;

use App\Models\Ledger;
use App\Models\tg_comm;
use App\Models\TgGroupUsers;
use App\Models\UserAccount;
use Illuminate\Support\Facades\Storage;

class TgComm
{
    public static function TgComm($msg){
        $tg_comm = include Storage::disk('dataconfig')->path('TgComm.php');
        foreach ($tg_comm as $v) {
            if (str_starts_with($msg['message_text'], $v['command'])){
                $res['ok']= true;
                $res['id']= $v['id'];
                $res['command']= $v['command'];
                return $res;  //有的话 返回指令ID
            }
        }
    }

    public static function comm_1($msg){

    }

    //‘@’指令的处理
    public static function comm_2($msg){
        $res = self::parseLedgerMessage($msg['message_text']); //
        if ($res) {
            $TgGroupUsers=TgGroupUsers::GetUsername($res['username']);  //获取用户资料
            if ($TgGroupUsers) {
                $res=array_merge($res, ['user_id' => $TgGroupUsers->user_id,'chat_id'=>$msg['message_chat_id'],'token'=>$msg['token']]);  //加入用户和群组ID
                $Ledger=Ledger::AddIncome($res);  //写入收支记录
                $CheckUser=UserAccount::CheckUserId($res);  //检查该user_id是否有账户资料，有的话处理余额,没有的话添加相关账户资料
                if ($CheckUser){
                    $balance=UserAccount::UpdateUser($res);  //更新账号余额
                    $data=array_merge($res,['comm' => 2,'balance' => $balance,'token' => $msg['token']]); //添加资料到数组
                    $Msg=TgMsg::MakeMsg($data);  //构成发送数据
//                    dd($Msg);
                    $res=UserFun::CurlPost($Msg['url'],$Msg['text']);    //发送Tg消息
                    dd($res);
                    return $res;
                } else {
                    $balance=UserAccount::CreatUser($res); //新建用户账号,并写入充值金额
                    $res=array_merge($res,['balance' => $balance]);
                    //发送Tg通知
                    $Msg=TgMsg::MakeMsg($res);  //构成发送数据
                    dd($Msg);
                    $res=CurlPost($Msg);
                    return $res;
                }
            } else {
                return $res['usernamer'].'-该用户不存在';
            }
        } else {
            return false;
        }
    }

    //拆解【@XXX +1000】字串
    private static function parseLedgerMessage(string $text): ?array
    {
        if (preg_match('/@(\w+)\s*([+-])\s*(\d+(?:\.\d+)?)/', $text, $matches)) {
            $username = $matches[1];
            $type = $matches[2] === '+' ? '0' : '1';
            $amount = (float) str_replace(',', '', $matches[3]);

            return compact('username', 'type', 'amount');
        }

        return null; // 格式不符
    }

}
