@extends('base.base')
@section('base')
<div class="main-panel">
    <div class="content-wrapper">
        <div class="row">
            <div class="col-12 grid-margin stretch-card">
                <div class="card">
                    <div class="card-body">
                        <h4 class="card-title">个控回报配置</h4>
                        <p class="card-description">配置不同个控区间和倍率的权重调节</p>

                        <div class="row" style="margin-bottom: 20px;">
                            <!-- 游戏选择 -->
                            <div class="col-md-6 form-group">
                                <label for="game_select" style="font-weight: bold; margin-right: 10px;">选择游戏：</label>
                                <select id="game_select" class="form-control" style="width: 300px; display: inline-block;" onchange="switchGame(this.value)">
                                    @foreach($games as $id => $name)
                                        <option value="{{ $id }}" {{ $id == $gameId ? 'selected' : '' }}>
                                            {{ $name }} (GameID: {{ $id }})
                                        </option>
                                    @endforeach
                                </select>
                            </div>

                            <!-- 库存模式切换 -->
                            <div class="col-md-6 form-group">
                                <label style="font-weight: bold; margin-right: 10px;">库存模式：</label>
                                <div class="btn-group btn-group-toggle" data-toggle="buttons">
                                    <label class="btn btn-outline-primary {{ $stockMode == 1 ? 'active' : '' }}" onclick="switchStockMode(1)">
                                        <input type="radio" name="stock_mode" value="1" {{ $stockMode == 1 ? 'checked' : '' }}> 普通模式
                                    </label>
                                    <label class="btn btn-outline-success {{ $stockMode == 2 ? 'active' : '' }}" onclick="switchStockMode(2)">
                                        <input type="radio" name="stock_mode" value="2" {{ $stockMode == 2 ? 'checked' : '' }}> 库存模式
                                    </label>
                                </div>
                                <span style="margin-left: 15px; color: #666;">
                                    当前：<strong>{{ $stockMode == 2 ? '库存模式' : '普通模式' }}</strong>
                                </span>
                            </div>
                        </div>

<style>
    .table-wrapper {
        max-height: calc(100vh - 250px);
        overflow-y: auto;
        position: relative;
        border: 1px solid #ddd;
    }
    
    .config-table {
        width: 100%;
        border-collapse: collapse;
        margin: 0;
        background: #fff;
    }
    
    .config-table th,
    .config-table td {
        border: 1px solid #ddd;
        padding: 8px;
        text-align: center;
        font-size: 14px;
    }
    
    .config-table thead {
        position: sticky;
        top: 0;
        z-index: 100;
    }
    
    .config-table th {
        background-color: #4CAF50;
        color: white;
        font-weight: bold;
        position: sticky;
        top: 0;
        box-shadow: 0 2px 2px -1px rgba(0, 0, 0, 0.4);
    }
    
    .config-table tbody tr:nth-child(even) {
        background-color: #f9f9f9;
    }
    
    .config-table tbody tr:hover {
        background-color: #f0f0f0;
    }
    
    .config-table input[type="number"],
    .config-table input[type="text"] {
        width: 95%;
        padding: 5px;
        border: 1px solid transparent;
        border-radius: 3px;
        text-align: center;
        background: transparent;
        cursor: pointer;
    }
    
    .config-table input[type="number"]:focus,
    .config-table input[type="text"]:focus {
        border: 1px solid #4CAF50;
        background: #fff;
        outline: none;
        box-shadow: 0 0 5px rgba(76, 175, 80, 0.3);
    }
    
    .config-table input[type="number"]:read-only,
    .config-table input[type="text"]:read-only {
        cursor: pointer;
    }
    
    .config-table input[type="checkbox"] {
        width: 20px;
        height: 20px;
        cursor: pointer;
    }
    
    .editable-cell {
        cursor: pointer;
        position: relative;
    }
    
    .editable-cell:hover::after {
        content: '✎';
        position: absolute;
        right: 5px;
        top: 50%;
        transform: translateY(-50%);
        color: #4CAF50;
        font-size: 14px;
    }
    
    .group-header {
        background-color: #2196F3 !important;
        color: white !important;
        font-weight: bold;
        position: sticky;
        z-index: 50;
    }
    
    .field-label {
        color: #ccc;
        font-size: 11px;
    }
    
    /* 滚动条美化 */
    .table-wrapper::-webkit-scrollbar {
        width: 8px;
    }
    
    .table-wrapper::-webkit-scrollbar-track {
        background: #f1f1f1;
        border-radius: 4px;
    }
    
    .table-wrapper::-webkit-scrollbar-thumb {
        background: #888;
        border-radius: 4px;
    }
    
    .table-wrapper::-webkit-scrollbar-thumb:hover {
        background: #555;
    }
