@extends('base.base')
@section('base')
<meta name="csrf-token" content="{{ csrf_token() }}">
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">PG游戏参数配置</h3>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <thead>
                                <tr>
                                    <th>游戏ID</th>
                                    <th>游戏名称</th>
                                    <th>配置</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($pgGames as $game)
                                <tr>
                                    <td>{{ $game['gameId'] }}</td>
                                    <td>{{ $game['gameName'] }}</td>
                                    <td>
                                        <div class="config-editor" data-game-id="{{ $game['gameId'] }}">
                                            @php 
                                                $config = $game['config'] ? $game['config'] : [
                                                    "1" => ["FreeWinMax" => 7000, "RechargeControl" => 7000, "RechargeMaxPercent" => 70],
                                                    "2" => ["FreeWinMax" => 30000, "RechargeControl" => 100000, "RechargeMaxPercent" => 50],
                                                    "3" => ["FreeWinMax" => 150000, "RechargeControl" => 500000, "RechargeMaxPercent" => 40]
                                                ];
                                            @endphp
                                            
                                            <div class="config-form">
                                                @foreach([1, 2, 3] as $level)
                                                <div class="card mb-3">
                                                    <div class="card-header bg-light">
                                                        <strong>等级{{ $level }}配置</strong>
                                                    </div>
                                                    <div class="card-body">
                                                        <div class="row">
                                                            <div class="col-md-4 form-group">
                                                                <label>免费最大赢额 (FreeWinMax)</label>
                                                                <input type="number" class="form-control freeWinMax-input" 
                                                                    step="0.01"
                                                                    name="level[{{ $level }}][FreeWinMax]" 
                                                                    value="{{ isset($config[$level]['FreeWinMax']) ? $config[$level]['FreeWinMax'] / 100 : 0 }}">
                                                            </div>
                                                            <div class="col-md-4 form-group">
                                                                <label>充值控制额 (RechargeControl)</label>
                                                                <input type="number" class="form-control rechargeControl-input" 
                                                                    step="0.01"
                                                                    name="level[{{ $level }}][RechargeControl]" 
                                                                    value="{{ isset($config[$level]['RechargeControl']) ? $config[$level]['RechargeControl'] / 100 : 0 }}">
                                                            </div>
                                                            <div class="col-md-4 form-group">
                                                                <label>充值最大百分比 (RechargeMaxPercent)</label>
                                                                <input type="number" class="form-control" 
                                                                    name="level[{{ $level }}][RechargeMaxPercent]" 
                                                                    value="{{ $config[$level]['RechargeMaxPercent'] ?? 0 }}">
                                                            </div>
                                                        </div>
                                                    </div>
                                                </div>
                                                @endforeach
                                            </div>
                                        </div>
                                    </td>
                                    <td>
                                        <button class="btn btn-primary btn-sm save-config" data-game-id="{{ $game['gameId'] }}">保存</button>
                                        <span class="save-status ml-2"></span>
                                        <button class="btn btn-warning btn-sm copy-config ml-3" data-game-id="{{ $game['gameId'] }}">复制到所有游戏</button>
                                        <span class="copy-status ml-2"></span>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function() {
    // 添加按钮点击调试信息
    console.log('JS加载完成');
    
    $('.save-config').click(function() {
        console.log('保存按钮被点击');
        const gameId = $(this).data('game-id');
        console.log('游戏ID:', gameId);
        const configForm = $(this).closest('tr').find('.config-form');
        const saveBtn = $(this);
        const saveStatus = $(this).siblings('.save-status');
        
        // 显示保存中状态
        saveBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 保存中...');
        saveStatus.html('').removeClass('text-success text-danger');
        
        // 构建配置对象
        let configObj = {
            "1": {"FreeWinMax": 0, "RechargeControl": 0, "RechargeMaxPercent": 0},
            "2": {"FreeWinMax": 0, "RechargeControl": 0, "RechargeMaxPercent": 0},
            "3": {"FreeWinMax": 0, "RechargeControl": 0, "RechargeMaxPercent": 0}
        };
        
        // 收集表单数据
        configForm.find('input').each(function() {
            const name = $(this).attr('name');
            let value = 0;
            
            // 根据字段类型处理不同的转换逻辑
            if ($(this).hasClass('freeWinMax-input') || $(this).hasClass('rechargeControl-input')) {
                // 乘以100保存
                value = Math.round(parseFloat($(this).val() || 0) * 100);
            } else {
                value = parseInt($(this).val()) || 0;
            }
            
            // 解析name属性 level[1][FreeWinMax] 格式
            const matches = name.match(/level\[(\d+)\]\[([^\]]+)\]/);
            if (matches) {
                const level = matches[1];
                const field = matches[2];
                configObj[level][field] = value;
            }
        });
        
        // 转换成JSON
        const config = JSON.stringify(configObj);
        console.log('准备提交的配置:', config);
        
        // 确保CSRF令牌存在
        const token = $('meta[name="csrf-token"]').attr('content');
        console.log('CSRF令牌:', token ? '存在' : '不存在');
        
        // 阻止可能的默认行为
        event.preventDefault();
        
        $.ajax({
            url: "{{ url('/admin/pg-game-config/update') }}",
            method: 'POST',
            data: {
                gameId: gameId,
                config: config,
                _token: "{{ csrf_token() }}"
            },
            success: function(response) {
                console.log('成功响应:', response);
                
                // 恢复按钮状态
                saveBtn.prop('disabled', false).text('保存');
                
                if (response.status === 'success') {
                    // 显示成功提示
                    saveStatus.html('<i class="fa fa-check-circle"></i> 更新成功').addClass('text-success');
                    
                    // 使用toastr提示
                    if (typeof toastr !== 'undefined') {
                        toastr.success('配置更新成功');
                    } else {
                        // 备用提示方式
                        alert('配置更新成功');
                    }
                } else {
                    // 显示错误提示
                    saveStatus.html('<i class="fa fa-times-circle"></i> ' + (response.message || '更新失败')).addClass('text-danger');
                    
                    // 使用toastr提示
                    if (typeof toastr !== 'undefined') {
                        toastr.error(response.message || '更新失败');
                    } else {
                        // 备用提示方式
                        alert('更新失败: ' + (response.message || '未知错误'));
                    }
                }
                
                // 3秒后清除状态提示
                setTimeout(function() {
                    saveStatus.fadeOut(function() {
                        $(this).html('').show().removeClass('text-success text-danger');
                    });
                }, 3000);
            },
            error: function(xhr, status, error) {
                console.error('错误:', xhr.responseText);
                
                // 恢复按钮状态
                saveBtn.prop('disabled', false).text('保存');
                saveStatus.html('<i class="fa fa-times-circle"></i> 系统错误').addClass('text-danger');
                
                // 使用toastr提示
                if (typeof toastr !== 'undefined') {
                    toastr.error('系统错误，请稍后重试');
                } else {
                    // 备用提示方式
                    alert('系统错误，请稍后重试');
                }
                
                // 3秒后清除状态提示
                setTimeout(function() {
                    saveStatus.fadeOut(function() {
                        $(this).html('').show().removeClass('text-success text-danger');
                    });
                }, 3000);
            }
        });
    });

    // 复制到所有游戏
    $('.copy-config').click(function() {
        const gameId = $(this).data('game-id');
        const configForm = $(this).closest('tr').find('.config-form');
        const copyBtn = $(this);
        const copyStatus = $(this).siblings('.copy-status');

        if (!confirm('确定将该游戏当前参数复制到所有PG游戏？（不包含本游戏）')) {
            return;
        }

        // 显示复制中状态
        copyBtn.prop('disabled', true).html('<i class="fa fa-spinner fa-spin"></i> 复制中...');
        copyStatus.html('').removeClass('text-success text-danger');

        // 构建配置对象（与保存逻辑一致）
        let configObj = {
            "1": {"FreeWinMax": 0, "RechargeControl": 0, "RechargeMaxPercent": 0},
            "2": {"FreeWinMax": 0, "RechargeControl": 0, "RechargeMaxPercent": 0},
            "3": {"FreeWinMax": 0, "RechargeControl": 0, "RechargeMaxPercent": 0}
        };
        configForm.find('input').each(function() {
            const name = $(this).attr('name');
            let value = 0;
            if ($(this).hasClass('freeWinMax-input') || $(this).hasClass('rechargeControl-input')) {
                value = Math.round(parseFloat($(this).val() || 0) * 100);
            } else {
                value = parseInt($(this).val()) || 0;
            }
            const matches = name.match(/level\[(\d+)\]\[([^\]]+)\]/);
            if (matches) {
                const level = matches[1];
                const field = matches[2];
                configObj[level][field] = value;
            }
        });
        const config = JSON.stringify(configObj);

        $.ajax({
            url: "{{ url('/admin/pg-game-config/copy_all') }}",
            method: 'POST',
            data: {
                gameId: gameId,
                config: config,
                _token: "{{ csrf_token() }}"
            },
            success: function(response) {
                copyBtn.prop('disabled', false).text('复制到所有游戏');
                if (response.status === 'success') {
                    copyStatus.html('<i class="fa fa-check-circle"></i> 已复制到其他游戏（' + (response.affected || 0) + ' 个）').addClass('text-success');
                    if (typeof toastr !== 'undefined') toastr.success('复制成功');
                } else {
                    copyStatus.html('<i class="fa fa-times-circle"></i> ' + (response.message || '复制失败')).addClass('text-danger');
                    if (typeof toastr !== 'undefined') toastr.error(response.message || '复制失败');
                }
                setTimeout(function() {
                    copyStatus.fadeOut(function() {
                        $(this).html('').show().removeClass('text-success text-danger');
                    });
                }, 3000);
            },
            error: function(xhr) {
                copyBtn.prop('disabled', false).text('复制到所有游戏');
                copyStatus.html('<i class="fa fa-times-circle"></i> 系统错误').addClass('text-danger');
                if (typeof toastr !== 'undefined') toastr.error('系统错误，请稍后重试');
                setTimeout(function() {
                    copyStatus.fadeOut(function() {
                        $(this).html('').show().removeClass('text-success text-danger');
                    });
                }, 3000);
            }
        });
    });
});
</script>

<style>
.config-editor {
    position: relative;
}
</style>
@endsection 