<?php


namespace App\Services;

use App\Services\BaseService;
use App\Models\Keyboard;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Cache;
use App\Services\BetService;
use App\Services\BalanceLogService;
use App\Services\IssueService;
use App\Services\WalletService;
use App\Constants\Util;
use Illuminate\Support\Facades\Log;
use App\Services\SanJinRechargeService;
use Telegram\Bot\FileUpload\InputFile;

/**
 * 菜单
 */
class KeyboardService extends BaseService
{
    public static string $MODEL = Keyboard::class;

    /**
     * @description: 模型
     * @return {string}
     */
    public static function model(): string
    {
        return Keyboard::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[] = ['id', '=', $search['id']];
        }

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

        if (isset($search['button']) && !empty($search['button'])) {
            $where[] = ['button', '=', $search['button']];
        }
        if (isset($search['explain']) && !empty($search['explain'])) {
            $where[] = ['explain', '=', $search['explain']];
        }
        if (isset($search['language']) && !empty($search['language'])) {
            $where[] = ['language', '=', $search['language']];
        }

        return $where;
    }

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

    /**
     * @description: 查询所有数据
     * @param array $search
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public static function findAll(array $search = [])
    {

        return self::model()::where(self::getWhere($search))->get();

    }

    /**
     * @description: 分页查询
     * @param array $search
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public static function paginate(array $search = [])
    {
        $limit = isset($search['limit']) ? $search['limit'] : 15;
        $paginator = self::model()::where(self::getWhere($search))
             ->orderByDesc("id")
            ->paginate($limit);
        foreach ($paginator->items() as $item) {
            if (isset($item->buttons) && !empty($item->buttons)) {
                $item->buttons = json_decode($item->buttons, true);
            } else {
                $item->buttons = [];
            }
        }
        return ['total' => $paginator->total(), 'data' => $paginator->items()];
    }

    /**
     * @description:
     * @param {*} $params
     * @return {*}
     */
    public static function submit($params = [])
    {
        $result = false;
        $msg['code'] = self::NOT;
        $msg['msg'] = '';
        if (isset($params['buttons']) && !empty($params['buttons'])) {
            if (is_array($params['buttons'])) {
                $params['buttons'] = json_encode($params['buttons'], JSON_UNESCAPED_UNICODE);
            }
        } else {
            $params['buttons'] = json_encode([], JSON_UNESCAPED_UNICODE);
        }
        if (isset($params['image'])) {
            $params['image'] = Util::replacePartInUrl($params['image']);
        }

        // 2. 判断是否是更新
        if (!empty($params['id'])) {
            $info = self::findOne(['id' => $params['id']]);

            if (!$info) {
                $msg['msg'] = '数据不存在！';
            } else {
                if ($info->group_id != 1) {
                    unset($params['button']);
                }
                $result = $info->update($params);
                $id = $params['id'];
            }

        } else {
            // 创建
            $params['group_id'] = 1;
            $result = $info = static::$MODEL::create($params);
            $id = $result->id;
        }


        if ($result) {
            $msg['code'] = self::YES;
            $msg['msg'] = '设置成功';
        } else {
            $msg['msg'] = empty($msg['msg']) ? '操作失败' : $msg['msg'];
        }

        return $msg;
    }

    // 校验开始菜单 事件
    public static function checkStart($chatId, $keyword = '')
    {

        // Log::error('开始使用菜单事件：',['chatId'=>$chatId,'keyword'=>$keyword]);
        // 查找开始使用的菜单
        $list = self::findAll(['button' => '开始使用'])->toArray();

        foreach ($list as $item) {
            $buttons = [];
            if (isset($item['buttons']) && !empty($item['buttons'])) {
                $buttons = json_decode($item['buttons'], true);
            }

            // var_dump($buttons);
            foreach ($buttons as $row) {
                foreach ($row as $k => $v) {
                    if (isset($v['text']) && $v['text'] == $keyword) {

                        if (isset($v['url']) && !empty($v['url'])) {
                            return self::menuEvent($chatId, $v['url']);
                        }
                    }
                }

            }
        }

        return false;
    }

    // 开始菜单触发事件
    public static function menuEvent($chatId, $event = '')
    {
        switch ($event) {
            case "promotionalActivity":
                // 删除个人缓存
                Util::delCache($chatId);
                return ActivityRewardService::promotionalActivity($chatId);
            case 'recentBets': // 近期注单
                // 删除个人缓存
                Util::delCache($chatId);
                return BetService::record($chatId);

                break;
            case 'flowList': // 流水列表
                // 删除个人缓存
                Util::delCache($chatId);
                return BalanceLogService::getFlowingHistory($chatId);

                break;
            case 'winningHistory': // 开奖历史
                // 删除个人缓存
                Util::delCache($chatId);
                return IssueService::currentLotteryResults($chatId);

                break;
            case 'currentBetting': // 本期下注
                // 删除个人缓存
                Util::delCache($chatId);
                return BetService::currentBet($chatId);
            case 'checkBalance': // 查看余额
                // 删除个人缓存
                Util::delCache($chatId);
                // 查看余额 同步充值记录
                RechargeService::markUsdtRechargePending($chatId);
                RechargeService::syncUsdtRechargeRecords($chatId);
                return WalletService::getBalance($chatId);
            case 'selectLanguage': // 选择语言
                // 删除个人缓存
                Util::delCache($chatId);
                return UserService::getLanguages($chatId);

                break;
            case 'topUp': // 充值上分
                // 删除个人缓存
                Util::delCache($chatId);
                return SanJinRechargeService::qbApply($chatId);

                break;
            case "football":    //F1bet娱乐更多玩法(足球首页)
                // 删除个人缓存
                Util::delCache($chatId);
                return ActivityRewardService::footballUrl($chatId);

                break;
            default:
                return false;
        }
    }

    private static function isValidURL($url)
    {
        return filter_var($url, FILTER_VALIDATE_URL) !== false;
    }

    public static function getKeyWordReply($chatId, $text): ?array
    {
        // 关键字回复
        $keyboardText = KeyboardService::findOne(['button' => $text]);
        if ($keyboardText) {
            $keyboard = [];
            if ($keyboardText['buttons']) {
                $keyboard = json_decode($keyboardText['buttons'], true);
                $newKeyboard = [];
                foreach ($keyboard as $item) {
                    $t = [];
                    foreach ($item as $item1) {
                        if (static::isValidURL($item1['url'])) {
                            $t[] = $item1;
                        }
                    }
                    if (!empty($t)) $newKeyboard[] = $t;
                }
                $keyboard = $newKeyboard;
            }
            Util::delCache($chatId);
            $res = [
                'chat_id' => $chatId,
                'text' => $keyboardText['reply'],
                // 'reply_to_message_id' => $messageId
            ];
            if ($keyboard) {
                $res['reply_markup'] = json_encode(['inline_keyboard' => $keyboard]);
            }
            if ($keyboardText['image']) {
                $res['photo'] = InputFile::create(url($keyboardText['image']));
                unset($res['text']);
                $res['caption'] = $text;
                $res['protect_content'] = true;  // 防止转发
            }
            return $res;
        }
        return null;
    }
}
