<template>
  <view class="class-bullet-container">
    <!-- 第一行：自动缓慢滚动 + 可手动滑动 -->
    <view class="scroll-row first-row">
      <scroll-view
        class="ab-scroll mb-22rpx"
        scroll-x
        show-scrollbar="false"
        :scroll-left="scrollLeft1"
        @touchstart="onTouchStart1"
        @touchend="onTouchEnd1"
        @touchcancel="onTouchEnd1"
        @scroll="onScroll1"
      >
        <view class="sv-inner" id="sv1-inner">
          <!-- 一份内容 -->
          <view
            v-for="(item, idx) in categories"
            :key="item.id + '-row1-a-' + idx"
            class="category-item"
            @click="handleItemClick(item)"
          >
            <image v-if="item.categoryImage || item.logoUrl" :src="item.categoryImage || item.logoUrl" class="category-icon" mode="aspectFit" />
            <text class="category-text">{{ item.categoryName || item.name }}</text>
          </view>
          <!-- 第二份重复内容，用于无缝滚动 -->
          <view
            v-for="(item, idx) in categories"
            :key="item.id + '-row1-b-' + idx"
            class="category-item"
            @click="handleItemClick(item)"
          >
            <image v-if="item.categoryImage || item.logoUrl" :src="item.categoryImage || item.logoUrl" class="category-icon" mode="aspectFit" />
            <text class="category-text">{{ item.categoryName || item.name }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 第二行：反向数据，自动滚动速度略不同 -->
    <view class="scroll-row">
      <scroll-view
        class="ab-scroll"
        scroll-x
        show-scrollbar="false"
        :scroll-left="scrollLeft2"
        @touchstart="onTouchStart2"
        @touchend="onTouchEnd2"
        @touchcancel="onTouchEnd2"
        @scroll="onScroll2"
      >
        <view class="sv-inner" id="sv2-inner">
          <view
            v-for="(item, idx) in categoriesReversed"
            :key="item.id + '-row2-a-' + idx"
            class="category-item"
            @click="handleItemClick(item)"
          >
            <image v-if="item.categoryImage || item.logoUrl" :src="item.categoryImage || item.logoUrl" class="category-icon" mode="aspectFit" />
            <text class="category-text">{{ item.categoryName || item.name }}</text>
          </view>
          <view
            v-for="(item, idx) in categoriesReversed"
            :key="item.id + '-row2-b-' + idx"
            class="category-item"
            @click="handleItemClick(item)"
          >
            <image v-if="item.categoryImage || item.logoUrl" :src="item.categoryImage || item.logoUrl" class="category-icon" mode="aspectFit" />
            <text class="category-text">{{ item.categoryName || item.name }}</text>
          </view>
        </view>
      </scroll-view>
    </view>
  </view>
  
</template>

<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted, nextTick } from 'vue'

// 定义分类项接口（与模板字段一致）
interface CategoryItem {
  id: number
  categoryImage?: string
  logoUrl?: string
  name?: string
  categoryName?: string
}

// 定义组件属性
interface Props {
  /** 分类数据数组 */
  categories?: CategoryItem[]
}

const props = withDefaults(defineProps<Props>(), {
  categories: () => []
})

// 定义事件
const emit = defineEmits<{
  /** 点击分类项事件 */
  'itemClick': [item: CategoryItem]
}>()

// 模拟数据
const mockCategories: CategoryItem[] = [
  { id: 1, logoUrl: '/src/static/images/ls/6.png', name: '外卖点餐' },
  { id: 2, logoUrl: '/src/static/images/ls/7.png', name: '净菜商城' },
  { id: 3, logoUrl: '/src/static/images/ls/8.png', name: '生鲜冷链' },
  { id: 4, logoUrl: '/src/static/images/ls/9.png', name: '肉类' },
  { id: 5, logoUrl: '/src/static/images/ls/10.png', name: '调料' },
  { id: 6, logoUrl: '/src/static/images/ls/11.png', name: '零食' },
  { id: 7, logoUrl: '/src/static/images/ls/12.png', name: '海鲜' }
]

// 使用传入的数据或默认数据
const categories = computed(() => {
  return props.categories.length > 0 ? props.categories : mockCategories
})
// 第二行使用反向顺序以形成与第一行相反的视觉效果
const categoriesReversed = computed(() => {
  const list = categories.value || []
  return list.slice().reverse()
})

// ===== 自动滚动相关（电商标签推荐风格） =====
// 视口宽度，用于计算最大可滚动距离（scrollWidth - viewportWidth）
const systemInfo = uni.getSystemInfoSync()
const viewportWidth = systemInfo.windowWidth || 0

const scrollLeft1 = ref(0)
const scrollLeft2 = ref(0)

// 最大可滚动距离（由 scroll 事件提供，避免自己算）
const maxScroll1 = ref(0)
const maxScroll2 = ref(0)

const isTouching1 = ref(false)
const isTouching2 = ref(false)

