{{:ModuleInclude('public/header')}}

<style>
    .page-title {
        font-size: 18px;
        font-weight: 600;
        color: #1a1a2e;
        padding: 24px 0 16px 0;
        border-bottom: 2px solid #e8e8e8;
        margin-bottom: 20px;
    }
</style>

<div class="right-content">
    <div class="page-title">
        <i class="am-icon-qrcode am-margin-right-sm"></i>票码核销
    </div>

    <!-- 统计栏 -->
    <div class="am-g am-margin-top-sm">
        <div class="am-u-sm-4">
            <div class="am-panel am-panel-success am-radius">
                <div class="am-panel-hd am-text-center">今日核销</div>
                <div class="am-panel-bd am-text-center am-text-lg" id="stat-today">-</div>
            </div>
        </div>
        <div class="am-u-sm-4">
            <div class="am-panel am-panel-warning am-radius">
                <div class="am-panel-hd am-text-center">待核销</div>
                <div class="am-panel-bd am-text-center am-text-lg" id="stat-pending">-</div>
            </div>
        </div>
        <div class="am-u-sm-4">
            <div class="am-panel am-panel-primary am-radius">
                <div class="am-panel-hd am-text-center">已核销总数</div>
                <div class="am-panel-bd am-text-center am-text-lg" id="stat-verified">-</div>
            </div>
        </div>
    </div>

    <!-- 核销操作区 -->
    <div class="am-panel am-panel-default am-radius am-margin-top">
        <div class="am-panel-hd">扫码/输入核销</div>
        <div class="am-panel-bd">
            <form class="am-form form-validation" id="verify-form"
                action="{{:PluginsAdminUrl('vr_ticket', 'admin', 'TicketVerify')}}" method="POST"
                request-type="ajax-url" request-value="{{:PluginsAdminUrl('vr_ticket', 'admin', 'TicketVerify')}}">
                <div class="am-form-group">
                    <label>票码/短码</label>
                    <div class="am-input-group">
                        <input type="text" name="ticket_code" placeholder="请输入票码或扫描二维码" class="am-radius" required />
                        <span class="am-input-group-btn">
                            <button type="button" class="am-btn am-btn-default am-radius" id="scan-btn">
                                <i class="am-icon-camera"></i> 扫码
                            </button>
                        </span>
                    </div>
                    <div class="am-alert am-alert-secondary am-margin-top-xs am-text-xs">
                        支持手动输入票码或点击"扫码"使用摄像头扫描二维码
                    </div>
                </div>

                <div class="am-form-group">
                    <button type="submit" class="am-btn am-btn-primary am-radius">
                        <i class="am-icon-check"></i> 确认核销
                    </button>
                </div>
            </form>
        </div>
    </div>

    <!-- 结果展示区 -->
    <div id="result-container"></div>

    <!-- 摄像头扫码弹窗 -->
    <div class="am-modal am-modal-prompt" id="scan-modal">
        <div class="am-modal-dialog">
            <div class="am-modal-hd">
                扫码核销
                <a href="javascript: void(0)" class="am-modal-close am-close">&times;</a>
            </div>
            <div class="am-modal-bd">
                <video id="scan-video" style="width: 100%; max-width: 400px; display: none;" autoplay></video>
                <canvas id="scan-canvas" style="display: none;"></canvas>
                <div id="scan-status" class="am-text-center am-padding-top">点击"开始扫码"启动摄像头</div>
                <div class="am-margin-top">
                    <button type="button" class="am-btn am-btn-primary am-radius" id="start-scan-btn">
                        <i class="am-icon-video-camera"></i> 开始扫码
                    </button>
                    <button type="button" class="am-btn am-btn-default am-radius" id="stop-scan-btn"
                        style="display: none;">
                        <i class="am-icon-stop"></i> 停止
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="{{$public_host}}static/common/lib/JsBarcode/JsBarcode.all.min.js"></script>
<script>
    // 页面加载时获取统计
    $(function () {
        loadStats();
    });

    // 获取统计数据
    function loadStats() {
        $.ajax({
            url: '{{:PluginsAdminUrl('vr_ticket', 'admin', 'TicketStats')}}',
            type: 'POST',
            dataType: 'json',
            success: function (res) {
                if (res.code === 0 && res.data) {
                    $('#stat-today').text(res.data.today || 0);
                    $('#stat-pending').text(res.data.pending || 0);
                    $('#stat-verified').text(res.data.verified || 0);
                }
            }
        });
    }

    // ShopXO submit-ajax 成功回调：展示核销结果
    $(document).on('submit-success.form-validation', '#verify-form', function (e, res) {
        var html = '';

        if (res.code === 0) {
            var ticket = res.data || {};
            html = '<div class="am-alert am-alert-success am-margin-top am-radius">' +
                '<h4><i class="am-icon-check-circle"></i> 核销成功</h4>' +
                '<p><strong>观演人：</strong>' + (ticket.real_name || '—') + '</p>' +
                '<p><strong>座位：</strong>' + (ticket.seat_info || '无') + '</p>' +
                '<p><strong>商品名：</strong>' + (ticket.goods_name || '—') + '</p>' +
                '</div>';

            // 清空输入框
            $('input[name="ticket_code"]').val('');

            // 刷新统计
            loadStats();
        } else {
            html = '<div class="am-alert am-alert-danger am-margin-top am-radius">' +
                '<h4><i class="am-icon-times-circle"></i> 核销失败</h4>' +
                '<p>' + res.msg + '</p>' +
                '</div>';
        }

        $('#result-container').html(html);
    });

    // 扫码功能
    var video = document.getElementById('scan-video');
    var canvas = document.getElementById('scan-canvas');
    var stream = null;

    $('#scan-btn').on('click', function () {
        $('#scan-modal').modal('open');
    });

    $('#start-scan-btn').on('click', function () {
        startScan();
    });

    $('#stop-scan-btn').on('click', function () {
        stopScan();
    });

    function startScan() {
        navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } })
            .then(function (s) {
                stream = s;
                video.srcObject = stream;
                video.style.display = 'block';
                $('#start-scan-btn').hide();
                $('#stop-scan-btn').show();
                $('#scan-status').text('正在扫描...');

                // 开始扫描循环
                scanFrame();
            })
            .catch(function (err) {
                $('#scan-status').text('摄像头访问失败: ' + err.message);
            });
    }

    function stopScan() {
        if (stream) {
            stream.getTracks().forEach(function (track) {
                track.stop();
            });
            stream = null;
        }
        video.style.display = 'none';
        $('#start-scan-btn').show();
        $('#stop-scan-btn').hide();
        $('#scan-status').text('点击"开始扫码"启动摄像头');
    }

    function scanFrame() {
        if (!stream) return;

        if (video.readyState === video.HAVE_ENOUGH_DATA) {
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            var ctx = canvas.getContext('2d');
            ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

            // 简单模拟：直接将扫描内容填入输入框（实际需要用 jsQR 等库解析）
            // 这里暂时不支持二维码解析，仅展示摄像头功能
        }

        requestAnimationFrame(scanFrame);
    }

    // 弹窗关闭时停止摄像头
    $('#scan-modal').on('closed.modal', function () {
        stopScan();
    });
</script>

{{:ModuleInclude('public/footer')}}