<template>
  <view class="page">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-state">
      <view class="loading-skeleton" v-for="i in 5" :key="i">
        <view class="skeleton-logo"></view>
        <view class="skeleton-content">
          <view class="skeleton-title"></view>
          <view class="skeleton-subtitle"></view>
        </view>
      </view>
    </view>

    <!-- 字母索引列表 -->
    <view v-else class="index-list">
      <scroll-view 
        scroll-y 
        class="content"
        :scroll-into-view="currentLetter ? 'letter-' + currentLetter : ''"
        @scroll="onScroll"
        :scroll-with-animation="true"
      >
        <block v-for="(group, letter) in groupedBreweries" :key="letter">
          <view :id="'letter-' + letter" class="letter-section" :data-letter="letter">
            <view class="letter-title">{{letter}}</view>
            <view 
              class="brewery-item hover-effect"
              v-for="brewery in group"
              :key="brewery.id"
              @click="navigateToBrewery(brewery)"
            >
              <image 
                :src="brewery.brandLogo || '/static/images/default-logo.png'" 
                class="brewery-logo"
                mode="aspectFill"
                :lazy-load="true"
              />
              <view class="brewery-info">
                <text class="brewery-name text-ellipsis">{{brewery.brandName}}</text>
                <text class="beer-count">{{brewery.beerCount || 0}}款在售</text>
              </view>
              <image 
                src="/static/icons/arrow-right.png" 
                class="arrow-icon"
              />
            </view>
          </view>
        </block>
        
        <!-- 空状态 -->
        <view v-if="Object.keys(groupedBreweries).length === 0" class="empty-state">
          <image src="/static/images/empty.png" class="empty-image" />
          <text class="empty-text">暂无相关品牌</text>
        </view>
      </scroll-view>
      
      <!-- 右侧字母导航 -->
      <view class="letter-nav">
        <view class="indicator" :style="indicatorStyle"></view>
        <view 
          v-for="letter in letters" 
          :key="letter"
          class="letter-item"
          :class="{ active: currentLetter === letter }"
          @click="scrollToLetter(letter)"
        >
          {{letter}}
        </view>
      </view>
    </view>
  </view>
</template>

<script>
  import { getBreweries, getBeerList } from '@/api/bar.js'
  
  export default {
    name: 'HotLabel',
    data() {
      return {
        // 数据相关
        breweries: [],
        groupedBreweries: {},
        currentLetter: '',
        letters: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''),
        
        // 加载状态
        loading: false,
        scrollTimer: null,
        indicatorTop: 0,
        observer: null,
      }
    },
    computed: {
      indicatorStyle() {
        return {
          transform: `translateY(${this.indicatorTop}px)`,
        }
      }
    },
    created() {
      // 移除 Pinyin.setOptions 调用
    },
    onShow() {
      this.initData()
    },
    mounted() {
      this.setupIntersectionObserver()
    },
    beforeDestroy() {
      if (this.observer) {
        this.observer.disconnect()
      }
    },
    methods: {
      // 初始化数据
      async initData() {
        try {
          uni.showLoading({
            title: '加载中...'
          })
          
          const res = await getBreweries()
          if (res && res.code === 200 && res.data) {
            // 直接使用后端返回的分组数据
            this.groupedBreweries = res.data.groupedBreweries || {}
            this.letters = res.data.letters || []
            
            // 更新品牌列表
            this.breweries = res.data.breweries || []
          } else {
            throw new Error(res?.msg || '获取品牌列表失败')
          }
        } catch (error) {
          console.error('初始化数据失败:', error)
          uni.showToast({
            title: error.message || '加载失败，请重试',
            icon: 'none'
          })
        } finally {
          uni.hideLoading()
        }
      },
      
      // 设置交叉观察器
      setupIntersectionObserver() {
        if (typeof uni.createIntersectionObserver !== 'function') return
        
        this.observer = uni.createIntersectionObserver(this)
        this.observer
          .relativeTo('.content')
          .observe('.letter-section', (res) => {
            if (res.intersectionRatio > 0) {
              const letter = res.dataset.letter
              this.updateCurrentLetter(letter, false)
            }
          })
      },

      // 滚动事件处理
      onScroll(e) {
        if (this.scrollTimer) {
          clearTimeout(this.scrollTimer)
        }
        
        this.scrollTimer = setTimeout(() => {
          const query = uni.createSelectorQuery().in(this)
          query.selectAll('.letter-section').boundingClientRect()
          query.select('.content').boundingClientRect()
          query.exec(([sections, content]) => {
            if (!sections || !content) return
            
            const contentTop = content.top
            let currentSection = null
            let minDistance = Infinity
            
            // 找到距离顶部最近的section
            sections.forEach(section => {
              const distance = Math.abs(section.top - contentTop)
              if (distance < minDistance) {
                minDistance = distance
                currentSection = section
              }
            })
            
            if (currentSection) {
              const letter = currentSection.dataset.letter
              this.updateCurrentLetter(letter, false)
            }
          })
        }, 50) // 降低延迟以提高响应速度
      },

      // 更新当前字母
      updateCurrentLetter(letter, shouldScroll = true) {
        if (this.currentLetter === letter) return
        
        this.currentLetter = letter
        
        // 更新指示器位置
        const query = uni.createSelectorQuery().in(this)
        query.selectAll('.letter-item').boundingClientRect()
        query.select('.letter-nav').boundingClientRect()
        query.exec(([items, nav]) => {
          if (!items || !nav) return
          
          const index = this.letters.indexOf(letter)
          if (index > -1) {
            const item = items[index]
            // 调整指示器位置，确保准确对齐
            this.indicatorTop = item.top - nav.top + (item.height - 48) / 2 // 48是指示器的高度
          }
        })
        
        // 是否需要滚动到对应位置
        if (shouldScroll) {
          uni.pageScrollTo({
            selector: `#letter-${letter}`,
            duration: 300
          })
        }
      },

      // 滚动到指定字母
      scrollToLetter(letter) {
        this.updateCurrentLetter(letter)
        // 已有的滚动逻辑保持不变
      },
      
      // 导航到品牌详情
      navigateToBrewery(brewery) {
        uni.navigateTo({
          url: `/pages/activityList/styleSelection?breweryId=${brewery.id}`
        })
      },
    }
  }
