<?php

namespace App\Http\Controllers\Admin;

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

class GameSomeConfigController
{
    /**
     * 个控回报配置列表（可编辑）
     */
    public function index(Request $request)
    {
        // 获取游戏ID，默认为0（通用配置）
        $gameId = $request->input('game_id', 0);

        // 获取库存模式，默认为1（普通模式）
        $stockMode = $request->input('stock_mode', 1);

        // 可选的游戏列表
        $games = [
            0 => '通用配置',
            '921219001' => 'IGT-双砖',
            '1519119693' => 'Jokers Jewels',
        ];

        // 查询指定GameID和StockMode的配置
        $configs = DB::connection('write')
            ->table('QPPlatformDB.dbo.GameSomeConfig')
            ->where('GameID', $gameId)
            ->where('StockMode', $stockMode)
            ->orderBy('ZMin', 'asc')
            ->orderBy('ZMax', 'asc')
            ->orderBy('MultiMin', 'asc')
            ->get();

        return view('admin.game_some_config.index', compact('configs', 'games', 'gameId', 'stockMode'));
    }

    /**
     * 批量更新配置（只更新有变动的数据）
     */
    public function update(Request $request)
    {
        try {
            $configs = $request->input('configs', []);

            if (empty($configs)) {
                return apiReturnFail('没有需要更新的数据');
            }

            DB::beginTransaction();

            $updatedIds = [];
            $updatedCount = 0;

            foreach ($configs as $configId => $data) {
                // 构建更新数据（只包含提交的字段）
                $updateData = [];

                if (isset($data['ZMin'])) {
                    $updateData['ZMin'] = (int)$data['ZMin'];
                }
                if (isset($data['ZMax'])) {
                    $updateData['ZMax'] = (int)$data['ZMax'];
                }
                if (isset($data['MultiMin'])) {
                    $updateData['MultiMin'] = round((float)$data['MultiMin'], 2);
                }
                if (isset($data['MultiMax'])) {
                    $updateData['MultiMax'] = round((float)$data['MultiMax'], 2);
                }
//                if (isset($data['MultiAvg'])) {
//                    $updateData['MultiAvg'] = round((float)$data['MultiAvg'], 2);
//                }
                if (isset($data['Weight'])) {
                    $updateData['Weight'] = (int)$data['Weight'];
                }
                // 个控调节支持配置为空（使用 array_key_exists 以支持空字符串）
                if (array_key_exists('WeightAdjust', $data)) {
                    $updateData['WeightAdjust'] = (string)($data['WeightAdjust'] ?? '');
                }

                // Status字段不允许修改，已移除

                // 只有有数据时才更新
                if (!empty($updateData)) {
                    DB::connection('write')
                        ->table('QPPlatformDB.dbo.GameSomeConfig')
                        ->where('ConfigID', $configId)
                        ->update($updateData);

                    $updatedIds[] = $configId;
                    $updatedCount++;
                }
            }

            DB::commit();

            \Log::info('个控回报配置更新成功', [
                'admin_id' => $request->session()->get('admin')->id ?? 0,
                'updated_count' => $updatedCount,
                'config_ids' => $updatedIds
            ]);

            return apiReturnSuc("配置更新成功，共更新 {$updatedCount} 条数据");

        } catch (\Exception $e) {
            DB::rollBack();
            \Log::error('个控回报配置更新失败', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return apiReturnFail('更新失败: ' . $e->getMessage());
        }
    }
}
