<template>
  <view class="ticket-popup" v-if="visible" @click="handleMaskClick" @touchmove.stop.prevent="stopMove">
    <view class="popup-inner" @click.stop>
      <!-- Popup Header: 服务说明 -->
      <view class="popup-header" v-if="type === 'service'">
        <text class="popup-title-text">服务说明</text>
        <text class="popup-close" @click="close">✕</text>
      </view>

      <!-- Popup Header: 所有场馆 -->
      <view class="popup-header" v-if="type === 'venue'">
        <text class="popup-title-text">所有场馆</text>
        <text class="popup-close" @click="close">✕</text>
      </view>

      <!-- Popup Header: 须知 (带tabs) -->
      <view class="popup-header has-tabs" v-if="type === 'notice'">
        <view class="popup-tabs">
          <text 
            class="tab-item" 
            :class="{ active: activeTab === 'buy' }" 
            @click="activeTab = 'buy'"
          >购票须知</text>
          <text 
            class="tab-item" 
            :class="{ active: activeTab === 'watch' }" 
            @click="activeTab = 'watch'"
          >观演须知</text>
        </view>
        <text class="popup-close" @click="close">✕</text>
      </view>

      <!-- Popup Header: 购票 -->
      <view class="popup-header" v-if="type === 'buy'">
        <text class="popup-title-text">选择场次/票档</text>
        <text class="popup-close" @click="close">✕</text>
      </view>

      <!-- Popup Content -->
      <scroll-view class="popup-content" scroll-y :scroll-top="0" :class="{ 'has-bottom-bar': type === 'buy' }">
        <!-- 服务说明 -->
        <template v-if="type === 'service'">
          <view class="service-item" v-for="(item, index) in services" :key="index">
            <view class="service-item-title">
              <text :class="item.status === 'success' ? 'icon-success' : 'icon-warning'">
                {{ item.status === 'success' ? '✔' : '!' }}
              </text> 
              {{ item.title }}
            </view>
            <view class="service-item-content">{{ item.desc }}</view>
          </view>
        </template>

        <!-- 须知 -->
        <template v-if="type === 'notice'">
          <view class="service-item" v-for="(item, index) in currentList" :key="index">
            <view class="service-item-title notice-pure-title">{{ item.title }}</view>
            <view class="service-item-content">{{ item.desc }}</view>
          </view>
        </template>

        <!-- 场馆列表 -->
        <template v-if="type === 'venue'">
          <view class="venue-item" v-for="(item, index) in venues" :key="index" @click="handleVenueClick(item)">
            <view class="venue-info">
              <view class="venue-row">
                <iconfont name="icon-location" color="#ff404f" size="20px" propStyle="margin-right: 6px;"></iconfont>
                <text class="venue-name">{{ item.name }}</text>
              </view>
              <text class="venue-address">{{ item.address }}</text>
            </view>
            <view class="venue-nav">
              <view class="nav-circle">
                <iconfont name="icon-map-navigator" color="#fff" size="32rpx"></iconfont>
              </view>
            </view>
          </view>
        </template>

        <!-- 购票选择器 -->
        <template v-if="type === 'buy'">
          <view class="buy-section" v-if="sessionList.length > 0">
            <view class="buy-section-title">场次</view>
            <view class="buy-options-grid">
              <view 
                class="buy-option-item" 
                v-for="item in sessionList" 
                :key="item.name"
                :class="{ active: selectedSession === item.name, disabled: !item.has_available, expired: item.is_expired }"
                @click="item.has_available && (selectedSession = item.name)"
              >
                <text class="option-name">{{ item.name }}</text>
                <text class="option-status" v-if="item.is_expired">已停售</text>
              </view>
            </view>
          </view>
          
          <view class="buy-section" v-if="venueList.length > 0">
            <view class="buy-section-title">场馆</view>
            <view class="buy-options-grid">
              <view 
                class="buy-option-item" 
                v-for="item in venueList" 
                :key="item.name"
                :class="{ active: selectedVenue === item.name, disabled: !item.has_available }"
                @click="item.has_available && (selectedVenue = item.name)"
              >
                <text class="option-name">{{ item.name }}</text>
              </view>
            </view>
          </view>
          
          <view class="buy-section" v-if="roomList.length > 0">
            <view class="buy-section-title">演播室</view>
            <view class="buy-options-grid">
              <view 
                class="buy-option-item" 
                v-for="item in roomList" 
                :key="item.name"
                :class="{ active: selectedRoom === item.name, disabled: !item.has_available }"
                @click="item.has_available && (selectedRoom = item.name)"
              >
                <text class="option-name">{{ item.name }}</text>
              </view>
            </view>
          </view>
          
          <view class="buy-section" v-if="sectionList.length > 0">
            <view class="buy-section-title">票档(分区)</view>
            <view class="buy-options-grid">
              <view 
                class="buy-option-item" 
                v-for="item in sectionList" 
                :key="item.name"
                :class="{ active: selectedSection === item.name, disabled: !item.has_available }"
                @click="item.has_available && (selectedSection = item.name)"
              >
                <text class="option-name">{{ item.name }}</text>
                <text class="option-price" v-if="item.price !== undefined">¥{{ item.price }}</text>
              </view>
            </view>
          </view>
        </template>
      </scroll-view>

      <!-- 底部操作栏 -->
      <view class="popup-bottom-bar" v-if="type === 'buy'">
        <button class="buy-confirm-btn" :class="{ disabled: !selectedSection }" @click="handleConfirmBuy">选座买票</button>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: 'TicketPopup',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    type: {
      type: String,
      default: 'service', // service | venue | notice | buy
      validator: val => ['service', 'venue', 'notice', 'buy'].includes(val)
    },
    // 服务列表数据
    services: {
      type: Array,
      default: () => []
    },
    // 场馆列表数据
    venues: {
      type: Array,
      default: () => []
    },
    // 购票须知数据
    buyNotices: {
      type: Array,
      default: () => []
    },
    // 观演须知数据
    watchNotices: {
      type: Array,
      default: () => []
    },
    // 须知默认选中 tab
    defaultTab: {
      type: String,
      default: 'buy'
    },
    // Tree API 数据
    treeData: {
      type: Object,
      default: () => null
    },
    seatTemplates: {
      type: Object,
      default: () => null
    },
    // 场次元数据（用于场次停售控制）
    sessionMeta: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      activeTab: this.defaultTab,
      selectedSession: null,
      selectedVenue: null,
      selectedRoom: null,
      selectedSection: null
    };
  },
  computed: {
    currentList() {
      return this.activeTab === 'buy' ? this.buyNotices : this.watchNotices;
    },
    sessionList() {
      if (!this.treeData || !this.treeData.sessions) return [];
      const now = Math.floor(Date.now() / 1000);
      return Object.values(this.treeData.sessions).map(session => {
        // 检查该场次是否已过期（停售）
        const meta = this.sessionMeta.find(m => m.session === session.name);
        const isExpired = meta ? meta.batch_expire_ts <= now : false;
        return {
          ...session,
          has_available: session.has_available && !isExpired,
          is_expired: isExpired,
          // 绑定完整的 session_meta 对象，供外部使用 session_datetime
          meta: meta || null
        };
      });
    },
    venueList() {
      if (!this.selectedSession || !this.treeData) return [];
      const sessionNode = this.treeData.sessions[this.selectedSession];
      return sessionNode && sessionNode.venues ? Object.values(sessionNode.venues) : [];
    },
    roomList() {
      if (!this.selectedVenue || !this.selectedSession || !this.treeData) return [];
      const venueNode = this.treeData.sessions[this.selectedSession].venues[this.selectedVenue];
      return venueNode && venueNode.rooms ? Object.values(venueNode.rooms) : [];
    },
    sectionList() {
      if (!this.selectedRoom || !this.selectedVenue || !this.selectedSession || !this.treeData) return [];
      const roomNode = this.treeData.sessions[this.selectedSession].venues[this.selectedVenue].rooms[this.selectedRoom];
      return roomNode && roomNode.sections ? Object.values(roomNode.sections) : [];
    }
  },
  watch: {
    defaultTab(val) {
      this.activeTab = val;
    },
    treeData: {
      handler(val) {
        if (val && val.sessions) {
          const sessions = Object.keys(val.sessions);
          if (sessions.length > 0 && !this.selectedSession) {
            this.selectedSession = sessions[0];
          }
        }
      },
      immediate: true
    },
    selectedSession(val) {
      this.selectedVenue = null;
      if (val) {
        const venues = this.venueList;
        if (venues.length > 0) this.selectedVenue = venues[0].name;
      }
    },
    selectedVenue(val) {
      this.selectedRoom = null;
      if (val) {
        const rooms = this.roomList;
        if (rooms.length > 0) this.selectedRoom = rooms[0].name;
      }
    },
    selectedRoom(val) {
      this.selectedSection = null;
    }
  },
  methods: {
    handleMaskClick() {
      this.$emit('close');
    },
    close() {
      this.$emit('close');
    },
    handleVenueClick(venue) {
      this.$emit('nav', venue);
    },
    handleConfirmBuy() {
      if (!this.selectedSection) return;
      // Emit event to open seat selector
      this.$emit('confirm-buy', {
        session: this.selectedSession,
        venue: this.selectedVenue,
        room: this.selectedRoom,
        section: this.selectedSection
      });
    },
    stopMove() {
      // 防止滚动穿透
    }
  }
};
</script>

