<template>
  <view class="ticket-header">
    <!-- 使用全屏加载组件 -->
    <vr-loading :visible="isLoading" text="切换场次中..." />
    
    <view class="poster">
      <image class="poster-img" :src="posterUrl" :mode="posterMode" />
    </view>
    <view class="header-info">
      <text class="title">{{ title }}</text>
      <text class="tag">{{ tag }}</text>
      <view class="collect-btn" @click="handleCollect">
        <text class="heart-icon">{{ collected ? '♥' : '♡' }}</text>
        <text>{{ collected ? '已收藏' : '收藏演出' }}</text>
      </view>
    </view>
    
    <!-- 日期切换 Tab 卡片 -->
    <view class="date-tabs-wrapper" v-if="showDateTabs">
      <view class="date-tabs-container">
        <scroll-view class="date-tabs" scroll-x :show-scrollbar="false">
          <view 
            v-for="(item, index) in sortedDateList" 
            :key="item.uniqueKey"
            class="date-tab"
            :class="{ 
              'date-tab-current': item.isCurrent,
              'date-tab-expired': item.isExpired,
              'date-tab-loading': loadingId === item.uniqueKey
            }"
            @click="handleDateClick(item, $event)"
          >
            <!-- 点击涟漪效果 -->
            <view class="ripple" v-if="rippleId === item.id"></view>
            
            <view class="date-tab-day">{{ formatDayText(item.date) }}</view>
            <view class="date-tab-date">{{ formatDateText(item.date) }}</view>
            
            <!-- 加载指示器 -->
            <view class="tab-loading-dot" v-if="loadingId === item.uniqueKey"></view>
            
            <!-- 当前商品指示器 -->
            <view class="date-tab-indicator" v-if="item.isCurrent"></view>
            
            <!-- 当前商品标签 -->
            <view class="date-tab-current-tag" v-if="item.isCurrent">当前</view>
          </view>
        </scroll-view>
        
        <!-- 左侧渐隐遮罩 -->
        <!-- <view class="fade-mask fade-mask-left"></view> -->
        <!-- 右侧渐隐遮罩 -->
        <!-- <view class="fade-mask fade-mask-right"></view> -->
      </view>
    </view>
  </view>
</template>

<script>
// 引入全屏加载组件
import VrLoading from '../vr-loading/index.vue';

