<?php echo ModuleInclude('public/header'); ?>

<style>
/* VR票务 - 票务商品详情页 */
/* 完全独立于 ShopXO 标准商品页，不加载 goods-detail 相关 CSS */

/* 页面布局 */
.vr-ticket-page { max-width: 1200px; margin: 0 auto; padding: 20px; }
.vr-ticket-header { margin-bottom: 20px; }
.vr-event-title { font-size: 24px; font-weight: bold; color: #333; margin-bottom: 8px; }
.vr-event-subtitle { color: #666; font-size: 14px; }

/* 座位图区域 */
.vr-seat-section { margin-bottom: 30px; }
.vr-section-title { font-size: 18px; font-weight: bold; margin-bottom: 15px; color: #333; }

/* 座位图 */
.vr-seat-map-wrapper { background: #f8f9fa; border-radius: 8px; padding: 20px; margin-bottom: 20px; overflow-x: auto; }
.vr-stage {
    text-align: center;
    background: linear-gradient(180deg, #e8e8e8, #d0d0d0);
    border-radius: 50% 50% 0 0 / 20px 20px 0 0;
    padding: 15px 40px;
    margin: 0 auto 25px;
    max-width: 600px;
    color: #666;
    font-size: 13px;
    letter-spacing: 2px;
}
.vr-seat-rows { display: flex; flex-direction: column; align-items: center; gap: 4px; }
.vr-seat-row { display: flex; align-items: center; gap: 2px; }
.vr-row-label { width: 24px; text-align: center; color: #999; font-size: 12px; flex-shrink: 0; }

/* 座位格子 */
.vr-seat {
    width: 28px;
    height: 28px;
    border-radius: 4px;
    margin: 1px;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 9px;
    color: #fff;
    transition: all 0.15s;
    flex-shrink: 0;
    position: relative;
}
.vr-seat:hover { transform: scale(1.15); z-index: 1; box-shadow: 0 2px 8px rgba(0,0,0,0.3); }
.vr-seat.selected { border: 2px solid #333; transform: scale(1.1); }
.vr-seat.sold { background: #ccc !important; cursor: not-allowed; opacity: 0.5; }
.vr-seat.sold:hover { transform: none; box-shadow: none; }
.vr-seat.aisle { background: transparent !important; cursor: default; }
.vr-seat.space { background: transparent !important; cursor: default; }

/* 座位类型图例 */
.vr-legend { display: flex; gap: 15px; flex-wrap: wrap; margin-bottom: 15px; justify-content: center; }
.vr-legend-item { display: flex; align-items: center; gap: 6px; font-size: 13px; color: #666; }
.vr-legend-seat { width: 20px; height: 20px; border-radius: 3px; }

/* 已选座位 */
.vr-selected-seats { background: #fff; border: 1px solid #e8e8e8; border-radius: 8px; padding: 15px; margin-bottom: 20px; }
.vr-selected-title { font-weight: bold; margin-bottom: 10px; color: #333; }
.vr-selected-list { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 10px; min-height: 30px; }
.vr-selected-item {
    display: inline-flex; align-items: center; gap: 6px;
    background: #e8f4ff; border: 1px solid #b8d4f0;
    border-radius: 4px; padding: 4px 10px; font-size: 13px;
}
.vr-selected-item .remove { color: #f56c6c; cursor: pointer; font-size: 16px; line-height: 1; }
.vr-total { font-size: 16px; font-weight: bold; color: #333; margin-top: 10px; }

/* 场次选择 */
.vr-sessions { margin-bottom: 20px; }
.vr-session-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 10px; }
.vr-session-item {
    border: 1px solid #ddd; border-radius: 6px; padding: 10px;
    cursor: pointer; text-align: center;
    transition: all 0.15s;
}
.vr-session-item:hover { border-color: #409eff; }
.vr-session-item.selected { border-color: #409eff; background: #ecf5ff; }
.vr-session-item .date { font-size: 14px; font-weight: bold; color: #333; }
.vr-session-item .time { font-size: 13px; color: #666; margin-top: 4px; }
.vr-session-item .price { font-size: 14px; color: #f56c6c; font-weight: bold; margin-top: 6px; }

/* 观演人表单 */
.vr-attendee-form { background: #fff; border: 1px solid #e8e8e8; border-radius: 8px; padding: 20px; margin-bottom: 20px; }
.vr-form-title { font-weight: bold; margin-bottom: 15px; color: #333; }
.vr-attendee-item { background: #f8f9fa; border-radius: 6px; padding: 15px; margin-bottom: 10px; }
.vr-attendee-label { font-size: 13px; color: #666; margin-bottom: 5px; }
.vr-attendee-input { width: 100%; padding: 8px 12px; border: 1px solid #ddd; border-radius: 4px; font-size: 14px; }

/* 购买栏 */
.vr-purchase-bar {
    position: fixed; bottom: 0; left: 0; right: 0;
    background: #fff; border-top: 1px solid #e8e8e8;
    padding: 12px 20px; z-index: 100;
    display: flex; align-items: center; justify-content: space-between;
    box-shadow: 0 -2px 10px rgba(0,0,0,0.08);
}
.vr-purchase-info { font-size: 14px; color: #666; }
.vr-purchase-info strong { font-size: 20px; color: #f56c6c; }
.vr-purchase-btn {
    background: linear-gradient(135deg, #409eff, #3b8ef8);
    color: #fff; border: none; border-radius: 20px;
    padding: 12px 36px; font-size: 16px; font-weight: bold;
    cursor: pointer; transition: all 0.2s;
}
.vr-purchase-btn:hover { transform: scale(1.03); box-shadow: 0 4px 12px rgba(64,158,255,0.4); }
.vr-purchase-btn:disabled { background: #ccc; cursor: not-allowed; transform: none; box-shadow: none; }

/* 商品信息侧边 */
.vr-goods-info { background: #fff; border: 1px solid #e8e8e8; border-radius: 8px; padding: 15px; margin-bottom: 20px; }
.vr-goods-photos { display: grid; grid-template-columns: repeat(auto-fill, minmax(100px, 1fr)); gap: 8px; margin-bottom: 15px; }
.vr-goods-photos img { width: 100%; aspect-ratio: 1; object-fit: cover; border-radius: 4px; }
</style>

<!-- 页面内容 -->
<div class="vr-ticket-page" id="vrTicketApp">
    <!-- 商品头部 -->
    <div class="vr-ticket-header">
        <div class="vr-event-title"><?php echo htmlspecialchars($goods['title'] ?? 'VR演唱会', ENT_QUOTES, 'UTF-8'); ?></div>
        <div class="vr-event-subtitle"><?php echo htmlspecialchars($goods['simple_desc'] ?? '', ENT_QUOTES, 'UTF-8'); ?></div>
    </div>

    <!-- 场次选择 -->
    <div class="vr-seat-section" id="sessionSection">
        <div class="vr-section-title">选择场次</div>
        <div class="vr-session-grid" id="sessionGrid">
            <!-- 由 JS 动态渲染 -->
            <div class="vr-no-session-tip">该商品暂无场次信息</div>
        </div>
    </div>

    <!-- 座位图 -->
    <div class="vr-seat-section" id="seatSection" style="display:none">
        <div class="vr-section-title">选择座位 <span style="font-size:13px;color:#999;font-weight:normal">（点击空座选中，再点击取消）</span></div>
        <div class="vr-legend" id="seatLegend"></div>
        <div class="vr-seat-map-wrapper">
            <div class="vr-stage">舞 台</div>
            <div class="vr-seat-rows" id="seatRows"></div>
        </div>
    </div>

    <!-- 已选座位 -->
    <div class="vr-selected-seats" id="selectedSection" style="display:none">
        <div class="vr-selected-title">已选座位 <span id="selectedCount">(0)</span></div>
        <div class="vr-selected-list" id="selectedList"></div>
        <div class="vr-total">合计：<strong id="totalPrice">¥0</strong></div>
    </div>

    <!-- 观演人信息 -->
    <div class="vr-attendee-form" id="attendeeSection" style="display:none">
        <div class="vr-form-title">观演人信息 <span style="font-size:12px;color:#999">(每张票需填写一位)</span></div>
        <div id="attendeeList"></div>
    </div>

    <!-- 商品详情（保留） -->
    <?php if (!empty($goods['content'])): ?>
    <div class="vr-seat-section">
        <div class="vr-section-title">演出详情</div>
        <div class="goods-detail-content"><?php echo $goods['content']; ?></div>
    </div>
    <?php endif; ?>

    <!-- 购买栏 -->
    <div class="vr-purchase-bar">
        <div class="vr-purchase-info">
            已选 <strong id="barCount">0</strong> 座
            合计 <strong id="barPrice">¥0</strong>
        </div>
        <button class="vr-purchase-btn" id="purchaseBtn" disabled onclick="vrTicketApp.submit()">
            提交订单
        </button>
    </div>
</div>

<?php echo ModuleInclude('public/footer'); ?>

<script>
(function() {
    var app = {
        goodsId: <?php echo intval($goods['id'] ?? 0); ?>,
        seatMap: <?php echo json_encode($vr_seat_template['seat_map'] ?? []); ?>,
        specBaseIdMap: <?php echo json_encode($vr_seat_template['spec_base_id_map'] ?? []); ?>,
        selectedSeats: [],      // [{row, col, char, price, label, classes}]
        soldSeats: {},          // {row_col: true}
        currentSession: null,
        sessionSpecId: null,
        requestUrl: '<?php echo Config("shopxo.host_url"); ?>',
        userId: <?php echo IsMobileLogin(); ?>,

        init: function() {
            this.renderSessions();
            this.bindEvents();
            this.loadSoldSeats();
        },

        // 渲染场次列表（基于 ShopXO spec 数据）
        renderSessions: function() {
            var specData = <?php echo json_encode($goods_spec_data ?? []); ?> || [];
            var html = '';
            if (specData.length > 0) {
                specData.forEach(function(spec) {
                    html += '<div class="vr-session-item" data-spec-id="'+spec.spec_id+'" data-spec-base-id="'+spec.spec_id+'" onclick="vrTicketApp.selectSession(this)">' +
                        '<div class="date">'+spec.spec_name+'</div>' +
                        '<div class="price">¥'+spec.price+'</div></div>';
                });
                document.getElementById('sessionGrid').innerHTML = html;
            }
        },

        selectSession: function(el) {
            // 移除其他选中
            document.querySelectorAll('.vr-session-item').forEach(function(item) {
                item.classList.remove('selected');
            });
            el.classList.add('selected');
            this.currentSession = el.dataset.specId;
            this.sessionSpecId = el.dataset.specBaseId;

            // 显示座位图
            document.getElementById('seatSection').style.display = 'block';
            document.getElementById('attendeeSection').style.display = 'block';

            this.renderSeatMap();
            this.loadSoldSeats();
        },

        renderSeatMap: function() {
            var map = this.seatMap;
            if (!map || !map.map || map.map.length === 0) {
                document.getElementById('seatRows').innerHTML = '<div style="text-align:center;color:#999;padding:40px">座位图加载失败</div>';
                return;
            }

            // 渲染图例
            var legendHtml = '';
            var sections = map.sections || [];
            var seats = map.seats || {};
            sections.forEach(function(sec) {
                var color = sec.color || '#409eff';
                legendHtml += '<div class="vr-legend-item"><div class="vr-legend-seat" style="background:'+color+'"></div>'+sec.name+'</div>';
            });
            legendHtml += '<div class="vr-legend-item"><div class="vr-legend-seat" style="background:#ccc"></div>已售</div>';
            document.getElementById('seatLegend').innerHTML = legendHtml;

            // 渲染座位图
            var rowsContainer = document.getElementById('seatRows');
            var row_labels = map.row_labels || [];
            var rowsHtml = '';

            map.map.forEach(function(rowStr, rowIndex) {
                var rowLabel = row_labels[rowIndex] || String.fromCharCode(65 + rowIndex);
                rowsHtml += '<div class="vr-seat-row">';
                rowsHtml += '<div class="vr-row-label">'+rowLabel+'</div>';

                var chars = rowStr.split('');
                chars.forEach(function(char, colIndex) {
                    if (char === '_' || char === '-') {
                        rowsHtml += '<div class="vr-seat space" style="width:28px;height:28px"></div>';
                    } else {
                        var seatInfo = seats[char] || {};
                        var color = seatInfo.color || '#409eff';
                        var price = seatInfo.price || 0;
                        var label = seatInfo.label || '';

                        rowsHtml += '<div class="vr-seat '+(seatInfo.classes||'')+'" '+
                            'style="background:'+color+'" '+
                            'data-row="'+rowIndex+'" data-col="'+colIndex+'" '+
                            'data-row-label="'+rowLabel+'" data-col-num="'+(colIndex+1)+'" '+
                            'data-char="'+char+'" data-price="'+price+'" '+
                            'data-seat-id="'+char+'" data-label="'+rowLabel+(colIndex+1)+'排'+(colIndex+1)+'座" '+
                            'onclick="vrTicketApp.toggleSeat(this)"></div>';
                    }
                });
                rowsHtml += '</div>';
            });

            rowsContainer.innerHTML = rowsHtml;
        },

        toggleSeat: function(el) {
            if (el.classList.contains('sold')) return;

            var row = el.dataset.row;
            var col = el.dataset.col;
            var rowLabel = el.dataset.rowLabel;
            var colNum = el.dataset.colNum;
            var seatKey = rowLabel + '_' + colNum;  // e.g. "A_1" — matches specBaseIdMap key format
            var seat = {
                row: parseInt(row),
                col: parseInt(col),
                rowLabel: rowLabel,
                colNum: parseInt(colNum),
                seatKey: seatKey,               // 用于 specBaseIdMap 查找
                char: el.dataset.char,
                price: parseFloat(el.dataset.price),
                label: el.dataset.label,
                seatId: el.dataset.seatId,
            };

            if (el.classList.contains('selected')) {
                // 取消选中
                el.classList.remove('selected');
                this.selectedSeats = this.selectedSeats.filter(function(s) {
                    return s.seatKey !== seatKey;
                });
            } else {
                // 选中
                el.classList.add('selected');
                this.selectedSeats.push(seat);
            }

            this.updateSelectedUI();
        },

        updateSelectedUI: function() {
            var count = this.selectedSeats.length;
            var total = this.selectedSeats.reduce(function(sum, s) { return sum + s.price; }, 0);

            document.getElementById('selectedCount').textContent = '(' + count + ')';
            document.getElementById('totalPrice').textContent = '¥' + total.toFixed(2);
            document.getElementById('barCount').textContent = count;
            document.getElementById('barPrice').textContent = '¥' + total.toFixed(2);

            // 渲染已选列表
            var listHtml = '';
            this.selectedSeats.forEach(function(seat, i) {
                listHtml += '<div class="vr-selected-item">' +
                    seat.label + ' ¥' + seat.price +
                    '<span class="remove" onclick="vrTicketApp.removeSeat('+i+')">×</span></div>';
            });
            document.getElementById('selectedList').innerHTML = listHtml;

            // 渲染观演人表单
            this.renderAttendeeForms();

            // 更新按钮状态
            document.getElementById('purchaseBtn').disabled = count === 0;
        },

        removeSeat: function(index) {
            var seat = this.selectedSeats[index];
            if (seat) {
                var el = document.querySelector(
                    '[data-row-label="'+seat.rowLabel+'"][data-col-num="'+seat.colNum+'"]'
                );
                if (el) el.classList.remove('selected');
                this.selectedSeats.splice(index, 1);
                this.updateSelectedUI();
            }
        },

        renderAttendeeForms: function() {
            var html = '';
            this.selectedSeats.forEach(function(seat, i) {
                html += '<div class="vr-attendee-item">' +
                    '<div class="vr-attendee-label">第 '+(i+1)+' 张票 - '+seat.label+'</div>' +
                    '<div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">' +
                        '<input type="text" class="vr-attendee-input" placeholder="真实姓名 *" data-field="real_name" data-index="'+i+'" required>' +
                        '<input type="tel" class="vr-attendee-input" placeholder="手机号 *" data-field="phone" data-index="'+i+'" required>' +
                    '</div>' +
                    '<div style="margin-top:8px">' +
                        '<input type="text" class="vr-attendee-input" placeholder="身份证号（选填）" data-field="id_card" data-index="'+i+'">' +
                    '</div>' +
                    '<input type="hidden" class="vr-attendee-input" value="'+seat.label+'" data-field="seat_info" data-index="'+i+'">' +
                '</div>';
            });
            document.getElementById('attendeeList').innerHTML = html;
        },

        loadSoldSeats: function() {
            // TODO: 从后端加载已售座位
            // $.get(this.requestUrl + '?s=plugins/vr_ticket/index/sold_seats', {
            //     goods_id: this.goodsId,
            //     spec_base_id: this.sessionSpecId
            // }, function(res) {
            //     // 标记已售座位
            // });
        },

        bindEvents: function() {
            // 空实现，后续扩展
        },

        submit: function() {
            if (this.selectedSeats.length === 0) {
                alert('请先选择座位');
                return;
            }
            if (!this.userId) {
                alert('请先登录');
                location.href = this.requestUrl + '?s=index/user/logininfo';
                return;
            }

            // 收集观演人信息（按座位顺序索引）
            var inputs = document.querySelectorAll('#attendeeList input');
            var attendeeData = {};
            inputs.forEach(function(input) {
                var idx = input.dataset.index;
                var field = input.dataset.field;
                if (!attendeeData[idx]) attendeeData[idx] = {};
                attendeeData[idx][field] = input.value;
            });

            // 【Plan A】每座一行 goods_params，逐座提交
            // spec_base_id 从 specBaseIdMap[seatKey] 获取；若未生成 SKU（Plan B 过渡期），降级用 sessionSpecId
            var self = this;
            var goodsParamsList = this.selectedSeats.map(function(seat, i) {
                // Plan A: 座位级 SKU（specBaseIdMap key 格式 = rowLabel_colNum，如 "A_1"）
                // Plan B 回退: sessionSpecId（Zone 级别 SKU）
                // PHP 返回格式: specBaseIdMap['A_1'] = 2001（整数），非对象
                var specBaseId = self.specBaseIdMap[seat.seatKey] || self.sessionSpecId;
                var seatAttendee = attendeeData[i] || {};
                return {
                    goods_id: self.goodsId,
                    spec_base_id: parseInt(specBaseId) || 0,
                    stock: 1,
                    extension_data: JSON.stringify({
                        attendee: seatAttendee,
                        seat: {
                            row: seat.row,
                            col: seat.col,
                            rowLabel: seat.rowLabel,
                            colNum: seat.colNum,
                            seatKey: seat.seatKey,
                            label: seat.label,
                            price: seat.price
                        }
                    })
                };
            });

            var goodsParams = JSON.stringify(goodsParamsList);

            var checkoutUrl = this.requestUrl + '?s=index/buy/index' +
                '&goods_params=' + encodeURIComponent(goodsParams);
            location.href = checkoutUrl;
        }
    };

    window.vrTicketApp = app;
    app.init();
})();
</script>

<?php echo ModuleInclude('public/footer'); ?>