<style>
/* Popup 容器样式 - 复用主 CSS 文件中的定义 */
.ticket-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  z-index: 999;
  display: flex;
  justify-content: center;
  align-items: flex-end;
}

.popup-inner {
  position: relative;
  width: 100%;
  max-width: 1600rpx;
  height: 70vh;
  background-color: #fff;
  border-radius: 16px 16px 0 0;
  display: flex;
  flex-direction: column;
  max-height: 70vh;
  padding: 0 16px;
}

.popup-header {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  position: relative;
  flex-shrink: 0;
}

.popup-header.has-tabs {
  justify-content: flex-start;
}

.popup-title-text {
  font-size: 18px;
  font-weight: bold;
  color: #111;
}

.popup-tabs {
  display: flex;
  gap: 24px;
}

.tab-item {
  font-size: 16px;
  color: #666;
  position: relative;
  transition: all 0.2s;
}

.tab-item.active {
  font-size: 20px;
  font-weight: bold;
  color: #111;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -12px;
  left: 50%;
  transform: translateX(-50%);
  width: 50%;
  height: 3px;
  background-color: #ff404f;
  border-radius: 2px;
}

.popup-close {
  position: absolute;
  right: 20px;
  font-size: 20px;
  color: #333;
  font-weight: 300;
}

