<?php

namespace App\Services;

use App\Constants\StepStatus;
use App\Models\Bank;
use App\Models\Config;
use App\Models\PaymentOrder;
use App\Models\Wallet;
use Illuminate\Support\Facades\Cache;
use Telegram\Bot\Api;
use App\Services\Payment\SanJinService;
use App\Services\BaseService;

class SanJinRechargeService extends BaseService
{
    /**
     * @param Api $telegram
     * @param $data
     * @param $chatId
     * @param $firstName
     * @param $messageId
     * @throws \Telegram\Bot\Exceptions\TelegramSDKException
     */
    public static function init(Api $telegram, $data, $chatId, $firstName, $messageId)
    {
        //点击三斤充值按钮
        if ($data === "topup@@sj_apply") {
            $res = SanJinRechargeService::qbApply($chatId, $messageId);
            $telegram->editMessageText($res);
        }


        //三斤账单
        $pattern = "/^topup@@sj_bill_\d+$/";
        if (preg_match($pattern, $data)) {
            $page = preg_replace('/^topup@@sj_bill_/', '', $data);
            if (empty($page) || $page < 1) $page = 1;
            $page = intval($page);
            $res = SanJinRechargeService::bill($chatId, $firstName, $messageId, $page);
            $telegram->editMessageText($res);
        }

        //选择充值
        $pattern = "/^topup@@sj_amount_\d+$/";
        if (preg_match($pattern, $data)) {
            $amount = preg_replace('/^topup@@sj_amount_/', '', $data);
           
            $res = SanJinRechargeService::inputSjAmount($chatId, $amount, $messageId);
            
            self::sendMessage($chatId,$res['text'],$res['keyboard']??[],$res['image']);
            // $telegram->editMessageText($res);
        }


        // 支付通道
        $pattern = '/^topup_channel@@(.+)$/';
        if (preg_match($pattern, $data, $matches)) {
            $k = $matches[1]; 
            
            // 验证 $k 是否有效
            $channel = SanJinService::getChannel();
            if (!isset($channel[$k])) {
                // 处理无效的通道
                $text = lang("无效的支付通道！");
                $res = [
                    'chat_id' => $chatId,
                    'text' => $text
                ];
                $telegram->sendMessage($res);
                return;
            }
            
           
            Cache::put($chatId.'_sj_payment_type', $k); 
            Cache::put(get_step_key($chatId), StepStatus::INPUT_RECHARGE_SJ_MONEY);

            $paymentType = $k;
            $product = SanJinService::product();
            $max = 0;
            $min = 0;
            $rate = 0;

            $keyboard = [];
            $rechargeText = '';
            foreach ($product as $k => $v) {
                if ($v['type'] == $paymentType) {

                    if($v['type'] == 'zfbge'){
                        $rechargeText = lang('充值金额')."：（".implode('，',$v['fixed'])."） \n";

                        foreach($v['fixed'] as $num){
                            $keyboard[] = [
                                ['text' => "{$num}", 'callback_data' => "topup@@sj_amount_".$num ]
                            ];
                        }
                        
                    }else{
                        if ($min == 0) {
                            $min = $v['min'];
                        }
                        if ($max == 0) {
                            $max = $v['max'];
                        }
                        if ($min > $v['min']) {
                            $min = $v['min'];
                        }
                        if ($max < $v['max']) {
                            $max = $v['max'];
                        }
                    }
                }
                
            }

            
            $text = lang("请输入充值的金额")." \n";
            // $text .= "充值方式：".$channel[$k];
            if($rechargeText){
                $text .= $rechargeText;
                $text .= lang("🔔 提示：请选择下方充值的金额");
            }else{
                $text .= lang("充值金额")."：{$min} - {$max} \n";
                $text .= lang("🔔 提示：请务必核对（充值最大金额和最小金额，账号信息一致），若不一致无法到账。");
    
            }

            $res = [
                'chat_id' => $chatId,
                'text' => $text,
                'message_id' => $messageId
            ];
            if($keyboard){
                $res['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
            }
            $telegram->editMessageText($res);
        }
    }

    public static function onMessage($chatId, $text, $messageId, $stepStatus)
    {
        switch ($stepStatus) {
            case StepStatus::INPUT_RECHARGE_SJ_MONEY://输入提现金额
                $res = SanJinRechargeService::inputSjAmount($chatId, $text, $messageId);
                return $res;
                break;
        }
        return null;
    }

    //三斤账单
    private static function bill($chatId, $firstName, $messageId, $page = 1, $limit = 5)
    {
        $list = PaymentOrder::where('member_id', $chatId)
            // ->where('type', 1)
            ->orderByDesc('created_at')
            ->forPage($page, $limit)
            ->get();

        $count = PaymentOrder::where('member_id', $chatId)
            // ->where('type', 1)
            ->count();


        $text = "👤 {$firstName}({$chatId})    ".lang('第三方订单记录')."\n\n";
        foreach ($list as $item) {
            $amount = floatval($item->amount);

            $amount = $item->type == 2 ? "➖ {$amount}" : "➕ $amount";
            $text .= "-------------------------------------\n";
            $text .= lang('订单类型')."：".($item->type == 1?lang("充值"):lang("提现"))." \n";
            $text .= lang('订单金额')."：{$amount} \n";
            $text .= lang('订单号')."：{$item->order_no}\n";
            if($item->type == 2){
                $text .= lang("银行")."：{$item->bank_name}\n";
                $text .= lang("姓名")."：{$item->account}\n";
                $text .= lang('卡号')."：{$item->card_no}\n";
            }else{
                $text .= lang("充值类型")."：".lang($item->bank_name)."\n";
            }

            $status = [lang('待处理'), lang('处理中'), lang('成功'), lang('失败')];
            
            if($item->type == 1 && $item->created_at < date('Y-m-d H:i:s',time() - 600) && $item->status == 1){
                $text .= lang('状态')."：".lang("已超时")."\n";
            }else{
                $text .= lang('状态')."：{$status[$item->status]}\n";

            }
            if ($item->remark) {
                $text .= lang('说明')."：{$item->remark}\n";
            }
            $text .= lang('日期')."：{$item->created_at}\n";
        }

        if ($page > 1) {
            $keyboard[] = [
                ['text' => lang("👆上一页"), 'callback_data' => "topup@@sj_bill_" . ($page - 1)]
            ];
        }
        $allPage = ceil($count / $limit);
        if ($allPage > $page) {
            if ($page > 1) {
                $keyboard[count($keyboard) - 1][] = ['text' => lang("👇下一页"), 'callback_data' => "topup@@sj_bill_" . ($page + 1)];
            } else {
                $keyboard[] = [
                    ['text' => lang("👇下一页"), 'callback_data' => "topup@@sj_bill_" . ($page + 1)]
                ];
            }
        }
        $keyboard[] = [
            ['text' => lang("↩️返回"), 'callback_data' => "topUp@@home"]
        ];
        return [
            'chat_id' => $chatId,
            'text' => $text,
            'message_id' => $messageId,
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
        ];
    }

    //1.三斤充值
    public static function qbApply($chatId, $messageId = null)
    {
        $three_payment_switch = Config::where('field', 'three_payment_switch')->first()->val;
        

        $text = lang("请选择支付的通道")." \n";
        $keyboard = [];
        $channel = SanJinService::getChannel();
        $keyboard[] = [
            ['text' => 'USDT', 'callback_data' => "topup@@topup"],
        ];

        if ($three_payment_switch == 1) {
            foreach($channel as $k => $v){
                $keyboard[] = [
                    ['text' => lang($v), 'callback_data' => "topup_channel@@" .$k]
                ];
            }
        }
        

        $keyboard[] = [
            ['text' => lang("↩️返回"), 'callback_data' => "topUp@@home"]
        ];
        // $wallet = Wallet::where('member_id', $chatId)->first();
        // $temp = floatval($wallet->available_balance);
        // $text = "请发送提现金额\n";
        // $text .= "💰 当前余额{$temp} RMB\n";


        // Cache::put(get_step_key($chatId), StepStatus::INPUT_WITHDRAW_QB_MONEY);
        return [
            'chat_id' => $chatId,
            'text' => $text,
            'message_id' => $messageId,
            'reply_markup' => json_encode(['inline_keyboard' => $keyboard])
        ];
    }

    //2.输入三斤提现金额
    private static function inputSjAmount($chatId, $amount, $messageId)
    {
        // 支付通道
        $paymentType = Cache::get($chatId.'_sj_payment_type');
        if(empty($paymentType)){
            // 处理无效的通道
            $text = lang("无效的支付通道！");
            $res = [
                'chat_id' => $chatId,
                'text' => $text
            ];
            return $res;
        }

        // 验证 $k 是否有效
        $channel = SanJinService::getChannel();
        if (!isset($channel[$paymentType])) {
            // 处理无效的通道
            $text = lang("无效的支付通道！");
            $res = [
                'chat_id' => $chatId,
                'text' => $text
            ];
            return $res;
            return;
        }

        if (!preg_match('/^\d+(\.\d{1,2})?$/', $amount)) {
            return [
                'chat_id' => $chatId,
                'text' => lang("金额输入不正确，请发送预充值数字"),
                'reply_to_message_id' => $messageId
            ];
        }
      
        $res = PaymentOrderService::createPay($chatId,$amount,$paymentType);
        if(isset($res['image'])){
            Cache::forget(get_step_key($chatId));
        }
        return $res;
    }


    public static function getWhere(array $search = []): array
    {
        return [];
    }
}