<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;

class GameNumberMappingController
{
    /**
     * 数字游戏映射列表
     */
    public function index(Request $request)
    {
        // 从 SQL Server 查询所有映射关系
        $mappings = DB::connection('write')
            ->table('agent.dbo.game_number_mapping')
            ->select('id', 'number', 'game_id')
            ->orderBy('number', 'asc')
            ->get();

        // 获取所有游戏ID
        $gameIds = $mappings->pluck('game_id')->unique()->toArray();

        // 从 MySQL 查询游戏信息
        $games = [];
        if (!empty($gameIds)) {
            $gamesData = DB::connection('mysql')
                ->table('webgame.games')
                ->whereIn('id', $gameIds)
                ->select('id', 'brand', 'title')
                ->get();
            
            // 转换为以 game_id 为键的数组
            foreach ($gamesData as $game) {
                $games[$game->id] = $game;
            }
        }

        // 合并数据
        foreach ($mappings as $mapping) {
            if (isset($games[$mapping->game_id])) {
                $mapping->brand = $games[$mapping->game_id]->brand;
                $mapping->title = $games[$mapping->game_id]->title;
            } else {
                $mapping->brand = null;
                $mapping->title = null;
            }
        }

        return view('admin.game_number_mapping.index', compact('mappings'));
    }

    /**
     * 添加映射页面
     */
    public function add(Request $request)
    {
        if ($request->isMethod('post')) {
            // 手动检查数字是否已存在
            $exists = DB::connection('write')
                ->table('agent.dbo.game_number_mapping')
                ->where('number', $request->number)
                ->exists();
            
            if ($exists) {
                return apiReturnFail('该数字已被使用');
            }
            
            // 从 MySQL 检查游戏是否存在
            $gameExists = DB::connection('mysql')
                ->table('webgame.games')
                ->where('id', $request->game_id)
                ->exists();
            
            if (!$gameExists) {
                return apiReturnFail('选择的游戏不存在');
            }
            
            $validator = Validator::make($request->all(), [
                'number' => 'required|integer|min:0|max:9',
                'game_id' => 'required|integer',
            ], [
                'number.required' => '数字不能为空',
                'number.integer' => '数字必须是0-9之间的整数',
                'number.min' => '数字必须在0-9之间',
                'number.max' => '数字必须在0-9之间',
                'game_id.required' => '请选择游戏',
            ]);

            if ($validator->fails()) {
                return apiReturnFail($validator->errors()->first());
            }

            try {
                DB::connection('write')
                    ->table('agent.dbo.game_number_mapping')
                    ->insert([
                        'number' => $request->number,
                        'game_id' => $request->game_id,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);

                // 清除缓存
                $cacheKey = 'game_number_mapping:' . $request->number;
                Redis::del($cacheKey);

                return apiReturnSuc('添加成功');
            } catch (\Exception $e) {
                return apiReturnFail('添加失败：' . $e->getMessage());
            }
        }

        // 从 MySQL 获取所有游戏列表
        $games = DB::connection('mysql')
            ->table('webgame.games')
            ->select('id', 'brand', 'title')
            ->where('state', '>', 0)
            ->orderBy('brand')
            ->orderBy('title')
            ->get();

        // 获取已使用的数字
        $usedNumbers = DB::connection('write')
            ->table('agent.dbo.game_number_mapping')
            ->pluck('number')
            ->toArray();

        return view('admin.game_number_mapping.add', compact('games', 'usedNumbers'));
    }

    /**
     * 修改映射页面
     */
    public function update(Request $request, $id)
    {
        $mapping = DB::connection('write')
            ->table('agent.dbo.game_number_mapping')
            ->where('id', $id)
            ->first();

        if (!$mapping) {
            return apiReturnFail('映射不存在');
        }

        if ($request->isMethod('post')) {
            // 手动检查数字是否已被其他记录使用
            $exists = DB::connection('write')
                ->table('agent.dbo.game_number_mapping')
                ->where('number', $request->number)
                ->where('id', '!=', $id)
                ->exists();
            
            if ($exists) {
                return apiReturnFail('该数字已被使用');
            }
            
            // 从 MySQL 检查游戏是否存在
            $gameExists = DB::connection('mysql')
                ->table('webgame.games')
                ->where('id', $request->game_id)
                ->exists();
            
            if (!$gameExists) {
                return apiReturnFail('选择的游戏不存在');
            }
            
            $validator = Validator::make($request->all(), [
                'number' => 'required|integer|min:0|max:9',
                'game_id' => 'required|integer',
            ], [
                'number.required' => '数字不能为空',
                'number.integer' => '数字必须是0-9之间的整数',
                'number.min' => '数字必须在0-9之间',
                'number.max' => '数字必须在0-9之间',
                'game_id.required' => '请选择游戏',
            ]);

            if ($validator->fails()) {
                return apiReturnFail($validator->errors()->first());
            }

            try {
                // 获取旧的 number，用于清除旧缓存
                $oldNumber = $mapping->number;
                
                DB::connection('write')
                    ->table('agent.dbo.game_number_mapping')
                    ->where('id', $id)
                    ->update([
                        'number' => $request->number,
                        'game_id' => $request->game_id,
                        'updated_at' => now(),
                    ]);

                // 清除旧的和新的缓存
                $oldCacheKey = 'game_number_mapping:' . $oldNumber;
                $newCacheKey = 'game_number_mapping:' . $request->number;
                Redis::del([$oldCacheKey, $newCacheKey]);

                return apiReturnSuc('修改成功');
            } catch (\Exception $e) {
                return apiReturnFail('修改失败：' . $e->getMessage());
            }
        }

        // 从 MySQL 获取游戏信息
        $game = DB::connection('mysql')
            ->table('webgame.games')
            ->where('id', $mapping->game_id)
            ->first();

        // 从 MySQL 获取所有游戏列表
        $games = DB::connection('mysql')
            ->table('webgame.games')
            ->select('id', 'brand', 'title')
            ->where('state', '>', 0)
            ->orderBy('brand')
            ->orderBy('title')
            ->get();

        // 获取已使用的数字（排除当前记录）
        $usedNumbers = DB::connection('write')
            ->table('agent.dbo.game_number_mapping')
            ->where('id', '!=', $id)
            ->pluck('number')
            ->toArray();

        return view('admin.game_number_mapping.update', compact('mapping', 'game', 'games', 'usedNumbers'));
    }

    /**
     * 删除映射
     */
    public function delete(Request $request, $id)
    {
        try {
            // 先获取要删除的记录，用于清除缓存
            $mapping = DB::connection('write')
                ->table('agent.dbo.game_number_mapping')
                ->where('id', $id)
                ->first();

            $deleted = DB::connection('write')
                ->table('agent.dbo.game_number_mapping')
                ->where('id', $id)
                ->delete();

            if ($deleted) {
                // 清除缓存
                if ($mapping) {
                    $cacheKey = 'game_number_mapping:' . $mapping->number;
                    Redis::del($cacheKey);
                }
                return apiReturnSuc('删除成功');
            } else {
                return apiReturnFail('删除失败，记录不存在');
            }
        } catch (\Exception $e) {
            return apiReturnFail('删除失败：' . $e->getMessage());
        }
    }
}