.popup-content {
  flex: 1;
  overflow-y: auto;
  overflow-x: hidden;
  padding: 24px 20px 40px 20px;
  box-sizing: border-box;
  word-break: break-word;
}

/* 服务/须知列表项 */
.service-item {
  margin-bottom: 24px;
}

.service-item-title {
  font-size: 16px;
  font-weight: bold;
  color: #111;
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.notice-pure-title {
  font-weight: normal;
}

.service-item-content {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
  padding-left: 0;
  text-align: left;
}

.icon-success, .icon-warning {
  width: 14px;
  height: 14px;
  border-radius: 50%;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  color: #fff;
  margin-right: 6px;
}

.icon-success {
  background-color: #2ac55a;
}

.icon-warning {
  background-color: transparent;
  color: #ff404f;
  border: 1px solid #ff404f;
}

/* 场馆列表项 */
.venue-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.venue-item:last-child {
  border-bottom: none;
}

.venue-info {
  flex: 1;
  text-align: left;
  padding-right: 16px;
}

.venue-row {
  display: flex;
  align-items: center;
  margin-bottom: 6px;
  line-height: 1;
}

.venue-name {
  font-size: 16px;
  font-weight: bold;
  color: #111;
  margin-bottom: 6px;
}

.venue-address {
  font-size: 13px;
  color: #999;
  line-height: 1.4;
}

.venue-nav {
  flex-shrink: 0;
}

.nav-circle {
  width: 36px;
  height: 36px;
  background-color: #d2cfcf;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 购票选择器样式 */
.has-bottom-bar {
  padding-bottom: 90px;
}

.buy-section {
  margin-bottom: 24px;
}

.buy-section-title {
  font-size: 16px;
  font-weight: bold;
  color: #111;
  margin-bottom: 12px;
}

.buy-options-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.buy-option-item {
  padding: 10px 20px;
  background-color: #f5f5f5;
  border-radius: 8px;
  border: 1px solid transparent;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
}

.buy-option-item.active {
  background-color: #fff0f1;
  border-color: #ff404f;
}

.buy-option-item.disabled {
  opacity: 0.5;
  background-color: #f9f9f9;
}

/* 已停售场次样式 */
.buy-option-item.expired {
  background-color: #f5f5f5;
  opacity: 0.6;
}

.buy-option-item.expired .option-name {
  color: #999;
  text-decoration: line-through;
}

.option-status {
  font-size: 11px;
  color: #ff404f;
  margin-top: 2px;
}

.option-name {
  font-size: 14px;
  color: #333;
}

.buy-option-item.active .option-name {
  color: #ff404f;
  font-weight: bold;
}

.option-price {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.buy-option-item.active .option-price {
  color: #ff404f;
}

/* 底部操作栏 */
.popup-bottom-bar {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px 20px 30px;
  background-color: #fff;
  border-top: 1px solid #f0f0f0;
}

.buy-confirm-btn {
  width: 100%;
  height: 48px;
  line-height: 48px;
  background: linear-gradient(90deg, #ff6b81, #ff404f);
  color: #fff;
  border-radius: 24px;
  font-size: 16px;
  font-weight: bold;
  border: none;
}

.buy-confirm-btn.disabled {
  background: #ccc;
}
</style>
