<?php


namespace App\Services;


use App\Http\Controllers\api\TelegramWebHook;
use App\Services\BaseService;
use App\Models\User;
use App\Models\BalanceLog;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use Telegram\Bot\Api;
use Telegram\Bot\Exceptions\TelegramSDKException;
use App\Http\Controllers\api\Home;

class UserService extends BaseService
{
    public static string $MODEL = User::class;

    /**
     * @description: 模型
     * @return {string}
     */
    public static function model(): string
    {
        return User::class;
    }

    /**
     * @description: 枚举
     * @return {*}
     */
    public static function enum(): string
    {
        return '';
    }

    /**
     * @description: 获取查询条件
     * @param {array} $search 查询内容
     * @return {array}
     */
    public static function getWhere(array $search = []): array
    {
        $where = [];
        if (isset($search['id']) && !empty($search['id'])) {
            $where[] = ['users.id', '=', $search['id']];
        }

        if (isset($search['register_ip']) && !empty($search['register_ip'])) {
            $where[] = ['users.register_ip', '=', $search['register_ip']];
        }

        if (isset($search['member_id']) && !empty($search['member_id'])) {
            $where[] = ['users.member_id', '=', $search['member_id']];
        }
        if (isset($search['first_name']) && !empty($search['first_name'])) {
            $where[] = ['users.first_name', '=', $search['first_name']];
        }
        if (isset($search['username']) && !empty($search['username'])) {
            $where[] = ['users.username', '=', $search['username']];
        }
        if (isset($search['like_first_name']) && !empty($search['like_first_name'])) {
            $where[] = ['users.first_name', 'like', "%" . $search['like_first_name'] . "%"];
        }
        if (isset($search['user_code']) && !empty($search['user_code'])) {
            $where[] = ['users.user_code', '=', $search['user_code']];
        }
        if (isset($search['agent_user_code']) && !empty($search['agent_user_code'])) {
            $where[] = ['users.agent_user_code', '=', $search['agent_user_code']];
        }
        if (isset($search['level']) && !empty($search['level'])) {
            $where[] = ['users.level', '=', $search['level']];
        }
        // 用户类型/注册来源：-1 tg用户，0 后台客服账号，1 真实用户，2 虚拟用户
        // 不能用 empty()，否则 from=0（后台客服）会被误判为空
        if (array_key_exists('from', $search) && $search['from'] !== null && $search['from'] !== '') {
            $where[] = ['users.from', '=', $search['from']];
        }
        if (!empty($search['start_time'])) {
            $startTime = $search['start_time'] . " 00:00:00";
            $where[] = ['users.created_at', '>=', $startTime];
        }
        if (!empty($search['end_time'])) {
            $endTime = $search['end_time'] . " 23:59:59";
            $where[] = ['users.created_at', '<=', $endTime];
        }
        if (!empty($search['recharge_channel_group_id'])) {
            $where[] = ['users.recharge_channel_group_id', '=', $search['recharge_channel_group_id']];
        }
        return $where;
    }

    /**
     * @description: 查询单条数据
     * @param array $search
     * @return \App\Models\User|null
     */
    public static function findOne(array $search): ?User
    {
        return static::$MODEL::where(self::getWhere($search))->first();
    }

    /**
     * @description: 查询所有数据
     * @param array $search
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function findAll(array $search = [])
    {
        return static::$MODEL::where(self::getWhere($search))->get();
    }

    /**
     * @description: 分页查询
     * @param array $search
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public static function paginate(array $search = [], $order = 'desc', $by = 'created_at')
    {
        $limit = isset($search['limit']) ? $search['limit'] : 15;
        $page = isset($search['page']) ? $search['page'] : 1;
        $where = self::getWhere($search);
        $total = static::$MODEL::where($where)->count();
        $query = static::$MODEL::with(['wallet','level','agent'])
            ->leftJoin('wallets', 'users.member_id', '=', 'wallets.member_id')
            ->where($where);
        if ($by == 'available_balance') $by = "wallets.{$by}";
        else {
            $by = "users.{$by}";
        }
        $list = $query->orderBy($by, $order)
            ->select("users.*")
            ->forPage($page, $limit)
            ->get();

        $thirdGameBalances = app(ThirdGameBalanceService::class)->totals(
            $list->pluck('member_id')->all()
        );
        foreach($list as &$item) {
            $item['total_consume'] = BalanceLog::getTotalConsume($item->member_id);//用户累计消费总额
            $item['third_game_total_balance'] = $thirdGameBalances[(string) $item->member_id] ?? null;
        }
        return ['total' => $total, 'data' => $list];
    }

    //设置游戏ID
    public function setGameID($chatId, $gameId)
    {
        $gameId = trim($gameId);
        if (!$gameId) return ['chat_id' => $chatId, 'text' => '❌游戏ID设置失败，请输入正确的游戏ID'];

        if (User::where('game_id', $gameId)->where('member_id', '<>', $chatId)->first()) {
            return ['chat_id' => $chatId, 'text' => '❌游戏ID设置失败，游戏ID已绑定其他用户'];
        }
        $user = User::where('member_id', $chatId)->first();
        $user->game_id = $gameId;
        $user->save();
        return ['chat_id' => $chatId, 'text' => "✅ 游戏ID设置成功\n游戏ID：{$gameId}"];
    }

    /**
     * @param Api $telegram
     * @param $data
     * @param $chatId
     * @param $firstName
     * @param $messageId
     * @return void
     * @throws TelegramSDKException
     */
    public static function init(Api $telegram, $data, $chatId, $firstName, $messageId): void
    {
        $pattern = "/^setLanguage@@.*$/";
        if (preg_match($pattern, $data)) {
            $language = preg_replace('/^setLanguage@@/', '', $data);
            $res = UserService::setLanguage($chatId, $language);
            $telegram->deleteMessage(['chat_id' => $chatId, 'message_id' => $messageId]);
            TelegramWebHook::setReplyKeyboard($chatId, $language);
//            $telegram->sendMessage($res);
        }
    }


    public static function getIsBanned($memberId)
    {
        $user = User::where('member_id', $memberId)->first();
        return $user->is_banned == 1;
    }


    public static function setLanguage($chatId, $language): array
    {
        $userInfo = self::findOne(['member_id' => $chatId]);
        $userInfo->setLanguage($language);
        $userInfo->save();
        App::setLocale($language);
        (new Home)->setMyCommands();
        return self::getLanguages($chatId);
    }

    public static function getLanguages($chatId): array
    {
        $keyboard = [
            [['text' => lang('en'), 'callback_data' => "setLanguage@@en"]],
            [['text' => lang('zh'), 'callback_data' => "setLanguage@@zh"]],
            [['text' => lang('vi'), 'callback_data' => "setLanguage@@vi"]],
            [['text' => lang('❌取消'), 'callback_data' => "message@@close"]],
        ];
        return [
            'chat_id' => $chatId,
            'text' => lang("请选择您的语言"),
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard]),
            'protect_content' => true
        ];
    }

}