</script>

<style lang="scss" scoped>
.page {
  min-height: 100vh;
  background: #F8F9FC;
  
  // 加载状态
  .loading-state {
    padding: 24rpx;
    
    .loading-skeleton {
      display: flex;
      align-items: center;
      padding: 32rpx;
      margin-bottom: 24rpx;
      background: #FFFFFF;
      border-radius: 16rpx;
      box-shadow: 0 4rpx 16rpx rgba(0,0,0,0.04);
      
      .skeleton-logo {
        width: 88rpx;
        height: 88rpx;
        background: linear-gradient(90deg, #F5F5F5, #FAFAFA, #F5F5F5);
        border-radius: 16rpx;
        margin-right: 32rpx;
        animation: skeleton-loading 1.5s infinite;
      }
      
      .skeleton-content {
        flex: 1;
        
        .skeleton-title {
          width: 60%;
          height: 36rpx;
          background: linear-gradient(90deg, #F5F5F5, #FAFAFA, #F5F5F5);
          border-radius: 8rpx;
          margin-bottom: 16rpx;
          animation: skeleton-loading 1.5s infinite;
        }
        
        .skeleton-subtitle {
          width: 40%;
          height: 28rpx;
          background: linear-gradient(90deg, #F5F5F5, #FAFAFA, #F5F5F5);
          border-radius: 6rpx;
          animation: skeleton-loading 1.5s infinite;
        }
      }
    }
  }
  
  // 字母索引列表
  .index-list {
    display: flex;
    height: 100vh;
    background: #FFFFFF;
    
    .content {
      flex: 1;
      height: 100%;
      
      .letter-section {
        .letter-title {
          padding: 20rpx 32rpx;
          font-size: 28rpx;
          color: #666666;
          background: #F8F9FC;
          font-weight: 600;
        }
        
        .brewery-item {
          display: flex;
          align-items: center;
          padding: 32rpx;
          margin: 0 32rpx;
          border-bottom: 2rpx solid #F5F7FA;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          position: relative;
          
          &:active {
            background: #F8F9FC;
            transform: scale(0.99);
          }
          
          &::after {
            content: '';
            position: absolute;
            left: 32rpx;
            right: 32rpx;
            bottom: 0;
            height: 2rpx;
            background: #F5F7FA;
          }
          
          &:last-child::after {
            display: none;
          }
          
          .brewery-logo {
            width: 88rpx;
            height: 88rpx;
            border-radius: 16rpx;
            margin-right: 32rpx;
            background: #F8F9FC;
            box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.06);
            transition: transform 0.3s ease;
            
            &:active {
              transform: scale(0.95);
            }
          }
          
          .brewery-info {
            flex: 1;
            
            .brewery-name {
              font-size: 30rpx;
              color: #333333;
              margin-bottom: 12rpx;
              font-weight: 600;
            }
            
            .beer-count {
              font-size: 26rpx;
              color: #666666;
              display: flex;
              align-items: center;
              
              &::before {
                content: '';
                display: inline-block;
                width: 12rpx;
                height: 12rpx;
                border-radius: 50%;
                background: #19C375;
                margin-right: 8rpx;
              }
            }
          }
          
          .arrow-icon {
            width: 36rpx;
            height: 36rpx;
            opacity: 0.4;
            margin-left: 24rpx;
            transition: transform 0.3s ease;
          }
          
          &:active .arrow-icon {
            transform: translateX(4rpx);
          }
        }
      }
      
      .empty-state {
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 120rpx 0;
        
        .empty-image {
          width: 280rpx;
          height: 280rpx;
          margin-bottom: 40rpx;
          opacity: 0.8;
        }
        
        .empty-text {
          font-size: 30rpx;
          color: #666666;
          letter-spacing: 2rpx;
        }
      }
    }
    
    // 右侧字母导航
    .letter-nav {
      display: flex;
      flex-direction: column;
      justify-content: center;
      padding: 24rpx 16rpx;
      background: #FFFFFF;
      box-shadow: -4rpx 0 16rpx rgba(0,0,0,0.03);
      position: relative;
      
      .indicator {
        position: absolute;
        left: 50%;
        width: 48rpx;
        height: 48rpx;
        border-radius: 50%;
        background: rgba(25, 54, 122, 0.1);
        transform: translateX(-50%);
        transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        pointer-events: none;
        z-index: 1;
      }
      
      .letter-item {
        width: 40rpx;
        height: 40rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 24rpx;
        color: #666666;
        margin: 4rpx 0;
        border-radius: 50%;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        font-weight: 500;
        position: relative;
        z-index: 2;
        
        &.active {
          color: #FFFFFF;
          background: #19367A;
          font-weight: 600;
          transform: scale(1.1);
          box-shadow: 0 4rpx 8rpx rgba(25, 54, 122, 0.2);
        }
        
        &:active {
          transform: scale(0.9);
        }
      }
    }
  }
}

@keyframes skeleton-loading {
  0% {
    background-position: -200% 0;
  }
  100% {
    background-position: 200% 0;
  }
}

// 添加按键反馈效果
.hover-effect {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  &:active {
    transform: scale(0.98);
    opacity: 0.9;
  }
}

// 文本省略
.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>