<template>
  <view class="mall-page">
    <view class="mall-head" :style="{ height: headHeight + 'px', paddingTop: headTop + 'px' }">
      <view class="head-nav">
        <!-- 返回按鈕 -->
        <view class="head-left" @tap="goBack">
          <text v-if="pagesNum > 1" class="wlIcon wlIcon-fanhui1 head-icon"></text>
          <text v-else class="wlIcon wlIcon-zhuye head-icon"></text>
        </view>
        <!-- 搜索框 -->
        <view class="head-search" @tap="goSearch">
          <text class="wlIcon wlIcon-sousuo1 search-icon"></text>
          <swiper class="search-swiper" vertical autoplay circular interval="3000">
            <swiper-item>
              <text class="search-text">{{ $t('mall.searchPlaceholder') }}</text>
            </swiper-item>
            <swiper-item v-for="item in searchModules" :key="item.keywords">
              <text class="search-text">{{ item.keywords }}</text>
            </swiper-item>
          </swiper>
        </view>
        <!-- 消息中心 -->
        <view class="head-right" @tap="goNotice">
          <text class="wlIcon wlIcon-xiaoxizhongxin head-icon"></text>
        </view>
      </view>
      <!-- 分類按鈕 -->
      <view class="head-tabs">

        <scroll-view class="tabs-scroll" scroll-x scroll-with-animation :scroll-left="scrollLeft">
          <view class="tab-item" :class="{ active: currentTabId === 'home' }" @tap="onTabSelect('home', 0)">
            <text>{{ $t('mall.recommend') }}</text>
          </view>

          <view class="tab-item" v-for="(item, index) in categories" :key="item.id"
            :class="{ active: currentTabId === item.id }" @tap="onTabSelect(item.id, index + 1)">
            <text>{{ item.name }}</text>
          </view>
        </scroll-view>
        <view class="tabs-more" @tap="showCategoryModal">
          <text v-if="showCategoryPopup" class="wlIcon wlIcon-fanhui3"></text>
          <text v-else class="wlIcon wlIcon-fanhui4"></text>
        </view>
      </view>
    </view>
    <view class="mall-head-placeholder" :style="{ height: headHeight + 'px' }"></view>
    <swiper class="mall-swiper" :current="currentSwiperIndex" :style="{ height: swiperHeight + 'px' }"
      @change="onSwiperChange">
      <swiper-item>
        <mall-home-content :scrollHeight="swiperHeight" :isActive="currentTabId === 'home'" :dataStyle="listStyle"
          :homeModules="homeModules" />
      </swiper-item>
      <swiper-item v-for="item in categories" :key="item.id">
        <mall-category-content :cid="item.id" :childlist="item.childlist" :scrollHeight="swiperHeight"
          :isActive="currentTabId === item.id" :dataStyle="listStyle" />
      </swiper-item>
    </swiper>

    <view class="category-modal" v-if="showCategoryPopup" :style="{ top: headHeight + 'px' }" @tap="showCategoryPopup = false">
      <view class="category-modal-content" @tap.stop="">
        <view class="category-modal-item" :class="{ active: currentTabId === 'home' }" @tap="onTabSelect('home', 0)">
          <text>{{ $t('mall.recommend') }}</text>
        </view>
        <view class="category-modal-item" v-for="(item, index) in categories" :key="item.id"
          :class="{ active: currentTabId === item.id }" @tap="onTabSelect(item.id, index + 1)">
          <text>{{ item.name }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { pullMallInit } from '@/features/mall/mall-gateway'

export default {
  data() {
    return {
      categories: [],
      searchModules: [],
      currentTabId: 'home',
      currentSwiperIndex: 0,
      scrollLeft: 0,
      showCategoryPopup: false,
      listStyle: 'col-2-20',
      headHeight: 0,
      headTop: 0,
      swiperHeight: 600,
      pagesNum: 1,
      homeModules: {}
    }
  },
  async onLoad() {
    const sysInfo = uni.getSystemInfoSync()
    this.headTop = sysInfo.statusBarHeight || 0
    this.headHeight = this.headTop + 44 + uni.upx2px(80)
    this.swiperHeight = sysInfo.windowHeight - this.headHeight
    this.pagesNum = getCurrentPages().length
    await this.loadInit()
  },
  methods: {
    async loadInit() {
      try {
        const res = await pullMallInit()
        this.categories = res.categoryModules
        this.searchModules = res.searchModules
        this.homeModules = res.homeModules
      } catch (e) {
        console.error('加载初始化数据失败:', e)
      }
    },
    onTabSelect(id, index) {
      this.currentTabId = id
      this.currentSwiperIndex = index
      // 使用 query 动态获取标签宽度，让选中的标签滚动到可视区域
      this.scrollToTab(index)
      this.showCategoryPopup = false
    },
    onSwiperChange(e) {
      const current = e.detail.current
      this.currentSwiperIndex = current
      if (current === 0) {
        this.currentTabId = 'home'
      } else {
        this.currentTabId = this.categories[current - 1].id
      }
      this.scrollToTab(current)
    },
    scrollToTab(index) {
      const query = uni.createSelectorQuery().in(this)
      query.selectAll('.tab-item').boundingClientRect(rects => {
        if (!rects || rects.length === 0) return
        const sysInfo = uni.getSystemInfoSync()
        const screenWidth = sysInfo.windowWidth
        // 计算当前标签的累计宽度
        let totalWidth = 0
        for (let i = 0; i <= index && i < rects.length; i++) {
          totalWidth += rects[i].width
        }
        // 让选中的标签居中：滚动位置 = 累计宽度 - 屏幕一半
        const scrollOffset = totalWidth - screenWidth / 1.35
        this.scrollLeft = Math.max(0, scrollOffset)
      }).exec()
    },
    showCategoryModal() {
      this.showCategoryPopup = !this.showCategoryPopup
    },
    // 返回
    goBack() {
      if (this.pagesNum > 1) {
        uni.navigateBack({ delta: 1 })
      } else {
        uni.switchTab({ url: '/pages/index/index' })
      }
    },
    // 搜索
    goSearch() {
      uni.navigateTo({ url: '/pages/page/search?type=goods' })
    },
    // 消息中心
    goNotice() {
      uni.navigateTo({ url: '/pages/notice/mall-notice/index' })
    },
  }
}
</script>

<style scoped>
.mall-page {
  min-height: 100vh;
  background: #f5f5f5;
}

.mall-head {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background: #fff;
  z-index: 999;
}

.mall-head-placeholder {
  width: 100%;
}

.head-nav {
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 10rpx;
}

.head-left {
  width: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.head-icon {
  font-size: 44rpx;
  color: #333;
}

.head-search {
  flex: 1;
  height: 64rpx;
  background: #f5f5f5;
  border-radius: 32rpx;
  display: flex;
  align-items: center;
  padding: 0 24rpx;
}

.search-icon {
  font-size: 30rpx;
  margin-right: 10rpx;
  flex-shrink: 0;
  color: #999;
}

.search-swiper {
  height: 64rpx;
  flex: 1;
}

.search-text {
  font-size: 26rpx;
  color: #999;
  line-height: 64rpx;
}

.head-right {
  width: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.head-tabs {
  display: flex;
  align-items: center;
  height: 80rpx;
}

.tabs-scroll {
  flex: 1;
  white-space: nowrap;
  height: 100%;
}

.tab-item {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 0 30rpx;
  height: 100%;
  font-size: 28rpx;
  color: #666;
  position: relative;
}

.tab-item.active {
  color: #e54d42;
  font-weight: bold;
  font-size: 30rpx;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 40rpx;
  height: 6rpx;
  background: #e54d42;
  border-radius: 3rpx;
}

.tabs-more {
  width: 80rpx;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  color: #666;
}

.mall-swiper {
  width: 100%;
}

.category-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1000;
  background: rgba(0, 0, 0, 0.4);
}

.category-modal-content {
  background: #fff;
  padding: 20rpx 30rpx;
  display: flex;
  flex-wrap: wrap;
}

.category-modal-item {
  padding: 12rpx 30rpx;
  margin: 8rpx;
  background: #f5f5f5;
  border-radius: 30rpx;
  font-size: 26rpx;
  color: #666;
}

.category-modal-item.active {
  background: #e54d42;
  color: #fff;
}
</style>