let autoTimer1: any = null
let autoTimer2: any = null
let resumeTimer1: any = null
let resumeTimer2: any = null

// 速度和间隔可以根据效果微调
const AUTO_INTERVAL = 30
const AUTO_STEP_1 = 0.6
const AUTO_STEP_2 = 0.4
const RESUME_DELAY = 800
const RESET_THRESHOLD = 2 // 在距离末尾一定范围内就重置

function startAuto1() {
  if (autoTimer1) return
  autoTimer1 = setInterval(() => {
    if (isTouching1.value) return
    let next = scrollLeft1.value + AUTO_STEP_1
    const max = maxScroll1.value
    if (max > 0 && next >= max - RESET_THRESHOLD) {
      // 距离最右侧很近时，从头开始，实现循环
      next = 0
    }
    scrollLeft1.value = next
  }, AUTO_INTERVAL)
}

function startAuto2() {
  if (autoTimer2) return
  autoTimer2 = setInterval(() => {
    if (isTouching2.value) return
    let next = scrollLeft2.value + AUTO_STEP_2
    const max = maxScroll2.value
    if (max > 0 && next >= max - RESET_THRESHOLD) {
      next = 0
    }
    scrollLeft2.value = next
  }, AUTO_INTERVAL)
}

function stopAuto1() {
  if (autoTimer1) {
    clearInterval(autoTimer1)
    autoTimer1 = null
  }
}

function stopAuto2() {
  if (autoTimer2) {
    clearInterval(autoTimer2)
    autoTimer2 = null
  }
}

function onTouchStart1() {
  isTouching1.value = true
  if (resumeTimer1) clearTimeout(resumeTimer1)
  stopAuto1()
}

function onTouchEnd1() {
  resumeTimer1 = setTimeout(() => {
    isTouching1.value = false
    startAuto1()
  }, RESUME_DELAY)
}

function onScroll1(e: any) {
  const detail = e?.detail
  if (detail && typeof detail.scrollLeft === 'number') {
    scrollLeft1.value = detail.scrollLeft
    // scrollWidth - viewportWidth 为最大可滚动距离
    if (typeof detail.scrollWidth === 'number' && viewportWidth > 0) {
      const max = detail.scrollWidth - viewportWidth
      maxScroll1.value = max > 0 ? max : 0
    }
  }
}

function onTouchStart2() {
  isTouching2.value = true
  if (resumeTimer2) clearTimeout(resumeTimer2)
  stopAuto2()
}

function onTouchEnd2() {
  resumeTimer2 = setTimeout(() => {
    isTouching2.value = false
    startAuto2()
  }, RESUME_DELAY)
}

function onScroll2(e: any) {
  const detail = e?.detail
  if (detail && typeof detail.scrollLeft === 'number') {
    scrollLeft2.value = detail.scrollLeft
    if (typeof detail.scrollWidth === 'number' && viewportWidth > 0) {
      const max = detail.scrollWidth - viewportWidth
      maxScroll2.value = max > 0 ? max : 0
    }
  }
}

// 点击处理
const handleItemClick = (item: CategoryItem) => {
  emit('itemClick', item)
  navigateTo('/pages-store/pages/list/index?id=' + item.id)
}

function navigateTo(url: string) {
  uni.navigateTo({ url })
}

onMounted(() => {
  nextTick(() => {
    // 启动自动滚动，maxScroll 值会在第一次 scroll 事件时更新
    setTimeout(() => {
      startAuto1()
      startAuto2()
    }, 300)
  })
})

onUnmounted(() => {
  stopAuto1()
  stopAuto2()
  if (resumeTimer1) clearTimeout(resumeTimer1)
  if (resumeTimer2) clearTimeout(resumeTimer2)
})
</script>

<style lang="scss" scoped>
.class-bullet-container {
  width: 100%;
  overflow: hidden;

  .scroll-row {
    margin-bottom: 20rpx;
    overflow: hidden;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .ab-scroll {
    width: 100%;
    overflow: hidden;
  }

  .sv-inner {
    display: flex;
    flex-direction: row;
    gap: 20rpx;
  }

  .category-item {
    display: flex;
    align-items: center;
    justify-content: center;
    min-width: 120rpx;
    height: 60rpx;
    padding: 0 20rpx;
    border: 1px solid #C8C8C8;
    border-radius: 30rpx;
    cursor: pointer;
    transition: all 0.2s ease;
    flex-shrink: 0;

    &:active {
      transform: translateY(0) scale(0.95);
    }

    .category-icon {
      width: 32rpx;
      height: 32rpx;
      margin-right: 8rpx;
      flex-shrink: 0;
    }

    .category-text {
      font-size: 28rpx;
      color: #333;
      white-space: nowrap;
    }
  }
}

// 取消 CSS 动画，由 JS 控制的 scroll-left 实现无缝滚动，避免与手势滚动冲突导致的抖动
</style>
