<?php

namespace App\Services;

use App\Constants\StepStatus;
use App\Models\Address;
use App\Models\BalanceLog;
use App\Models\Bank;
use App\Models\Bet;
use App\Models\PaymentOrder;
use App\Models\Rebate;
use App\Models\User;
use App\Models\Wallet;
use Illuminate\Support\Facades\Cache;
use Telegram\Bot\Api;
use Telegram\Bot\Exceptions\TelegramSDKException;

class SecretService
{
    /**
     * @param Api $telegram
     * @param $data
     * @param $chatId
     * @param $firstName
     * @param $messageId
     * @throws TelegramSDKException
     */
    public static function init(Api $telegram, $data, $chatId, $firstName, $messageId): void
    {
        //秘钥管理首页
        if ($data === "secret@@index") {
            $res = SecretService::index($chatId, $messageId);
            $telegram->editMessageText($res);
        }

        //查看秘钥
        if ($data === "secret@@view") {
            $res = SecretService::view($chatId, $messageId);
            $telegram->editMessageText($res);
        }

        //找回账号
        if ($data === "secret@@retrieve") {
            $res = SecretService::retrieve($chatId, $messageId);
            $telegram->editMessageText($res);
        }

        //确认找回
        if ($data === "secret@@confirm") {
            $res = SecretService::confirm($chatId, $messageId);
            $telegram->editMessageText($res);
        }
    }

    public static function onMessage($chatId, $text, $messageId, $stepStatus): null|array
    {
        switch ($stepStatus) {
            case StepStatus::MY_INPUT_OLD_SECRET://输入原账户的秘钥
                $res = SecretService::inputOldSecret($chatId, $text, $messageId);
                break;
            case StepStatus::MY_INPUT_SECRET_PASS://输入查看秘钥的密码
                $res = SecretService::showSecretKey($chatId, $text, $messageId);
                break;
            default:
                $res = null;
                break;
        }
        return $res;

    }

    private static function showSecretKey($chatId, $password, $messageId): array
    {
        $user = User::where('member_id', $chatId)->first();
        if ($user->secret_pass == '') {
            $user->secret_pass = $password;
            $user->save();
        }


        if ($user->secret_pass !== $password) {
            $text = lang("密码错误");
            return [
                'chat_id' => $chatId,
                'text' => $text,
                'reply_to_message_id' => $messageId
            ];
        }

        $text = lang("秘钥") . "：{$user->secret_key}\n\n";
        $text .= lang("请保管好你的秘钥");
        return [
            'chat_id' => $chatId,
            'text' => $text,
        ];


    }

    private static function view($chatId, $messageId): array
    {
        $text = lang("请输入查看密码");
        $user = User::where('member_id', $chatId)->first();
        if ($user->secret_pass == '') {
            $secretKey = SecretService::generateRandomString(22);
            $user->secret_key = $secretKey;
            $user->save();
        }

        Cache::put(get_step_key($chatId), StepStatus::MY_INPUT_SECRET_PASS);

        return [
            'chat_id' => $chatId,
            'text' => $text,
            'message_id' => $messageId,
        ];
    }


    /**
     * @param string $chatId 接收者的member_id
     * @param string $secretKey 被接收者的 秘钥
     * @return bool
     */
    public static function migration(string $chatId, string $secretKey): bool
    {
        $user = User::where('secret_key', $secretKey)->where('member_id', '!=', $chatId)->first();
        $newUser = User::where('member_id', $chatId)->first();
        if (!$newUser || !$user) return false;
        $oldMemberId = $user->getMemberId();
//        $oldUserId = $user->id;
        $newMemberId = $chatId;
        $newUserId = $newUser->id;

        Address::where('member_id', $oldMemberId)->update(['member_id' => $newMemberId]);
        Bank::where('member_id', $oldMemberId)->update(['member_id' => $newMemberId]);
        Bet::where('member_id', $oldMemberId)->update(['member_id' => $newMemberId, 'user_id' => $newUserId]);
        PaymentOrder::where('member_id', $oldMemberId)->update(['member_id' => $newMemberId]);

        $wallet = Wallet::where('member_id', $user->getMemberId())->first();
        if ($wallet->available_balance > 0) {
            $res = WalletService::updateBalance($user->getMemberId(), $wallet->available_balance * -1);
            BalanceLogService::addLog($oldMemberId, $wallet->available_balance * -1, $res['before_balance'], $res['after_balance'], "资产转移", null, "转移至 {$newUser->getMemberId()}");

            $res = WalletService::updateBalance($chatId, $wallet->available_balance);
            BalanceLogService::addLog($chatId, $wallet->available_balance, $res['before_balance'], $res['after_balance'], "资产转移", null, "由 {$user->getMemberId()} 转移");
        }
        return true;
    }