</style>

<form id="configForm">
    <div class="table-wrapper">
        <table class="config-table">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>个控最小值<br><span class="field-label">(ZMin)</span></th>
                    <th>个控最大值<br><span class="field-label">(ZMax)</span></th>
                    <th>倍率最小<br><span class="field-label">(MultiMin)</span></th>
                    <th>倍率最大<br><span class="field-label">(MultiMax)</span></th>
                    <th>权重<br><span class="field-label">(Weight)</span></th>
                    <th>个控调节<br><span class="field-label">(WeightAdjust)</span></th>
                </tr>
            </thead>
            <tbody>
            @if(count($configs) == 0)
                <tr>
                    <td colspan="7" style="text-align: center; padding: 40px; color: #999;">
                        <i class="mdi mdi-alert-circle" style="font-size: 48px;"></i>
                        <p style="margin-top: 10px; font-size: 16px;">该游戏暂无配置数据</p>
                    </td>
                </tr>
            @else
            @php
                $currentGroup = null;
            @endphp
            @foreach($configs as $config)
                @php
                    $groupKey = $config->ZMin . '-' . $config->ZMax;
                    $isNewGroup = ($groupKey !== $currentGroup);
                    $currentGroup = $groupKey;
                @endphp
                
                @if($isNewGroup)
                    <tr class="group-header">
                        <td colspan="7">个控区间：{{ $config->ZMin }} - {{ $config->ZMax }}</td>
                    </tr>
                @endif
                
                <tr>
                    <td>{{ $config->ConfigID }}</td>
                    <td>
                        <input type="number" 
                               name="configs[{{ $config->ConfigID }}][ZMin]" 
                               value="{{ $config->ZMin }}" 
                               min="0" 
                               step="1">
                    </td>
                    <td>
                        <input type="number" 
                               name="configs[{{ $config->ConfigID }}][ZMax]" 
                               value="{{ $config->ZMax }}" 
                               min="0" 
                               step="1">
                    </td>
                    <td>
                        <input type="number" 
                               name="configs[{{ $config->ConfigID }}][MultiMin]" 
                               value="{{ number_format($config->MultiMin, 2, '.', '') }}" 
                               min="0" 
                               step="0.01">
                    </td>
                    <td>
                        <input type="number" 
                               name="configs[{{ $config->ConfigID }}][MultiMax]" 
                               value="{{ number_format($config->MultiMax, 2, '.', '') }}" 
                               min="0" 
                               step="0.01">
                    </td>
                    <td>
                        <input type="number" 
                               name="configs[{{ $config->ConfigID }}][Weight]" 
                               value="{{ $config->Weight }}" 
                               min="0" 
                               step="1">
                    </td>
                    <td>
                        <input type="text" 
                               name="configs[{{ $config->ConfigID }}][WeightAdjust]" 
                               value="{{ $config->WeightAdjust }}" 
                               placeholder="如: 15000-300Z"
                               style="width: 120px;">
                    </td>
                </tr>
            @endforeach
            @endif
            </tbody>
        </table>
    </div>

    @if(count($configs) > 0)
    <div style="text-align: center; margin: 20px 0;">
        <button type="button" class="btn btn-primary btn-lg" onclick="saveConfig()">保存配置</button>
    </div>
    @endif