export default {
  name: 'TicketHeader',
  components: {
    VrLoading
  },
  props: {
    posterUrl: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    tag: {
      type: String,
      default: ''
    },
    collected: {
      type: Boolean,
      default: false
    },
    posterMode: {
      type: String,
      default: 'aspectFill'
    },
    // 同场次关联商品列表（来自 peer_goods）
    peerGoods: {
      type: Array,
      default: () => []
    },
    // 当前商品 ID
    currentGoodsId: {
      type: [Number, String],
      default: null
    },
    // 当前商品的批号有效期（日期字符串或时间戳）
    currentGoodsTimestamp: {
      type: [Number, String],
      default: 0
    },
    // 当前商品标题（用于显示）
    currentGoodsTitle: {
      type: String,
      default: ''
    },
    // 场次元数据
    sessionMeta: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      isLoading: false,
      loadingId: null,
      rippleId: null
    };
  },
  computed: {
    // 是否显示日期 Tab
    showDateTabs() {
      // 只要有 peerGoods 或当前商品有时间戳/日期，就显示
      return (this.peerGoods && this.peerGoods.length > 0) || !!this.currentGoodsTimestamp;
    },
    // 合并排序后的日期列表
    sortedDateList() {
      const list = [];
      const currentTimestamp = this.parseTimestamp(this.currentGoodsTimestamp);
      const currentId = this.currentGoodsId;
      
      // 添加当前商品（如果有时长）
      if (currentTimestamp > 0) {
        list.push({
          uniqueKey: `current_${currentId}`,
          id: currentId,
          date: this.timestampToDate(currentTimestamp),
          timestamp: currentTimestamp,
          isCurrent: true,
          isExpired: this.isTimestampExpired(currentTimestamp)
        });
      }
      
      // 添加 peerGoods 中的商品
      if (this.peerGoods && this.peerGoods.length > 0) {
        this.peerGoods.forEach(item => {
          // 跳过已经是当前商品的（通过 ID 匹配）
          if (item.id === currentId) {
            return;
          }
          
          // 计算时间戳
          let timestamp = 0;
          if (item.date) {
            timestamp = this.dateToTimestamp(item.date);
          }
          
          list.push({
            uniqueKey: `peer_${item.id}`,
            id: item.id,
            date: item.date || '',
            title: item.title,
            timestamp: timestamp,
            isCurrent: false,
            isExpired: timestamp > 0 ? this.isTimestampExpired(timestamp) : false
          });
        });
      }
      
      // 按时间戳排序
      list.sort((a, b) => {
        // 未设置的（timestamp=0）排到最后
        if (a.timestamp === 0 && b.timestamp > 0) return 1;
        if (b.timestamp === 0 && a.timestamp > 0) return -1;
        return a.timestamp - b.timestamp;
      });
      
      return list;
    }
  },
  methods: {
    handleCollect() {
      this.$emit('collect');
    },
    // 解析时间戳或日期字符串为 Unix 时间戳
    parseTimestamp(value) {
      if (!value) return 0;
      // 如果是数字，直接返回（假设是 Unix 时间戳）
      if (typeof value === 'number') {
        return value;
      }
      // 如果是字符串，尝试解析
      if (typeof value === 'string') {
        // 如果看起来像日期格式 (YYYY-MM-DD)，转换为时间戳
        if (value.match(/^\d{4}-\d{2}-\d{2}/)) {
          const date = new Date(value);
          return Math.floor(date.getTime() / 1000);
        }
        // 尝试直接转换为数字
        const num = parseInt(value, 10);
        if (!isNaN(num)) {
          return num;
        }
      }
      return 0;
    },
    // 将时间戳转换为日期字符串 (YYYY-MM-DD)
    timestampToDate(timestamp) {
      if (!timestamp || timestamp <= 0) return '';
      const date = new Date(timestamp * 1000);
      return date.toISOString().split('T')[0];
    },
    // 将日期字符串转换为时间戳
    dateToTimestamp(dateStr) {
      if (!dateStr) return 0;
      const date = new Date(dateStr);
      return Math.floor(date.getTime() / 1000);
    },
    // 判断时间戳是否已过期（昨天之前）
    isTimestampExpired(timestamp) {
      if (!timestamp || timestamp <= 0) return false;
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const todayTimestamp = Math.floor(today.getTime() / 1000);
      // 昨天 23:59:59 之前视为过期
      return timestamp < todayTimestamp;
    },
    // 判断日期字符串是否已过期
    isDateExpired(dateStr) {
      if (!dateStr) return false;
      return this.isTimestampExpired(this.dateToTimestamp(dateStr));
    },
    // 格式化日期文本（如 05-19）
    formatDateText(dateStr) {
      if (!dateStr) return '未设置';
      const date = new Date(dateStr);
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${month}-${day}`;
    },
    // 格式化星期/特殊日期文本
    formatDayText(dateStr) {
      if (!dateStr) return '日期待定';
      const today = new Date();
      today.setHours(0, 0, 0, 0);
      const tomorrow = new Date(today);
      tomorrow.setDate(tomorrow.getDate() + 1);
      
      const date = new Date(dateStr);
      date.setHours(0, 0, 0, 0);
      
      if (date.getTime() === today.getTime()) {
        return '今日';
      } else if (date.getTime() === tomorrow.getTime()) {
        return '明日';
      }
      
      const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
      return weekdays[date.getDay()];
    },
    // 点击日期卡片
    handleDateClick(item, event) {
      // 排除当前商品和已过期日期
      if (item.isCurrent || item.isExpired) {
        return;
      }
      
      // 触发涟漪效果
      this.triggerRipple(item.uniqueKey);
      
      // 显示加载状态
      this.isLoading = true;
      this.loadingId = item.uniqueKey;
      
      // 延迟发出事件，让动画先播放
      setTimeout(() => {
        this.$emit('switch-date', item.id);
        
        // 动画完成后重置
        setTimeout(() => {
          this.isLoading = false;
          this.loadingId = null;
        }, 300);
      }, 500);
    },
    // 触发涟漪动画
    triggerRipple(id) {
      this.rippleId = id;
      setTimeout(() => {
        this.rippleId = null;
      }, 600);
    }
  }
};
</script>

<style scoped>
.ticket-header {
  background: 
    radial-gradient(ellipse at 20% 80%, rgba(120, 80, 255, 0.15) 0%, transparent 50%),
    radial-gradient(ellipse at 80% 20%, rgba(255, 0, 127, 0.1) 0%, transparent 40%),
    linear-gradient(160deg, #1a1625 0%, #2d2840 50%, #1f1b2e 100%);
  padding: 54px 20px 20px 20px;
  display: flex;
  align-items: flex-start;
  flex-wrap: wrap;
  color: #fff;
  position: relative;
}

.poster {
  flex-shrink: 0;
  width: 105px;
  height: 140px;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 10px rgba(0,0,0,0.3);
}

.poster-img {
  width: 100%;
  height: 100%;
}

.header-info {
  margin-left: 16px;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  flex: 1;
  min-width: 0;
  height: 140px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  line-height: 1.4;
  margin: 0;
  margin-top: 4px;
}

.tag {
  font-size: 12px;
  color: #d0cdd8;
  margin-top: 10px;
  text-align: left;
}

.collect-btn {
  margin-top: auto;
  align-self: flex-start;
  background-color: rgba(0, 0, 0, 0.4);
  padding: 8px 18px;
  border-radius: 20px;
  font-size: 14px;
  display: flex;
  align-items: center;
  transition: background-color 0.2s ease, transform 0.2s ease;
}

.collect-btn:active {
  transform: scale(0.95);
  background-color: rgba(0, 0, 0, 0.6);
}

.heart-icon {
  font-size: 14px;
  margin-right: 4px;
}

/* 日期切换 Tab 卡片 */
.date-tabs-wrapper {
  position: relative;
  width: 100vw;
  left: 50%;
  transform: translateX(-50%);
  margin-top: 20px;
  background: rgba(0, 0, 0, 0.2);
}

/* 容器 - 用于定位渐隐遮罩 */
.date-tabs-container {
  position: relative;
  padding: 12px 20px 16px;
  width: 100%;
  box-sizing: border-box;
}

/* 滚动视图 */
.date-tabs {
  display: flex;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  scrollbar-width: none;
  -ms-overflow-style: none;
}

.date-tabs ::-webkit-scrollbar {
  display: none;
}

/* 渐隐遮罩 - 固定在容器两侧 */
.fade-mask {
  position: absolute;
  top: 0;
  bottom: 0;
  width: 24px;
  pointer-events: none;
  z-index: 10;
}

.fade-mask-left {
  left: 0;
  background: linear-gradient(to right, rgba(0, 0, 0, 0.6), transparent);
}

.fade-mask-right {
  right: 0;
  background: linear-gradient(to left, rgba(0, 0, 0, 0.6), transparent);
}

.date-tab {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-width: 60px;
  padding: 10px 14px;
  margin-right: 8px;
  background: rgba(255, 255, 255, 0.08);
  border-radius: 10px;
  position: relative;
  overflow: hidden;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  flex-shrink: 0;
  cursor: pointer;
}

/* 当前 Tab（不可点击） */
.date-tab-current {
  cursor: default;
  background: rgba(255, 64, 79, 0.25);
  box-shadow: 0 0 20px rgba(255, 64, 79, 0.2);
}

.date-tab-current .date-tab-date {
  color: #ff404f;
  font-size: 16px;
  font-weight: bold;
}

.date-tab-current .date-tab-day {
  color: rgba(255, 64, 79, 0.8);
}

/* 已过期 Tab（不可点击） */
.date-tab-expired {
  cursor: not-allowed;
  opacity: 0.5;
}

.date-tab-expired .date-tab-date {
  text-decoration: line-through;
  color: rgba(255, 255, 255, 0.5);
}

.date-tab-expired .date-tab-day {
  color: rgba(255, 255, 255, 0.4);
}

/* 最后一个 tab 去掉右边距 */
.date-tab:last-child {
  margin-right: 0;
}

.date-tab:hover:not(.date-tab-current):not(.date-tab-expired) {
  background: rgba(255, 255, 255, 0.15);
  transform: translateY(-2px);
}

.date-tab:active:not(.date-tab-current):not(.date-tab-expired) {
  transform: scale(0.95) translateY(0);
}

/* 涟漪效果 */
.ripple {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 10px;
  height: 10px;
  background: rgba(255, 64, 79, 0.5);
  border-radius: 50%;
  transform: translate(-50%, -50%) scale(0);
  animation: ripple-expand 0.6s ease-out forwards;
}

@keyframes ripple-expand {
  0% {
    transform: translate(-50%, -50%) scale(0);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(8);
    opacity: 0;
  }
}

/* 加载指示点 */
.tab-loading-dot {
  position: absolute;
  top: 4px;
  right: 4px;
  width: 6px;
  height: 6px;
  background: #ff404f;
  border-radius: 50%;
  animation: loading-dot-pulse 0.8s ease-in-out infinite;
}

@keyframes loading-dot-pulse {
  0%, 100% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.5); opacity: 0.5; }
}

.date-tab-day {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
  margin-bottom: 2px;
  transition: color 0.3s ease;
}

.date-tab-date {
  font-size: 16px;
  font-weight: bold;
  color: #fff;
  transition: color 0.3s ease, transform 0.3s ease;
}

.date-tab-indicator {
  position: absolute;
  bottom: 2px;
  left: 50%;
  transform: translateX(-50%);
  width: 24px;
  height: 3px;
  background: #ff404f;
  border-radius: 2px;
  animation: indicator-glow 1.5s ease-in-out infinite;
}

@keyframes indicator-glow {
  0%, 100% { 
    box-shadow: 0 0 5px rgba(255, 64, 79, 0.5);
  }
  50% { 
    box-shadow: 0 0 15px rgba(255, 64, 79, 0.8), 0 0 25px rgba(255, 64, 79, 0.4);
  }
}

/* 当前商品标签 */
.date-tab-current-tag {
  position: absolute;
  top: -2px;
  right: -2px;
  background: linear-gradient(135deg, #ff404f, #ff6b81);
  color: #fff;
  font-size: 9px;
  padding: 1px 5px;
  border-radius: 4px 4px 4px 0;
  font-weight: bold;
}

/* 已过期状态 */
.date-tab-expired {
  opacity: 0.4;
}

.date-tab-expired .date-tab-date {
  text-decoration: line-through;
  color: rgba(255, 255, 255, 0.4);
}

.date-tab-expired .date-tab-day {
  color: rgba(255, 255, 255, 0.3);
}

/* 加载中状态 */
.date-tab-loading {
  background: rgba(255, 64, 79, 0.2);
  animation: tab-loading-pulse 1s ease-in-out infinite;
}

@keyframes tab-loading-pulse {
  0%, 100% { 
    background: rgba(255, 64, 79, 0.15);
    box-shadow: none;
  }
  50% { 
    background: rgba(255, 64, 79, 0.25);
    box-shadow: 0 0 15px rgba(255, 64, 79, 0.3);
  }
}
</style>
