@extends('base.base')
@section('base')
<div class="main-panel">
    <div class="content-wrapper">
        <div class="page-header">
            <h3 class="page-title">
                <span class="page-title-icon bg-gradient-primary text-white mr-2">
                    <i class="mdi mdi-tumblr-reblog"></i>
                </span>
                圣诞大转盘配置
            </h3>
        </div>

        <div class="row">
            <div class="col-12 grid-margin stretch-card">
                <div class="card">
                    <div class="card-body">
                        <h4 class="card-title">活动配置</h4>
                        <form class="forms-sample" id="activity-form">
                            <div class="form-row">
                                <div class="form-group col-md-4">
                                    <label>活动开始时间</label>
                                    <input type="datetime-local" class="form-control" name="start_time"
                                           value="{{ !empty($activity['start_time']) ? \Carbon\Carbon::parse($activity['start_time'])->format('Y-m-d\TH:i') : '' }}">
                                </div>
                                <div class="form-group col-md-4">
                                    <label>活动结束时间</label>
                                    <input type="datetime-local" class="form-control" name="end_time"
                                           value="{{ !empty($activity['end_time']) ? \Carbon\Carbon::parse($activity['end_time'])->format('Y-m-d\TH:i') : '' }}">
                                </div>
                                <div class="form-group col-md-4">
                                    <label>活动状态</label>
                                    <select class="form-control" name="status">
                                        <option value="0" {{ ($activity['status'] ?? 0) == 0 ? 'selected' : '' }}>关闭</option>
                                        <option value="1" {{ ($activity['status'] ?? 0) == 1 ? 'selected' : '' }}>开启</option>
                                    </select>
                                </div>
                            </div>
                            {{-- 隐藏图片地址配置 --}}
                            <input type="hidden" name="icon_url" value="{{ $activity['icon_url'] ?? '' }}">
                            <input type="hidden" name="button_url" value="{{ $activity['button_url'] ?? '' }}">
                            <input type="hidden" name="button_light_url" value="{{ $activity['button_light_url'] ?? '' }}">
                            <input type="hidden" name="lunzi_url" value="{{ $activity['lunzi_url'] ?? '' }}">
                            <input type="hidden" name="dipan_url" value="{{ $activity['dipan_url'] ?? '' }}">
                            <div class="form-group">
                                <label>免费转盘次数</label>
                                <input type="number" step="1" min="0" class="form-control" name="free_times"
                                       placeholder="未充值用户可获得的免费转盘次数（0表示不赠送）"
                                       value="{{ $activity['free_times'] ?? 0 }}">
                                <small class="form-text text-muted">
                                    说明：配置免费次数后，未充值的用户首次访问转盘时会自动获得该次数。每个用户只能获得一次免费次数。
                                </small>
                            </div>
                            <div class="form-group">
                                <label>充值规则（充值金额 -> 次数）</label>
                                <table class="table table-bordered" id="rules-table">
                                    <thead>
                                    <tr>
                                        <th>充值金额 (amount)</th>
                                        <th>赠送次数 (times)</th>
                                        <th>操作</th>
                                    </tr>
                                    </thead>
                                    <tbody>
                                    @foreach($rules as $idx => $rule)
                                        <tr>
                                            <td>
                                                <input type="number" step="0.01" class="form-control"
                                                       name="rules[{{ $idx }}][amount]"
                                                       value="{{ $rule['amount'] }}">
                                            </td>
                                            <td>
                                                <input type="number" step="1" class="form-control"
                                                       name="rules[{{ $idx }}][times]"
                                                       value="{{ $rule['times'] }}">
                                            </td>
                                            <td>
                                                <button type="button" class="btn btn-sm btn-danger" onclick="removeRuleRow(this)">删除</button>
                                            </td>
                                        </tr>
                                    @endforeach
                                    </tbody>
                                </table>
                                <button type="button" class="btn btn-sm btn-gradient-info" onclick="addRuleRow()">添加规则</button>
                                <small class="form-text text-muted mt-2">
                                    说明：这里配置充值金额与对应增加的大转盘次数，例如 9.99 → 1 次。
                                </small>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="row mt-3">
            <div class="col-12 grid-margin stretch-card">
                <div class="card">
                    <div class="card-body">
                        <h4 class="card-title">9档转盘配置</h4>
                        <p class="card-description">slot_index 0-8，每档一个 reward（奖励值）、weight（权重）、sort_index（排序索引）</p>
                        <div class="table-responsive">
                            <table class="table table-bordered">
                                <thead>
                                <tr>
                                    <th>档位索引 (slot_index)</th>
                                    <th>奖励值 (reward)</th>
                                    <th>权重 (weight)</th>
                                    <th>排序索引 (sort_index)</th>
                                </tr>
                                </thead>
                                <tbody>
                                @foreach($slots as $slot)
                                    <tr>
                                        <td>
                                            <input type="text" class="form-control" value="{{ $slot['slot_index'] }}" disabled>
                                        </td>
                                        <td>
                                            <input type="number" step="any" class="form-control"
                                                   name="slots[{{ $slot['slot_index'] }}][reward]"
                                                   value="{{ $slot['reward'] }}">
                                        </td>
                                        <td>
                                            <input type="number" step="1" class="form-control"
                                                   name="slots[{{ $slot['slot_index'] }}][weight]"
                                                   value="{{ $slot['weight'] }}">
                                        </td>
                                        <td>
                                            <input type="number" step="1" class="form-control"
                                                   name="slots[{{ $slot['slot_index'] }}][sort_index]"
                                                   value="{{ $slot['sort_index'] }}">
                                        </td>
                                    </tr>
                                @endforeach
                                </tbody>
                            </table>
                        </div>

                        <button type="button" class="btn btn-sm btn-gradient-primary mt-3" onclick="saveConfig()">
                            <i class="mdi mdi-content-save"></i> 保存配置
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    function saveConfig() {
        var activityData = $("#activity-form").serializeArray();
        var data = {};
        activityData.forEach(function (item) {
            data[item.name] = item.value;
        });

        var slots = {};
        $("input[name^='slots']").each(function () {
            var name = $(this).attr('name'); // slots[0][reward]
            var match = name.match(/slots\[(\d+)]\[(\w+)]/);
            if (match) {
                var index = match[1];
                var field = match[2];
                if (!slots[index]) {
                    slots[index] = {};
                }
                slots[index][field] = $(this).val();
            }
        });

        data['slots'] = slots;

        // 处理充值规则
        var rules = {};
        $("input[name^='rules']").each(function () {
            var name = $(this).attr('name'); // rules[0][amount]
            var match = name.match(/rules\[(\d+)]\[(\w+)]/);
            if (match) {
                var index = match[1];
                var field = match[2];
                if (!rules[index]) {
                    rules[index] = {};
                }
                rules[index][field] = $(this).val();
            }
        });

        // 转成数组并过滤空行
        var rulesArr = [];
        Object.keys(rules).forEach(function (k) {
            var r = rules[k];
            var amount = parseFloat(r.amount || 0);
            var times = parseInt(r.times || 0);
            if (!isNaN(amount) && amount > 0 && !isNaN(times) && times > 0) {
                rulesArr.push({amount: amount, times: times});
            }
        });

        data['recharge_rules'] = JSON.stringify(rulesArr);

        myRequest('/admin/christmas-wheel/update', 'post', data, function (res) {
            layer.msg(res.msg || (res.code === '200' ? '保存成功' : '保存失败'));
            if (res.code === '200') {
                setTimeout(function () {
                    window.location.reload();
                }, 1500);
            }
        });
    }

    function addRuleRow() {
        var tbody = $("#rules-table tbody");
        var index = tbody.children("tr").length;
        var row = '<tr>' +
            '<td><input type="number" step="0.01" class="form-control" name="rules[' + index + '][amount]" value=""></td>' +
            '<td><input type="number" step="1" class="form-control" name="rules[' + index + '][times]" value=""></td>' +
            '<td><button type="button" class="btn btn-sm btn-danger" onclick="removeRuleRow(this)">删除</button></td>' +
            '</tr>';
        tbody.append(row);
    }

    function removeRuleRow(btn) {
        $(btn).closest('tr').remove();
    }
</script>
@endsection