</form>

<script>
// 切换游戏
function switchGame(gameId) {
    // 检查是否有未保存的修改
    if (!checkUnsavedChanges('切换游戏')) {
        $('#game_select').val('{{ $gameId }}');
        return;
    }

    // 切换到选择的游戏，保持当前的库存模式
    const stockMode = {{ $stockMode }};
    window.location.href = '/admin/game-some-config?game_id=' + gameId + '&stock_mode=' + stockMode;
}

// 切换库存模式
function switchStockMode(mode) {
    // 检查是否有未保存的修改
    if (!checkUnsavedChanges('切换库存模式')) {
        return;
    }

    // 切换到选择的模式，保持当前的游戏选择
    const gameId = {{ $gameId }};
    window.location.href = '/admin/game-some-config?game_id=' + gameId + '&stock_mode=' + mode;
}

// 检查是否有未保存的修改
function checkUnsavedChanges(action) {
    let hasUnsavedChanges = false;
    $('input[name^="configs"]').each(function() {
        const name = $(this).attr('name');
        const currentValue = $(this).val();
        if (originalData[name] && originalData[name] !== currentValue) {
            hasUnsavedChanges = true;
            return false; // break
        }
    });

    if (hasUnsavedChanges) {
        return confirm('有未保存的修改，确定要' + action + '吗？');
    }
    return true;
}

// 保存原始数据
const originalData = {};

$(document).ready(function() {
    // 记录所有字段的原始值
    $('input[name^="configs"]').each(function() {
        const name = $(this).attr('name');
        if ($(this).attr('type') === 'checkbox') {
            originalData[name] = $(this).prop('checked');
        } else {
            originalData[name] = $(this).val();
            // 设置为只读，点击后才能编辑
            $(this).attr('readonly', true);
        }
    });
    
    // 点击input时移除只读，进入编辑模式
    $('input[type="number"], input[type="text"]').on('click', function() {
        $(this).attr('readonly', false);
        $(this).select();  // 选中内容，方便修改
    });
    
    // 失去焦点时恢复只读
    $('input[type="number"], input[type="text"]').on('blur', function() {
        $(this).attr('readonly', true);
    });
});

function saveConfig() {
    // 收集有变动的数据
    const changedData = {};
    let hasChanges = false;
    
    $('input[name^="configs"]').each(function() {
        const name = $(this).attr('name');
        let currentValue;
        
        if ($(this).attr('type') === 'checkbox') {
            currentValue = $(this).prop('checked');
        } else {
            currentValue = $(this).val();
        }
        
        // 只添加有变动的字段
        if (originalData[name] !== currentValue) {
            changedData[name] = currentValue;
            hasChanges = true;
        }
    });
    
    if (!hasChanges) {
        layer.msg('没有数据被修改', {icon: 0});
        return;
    }
    
    // 构建只包含变动数据的表单
    const formData = $.param(changedData);
    
    layer.msg('正在保存 ' + Object.keys(changedData).length + ' 个变动...', {icon: 16, time: 0, shade: 0.3});
    
    $.ajax({
        url: '/admin/game-some-config/update',
        type: 'POST',
        data: formData,
        dataType: 'json',
        success: function(res) {
            layer.closeAll();
            if (res.code === 200) {
                layer.msg('配置更新成功！', {icon: 1});
                setTimeout(function() {
                    location.reload();
                }, 1000);
            } else {
                layer.msg('更新失败: ' + (res.msg || '未知错误'), {icon: 2});
            }
        },
        error: function(xhr) {
            layer.closeAll();
            layer.msg('请求失败: ' + xhr.statusText, {icon: 2});
        }
    });
}
</script>

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