    private static function confirm($chatId, $messageId): array
    {
        $secret = Cache::get("{$chatId}_OLD_SECRET");
//        $user = User::where(['secret_key' => $secret])->where('member_id', '!=', $chatId)->first();
//        $wallet = Wallet::where('member_id', $user->getMemberId())->first();

        $res = SecretService::migration($chatId, $secret);
        if ($res) {
            return [
                'chat_id' => $chatId,
                'text' => lang('已完成迁移'),
                'message_id' => $messageId,
            ];
        } else {
            return [
                'chat_id' => $chatId,
                'text' => lang('迁移失败'),
                'message_id' => $messageId,
            ];
        }


    }


    private static function inputOldSecret($chatId, $secret, $messageId): array
    {
        $user = User::where(['secret_key' => $secret])->where('member_id', '!=', $chatId)->first();
        if (!$user) {
            return [
                'chat_id' => $chatId,
                'text' => lang("输入错误，请重新输入"),
                'reply_to_message_id' => $messageId
            ];
        }
        $wallet = Wallet::where('member_id', $user->getMemberId())->first();

        $keyboard = [
            [
                ['text' => lang('取消'), 'callback_data' => 'topUp@@home'],
                ['text' => lang('确认'), 'callback_data' => 'secret@@confirm'],
            ]
        ];
        $wallet->available_balance = bcadd($wallet->available_balance, 0, 2);
        $available_balance = $wallet->available_balance;
        $text = lang("原账号信息") . "：\n";
        $text .= lang("用户ID") . "：{$user->getMemberId()}\n";
        $text .= lang("用户名") . "：{$user->getUsername()}\n";
        $text .= lang("昵称") . "：{$user->getFirstName()}\n";
        $text .= lang("余额") . "：{$wallet->available_balance} RMB\n";
        $text .= "-------------------------------\n";
        $user = User::where('member_id', $chatId)->first();
        $wallet = Wallet::where('member_id', $user->getMemberId())->first();
        $wallet->available_balance = bcadd($wallet->available_balance, 0, 2);
        $text .= lang("新账号信息") . "：\n";
        $text .= lang('用户ID') . "：{$user->getMemberId()}\n";
        $text .= lang("用户名") . "：{$user->getUsername()}\n";
        $text .= lang('昵称') . "：{$user->getFirstName()}\n";
        $text .= lang('余额') . "：{$wallet->available_balance} RMB\n";
        $available_balance = bcadd($available_balance, $wallet->available_balance, 2);
        $text .= "-------------------------------\n";
        $text .= lang('合并后余额') . "：{$available_balance} RMB\n\n";

        $text .= lang("注意：请确认原账号信息，点击确认后，原账号将注销，原账号的余额以及其他信息将合并到新账号中！\n此操作不可撤销。请取消或确认。");

        Cache::put("{$chatId}_OLD_SECRET", $secret);
        return [
            'chat_id' => $chatId,
            'text' => $text,
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
        ];
    }


    private static function retrieve($chatId, $messageId): array
    {


        Cache::put(get_step_key($chatId), StepStatus::MY_INPUT_OLD_SECRET);
        return [
            'chat_id' => $chatId,
            'text' => lang('请输入原账号的秘钥'),
            'message_id' => $messageId,
        ];
    }

    private static function index($chatId, $messageId): array
    {
        $keyboard = [
            [
                ['text' => lang('查看秘钥'), 'callback_data' => 'secret@@view'],
                ['text' => lang('找回账号'), 'callback_data' => 'secret@@retrieve'],
            ],

            [
                ['text' => lang('返回'), 'callback_data' => 'topUp@@home'],
            ]
        ];

        $text = lang("秘钥管理") . "\n";
        $text .= lang("请选择业务类型");

        return [
            'chat_id' => $chatId,
            'text' => $text,
            'message_id' => $messageId,
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
        ];
    }

    private static function generateRandomString($length = 10)
    {
        // 定义大写字母和数字的字符集
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';

        // 获取字符集的长度
        $charactersLength = strlen($characters);

        // 初始化随机字符串
        $randomString = '';

        // 生成随机字符串
        for ($i = 0; $i < $length; $i++) {
            // 从字符集随机选择一个字符
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }

        return $randomString;
    }

}