<template>
  <!-- <scroll-view 
      class="home-page" 
      scroll-y 
      refresher-enabled 
      :refresher-triggered="isRefreshing"
      @refresherrefresh="handleRefresh"
    > -->
  <view class="home-page">
    <!-- 顶部背景区域 -->
    <view class="home-bg" :style="{ paddingTop: getNotchHeight() + 'px' }">
      <wd-search
        hide-cancel
        light
        clearable
        class="search-bar"
        :placeholder="$t('bookHome.searchPlaceholder')"
        @search="handleSearch"
      />
      <view class="icon-hua">
        <image
          src="../../static/book/home_icon.png"
          mode="aspectFit"
          class="icon-hua-img"
        />
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content-wrapper">
      <!-- 我的书单 & 推荐图书模块 -->
      <view class="mine-block">
        <!-- 我的书单 -->
        <Skeleton
          ref="myBookSkeleton"
          theme="image-card"
          :request="getMyBooks"
          :size="[{ height:'140px' }]"
          class="flex-1 w-[50%]"
        >
          <template #content="{ data }" >
            <view class="mine-1">
              <text class="mine-title">{{ $t('bookHome.block1') }}</text>
              <view
                v-if="data?.page?.records.length > 0"
                class="mine-more"
                @click="handleMoreClick"
              >
                {{ $t('bookHome.more') }}
                <image src="@/static/icon/icon_right.png" />
              </view>
              <view v-if="data?.page?.records.length > 0" class="mine-1-list">
                <view
                  v-for="(item, index) in data?.page?.records"
                  :key="index"
                  class="mine-item"
                  @click="handleMyBookClick(item.id)"
                >
                  <image :src="item.images" />
                  <text>{{ item.name }}</text>
                </view>
              </view>
              <text v-else class="zanwu">{{ $t('common.data_null') }}</text>
            </view>
          </template>
        </Skeleton>
        
        <!-- 推荐图书 -->
        <Skeleton
          ref="recommendBooksSkeleton"
          theme="image-card"
          :request="getRecommendBooks"
          :size="[{ height:'140px' }]"
          class="flex-1 w-[50%]"
        >
          <template #content="{ data }" >
            <view class="mine-2">
              <text class="mine-title">{{ $t('bookHome.block2') }}</text>
              <swiper
                v-if="data.books.length > 0"
                autoplay
                :interval="3000"
                :duration="500"
                class="recommend-list"
              >
                <swiper-item
                  v-for="(item, index) in data.books"
                  :key="index"
                  class="recommend-item"
                  @click="handleBookClick(item.id)"
                >
                  <image :src="item.images" width="100%" height="100%" />
                  <text>{{ item.name }}</text>
                </swiper-item>
              </swiper>
            </view>
          </template>
        </Skeleton>
      </view>

      <!-- 活动图书模块 -->
      <view class="activity-block">
        <Skeleton
          ref="activityLabelsSkeleton"
          theme="image-card"
          :size="Array(5).fill({ height:'28px', width: '18%' })"
          :request="getActivityLabels"
          @success="getActivityLabelsSuccess"
        >
          <template #loading-top>
            <wd-skeleton :row-col="[{ width: '45%', height: '35px' }]" animation="gradient" class="mb-2.5!" />
          </template>
          <template #content>
            <text class="activity-title">{{ $t('bookHome.activityTitle') }}</text>
            <scroll-view class="scroll-view" scroll-x :show-scrollbar="false">
              <view class="activity-label-list">
                <view
                  v-for="(item, index) in activityLabelList"
                  :key="index"
                  :class="[
                    'activity-label-item',
                    currentActivityIndex === index ? 'active-label' : ''
                  ]"
                  @click="handleActivityLabelClick(item.id, index)"
                >
                  <text>{{ item.title }}</text>
                </view>
              </view>
            </scroll-view>
          </template>
        </Skeleton>
        <Skeleton
          ref="activityBooksSkeleton"
          theme="image-card"
          :auto="false"
          :size="Array(4).fill({ height:'100px', width: '23%' })"
          class="mt-[20rpx]!"
          :request="getActivityBooks"
        >
          <template #content="{ data }">
            <scroll-view
              v-if="data.bookList.length > 0"
              class="scroll-view"
              scroll-x
              :show-scrollbar="false"
            >
              <view class="activity-list">
                <view
                  v-for="(item, index) in data.bookList"
                  :key="index"
                  class="activity-item"
                  @click="handleBookClick(item.bookId)"
                >
                  <image :src="item.images" />
                  <text class="activity-text">{{ item.name }}</text>
                </view>
              </view>
            </scroll-view>
            <text v-else class="zanwu" style="padding: 80rpx 0">{{ $t('global.dataNull') }}</text>
          </template>
        </Skeleton>
      </view>

      <!-- 分类图书模块 -->
      <view class="book-block">
        <Skeleton
          ref="categoryLevel1LabelSkeleton"
          theme="image-card"
          :size="Array(3).fill({ height:'75px', width: '32%' })"
          :request="getCategoryLabels"
          @success="getCategoryLabelsSuccess"
        >
          <template #content>
            <!-- 一级分类标签 -->
            <scroll-view class="scroll-view" scroll-x :show-scrollbar="false">
              <view class="book-tab-one">
                <view
                  v-for="(item, index) in categoryLevel1List"
                  :key="index"
                  :class="[
                    'tab-one-item',
                    currentLevel1Index === index ? 'tab-one-active' : ''
                  ]"
                  @click="handleCategoryLevel1Click(item.id, index)"
                >
                  <text>{{ item.title }}</text>
                </view>
              </view>
            </scroll-view>
          </template>
        </Skeleton>
        <Skeleton
          ref="categoryLevel2LabelSkeleton"
          theme="image-card"
          :auto="false"
          :size="Array(4).fill({ height:'30px', width: '24%' })"
          class="mt-[20rpx]!"
          :request="getSubLabels"
          @success="getSubLabelsSuccess"
        >
          <template #content>
            <!-- 二级分类标签 -->
            <scroll-view
              v-if="categoryLevel2List.length > 0"
              class="scroll-view"
              scroll-x
              :show-scrollbar="false"
              style="background: #fff; margin-top: 15rpx"
            >
              <view class="book-tab-two">
                <view
                  v-for="(item, index) in categoryLevel2List"
                  :key="index"
                  :class="[
                    'tab-two-item',
                    currentLevel2Index === index ? 'tab-two-active' : ''
                  ]"
                  @click="handleCategoryLevel2Click(item.id, index)"
                >
                  <text>{{ item.title }}</text>
                </view>
              </view>
            </scroll-view>
          </template>
        </Skeleton>

        <!-- 分类图书列表 -->
        <Skeleton
          ref="categoryBooksSkeleton"
          theme="image-card"
          :auto="false"
          :size="Array(2).fill({ height:'240px', width: '49%' })"
          :count="3"
          class="mt-[20rpx]!"
          :request="getBooksByLabel"
        >
          <template #content="{ data }">
            <view v-if="data.bookList.length > 0" class="book-list">
              <view
                v-for="(item, index) in data.bookList"
                :key="index"
                class="book-item"
                @click="handleBookClick(item.bookId)"
              >
                <image :src="item.images" />
                <text class="book-text">{{ item.name }}</text>
                <BookPrice :data="item" class="book-price-container" />
              </view>
            </view>
            <text v-else class="zanwu" style="padding: 100rpx 0">{{ $t('global.dataNull') }}</text>
          </template>
        </Skeleton>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app'
import { bookHomeApi } from '@/api/modules/book_home'
import { getNotchHeight } from '@/utils/system'
import { useUserStore } from '@/stores/user'
import BookPrice from '@/components/book/BookPrice.vue'
import type { ILabel } from '@/types/book'

const userStore = useUserStore()

// 我的书单
const myBookSkeleton = ref()

// 推荐图书
const recommendBooksSkeleton = ref()

// 活动图书
const activityLabelsSkeleton = ref()
const activityBooksSkeleton = ref()
const activityLabelList = ref<ILabel[]>([])
const currentActivityIndex = ref(0)

// 分类图书
const categoryLevel1LabelSkeleton = ref()
const categoryLevel2LabelSkeleton = ref()
const categoryBooksSkeleton = ref()
const categoryLevel1List = ref<ILabel[]>([])
const categoryLevel2List = ref<ILabel[]>([])
const currentLevel1Index = ref(0)
const currentLevel2Index = ref(0)

// VIP信息
const vipInfo = computed(() => userStore.userInfo?.userEbookVip?.[0] || null)

/**
 * 获取我的书单
 */
const getMyBooks = () => uni.getStorageSync('token') ? bookHomeApi.getMyBooks(1, 10) : []

/**
 * 获取推荐图书
 */
const getRecommendBooks = () => bookHomeApi.getRecommendBooks()

/**
 * 获取活动图书
 */
// 获取活动图书标签列表
const getActivityLabels = () => bookHomeApi.getBookLabelList(1)
const getActivityLabelsSuccess = (res: any) => {
  activityLabelList.value = res.lableList || []
  activityBooksSkeleton.value.reload()
}
// 获取活动图书列表
const getActivityBooks = () => {
  // 获取活动标签列表
  const index = currentActivityIndex.value || 0
  return bookHomeApi.getBooksByLabel(activityLabelList.value[index].id)
}

/**
 * 获取分类标签列表
 */
const getCategoryLabels = () => bookHomeApi.getBookLabelList(0)
const getCategoryLabelsSuccess = (res: any) => {
  categoryLevel1List.value = res.lableList || []
  currentLevel2Index.value = 0
  categoryLevel2LabelSkeleton.value.reload()
}
/**
 * 获取二级标签列表
 */
const getSubLabels = async () => {
  await getCategoryLabels()
  const pid = categoryLevel1List.value[currentLevel1Index.value]?.id || 0
  return bookHomeApi.getSubLabelList(pid)
}
const getSubLabelsSuccess = (res: any) => {
  categoryLevel2List.value = res.lableList || []
  categoryBooksSkeleton.value.reload()
}
/**
 * 获取分类标签图书列表
 */
const getBooksByLabel = () => {
  // 获取当前需要加载的标签id
  // 判断是否有一级标签当前选中值
  const level1Id = categoryLevel1List.value[currentLevel1Index.value]?.id
  // 判断是否有二级标签当前选中值
  const level2Id = categoryLevel2List.value[currentLevel2Index.value]?.id

  const labelId = level2Id || level1Id || 0
  return bookHomeApi.getBooksByLabel(labelId)
}

/**
 * 处理搜索点击
 */
const handleSearch = ({ value }: { value: string }) => {
  uni.navigateTo({
    url: `/pages/book/search?keyword=${value}`
  })
}

/**
 * 处理我的书单图书点击
 */
const handleMyBookClick = (bookId: number) => {
  uni.navigateTo({
    url: `/pages/book/reader?isBuy=1&bookId=${bookId}`
  })
}

/**
 * 处理图书点击
 */
const handleBookClick = (bookId: number) => {
	getPrompt()
	if(!uni.getStorageSync('token')) return
  uni.navigateTo({
    url: `/pages/book/detail?id=${bookId}`
  })
}

/**
 * 处理更多按钮点击
 */
const handleMoreClick = () => {
  uni.navigateTo({
    url: '/pages/user/myBook/index'
  })
}

/**
 * 处理活动标签点击
 */
const handleActivityLabelClick = async (labelId: number, index: number) => {
	getPrompt()
	if(!uni.getStorageSync('token')) return
  currentActivityIndex.value = index
  activityBooksSkeleton.value.reload()
}

/**
 * 处理一级分类标签点击
 */
const handleCategoryLevel1Click = async (labelId: number, index: number) => {
  currentLevel1Index.value = index
  currentLevel2Index.value = 0
  categoryBooksSkeleton.value.loading = true
  categoryLevel2LabelSkeleton.value.reload()
}

/**
 * 处理二级分类标签点击
 */
const handleCategoryLevel2Click = async (labelId: number, index: number) => {
  currentLevel2Index.value = index
  categoryBooksSkeleton.value.reload()
}

/**
 * 登录提示语
 */
const getPrompt = () => {
	if(!uni.getStorageSync('token')) {
	 uni.showModal({
	 	title: '提示',
	 	content: '请先登录后访问该页面',
	 	confirmText: '去登录',
	 	success: (res) => {
			console.log(res , 'res');
	 		if (res.confirm) uni.navigateTo({
					url: '/pages/login/login'
			});
	 	}
	 });
 }
}

/**
 * 刷新页面数据
 */
const handleRefresh = async () => {
  try {
    // 刷新所有数据
    await Promise.all([
      myBookSkeleton.value?.reload(),
      recommendBooksSkeleton.value?.reload(),
      activityLabelsSkeleton.value?.reload(),
      categoryLevel1LabelSkeleton.value?.reload()
    ])
  } catch (error) {
    console.error('刷新数据失败:', error)
  } finally {
    // 延迟关闭刷新状态，避免闪烁
    setTimeout(() => {
      uni.stopPullDownRefresh();
    }, 500)
  }
}

/**
 * 下拉刷新
 */
onPullDownRefresh(() => {
  handleRefresh()
})

/**
 * 页面显示
 */
onShow(() => {
  // 刷新数据
  myBookSkeleton.value?.reload()
  categoryLevel1LabelSkeleton.value?.reload()
})
</script>

<style lang="scss" scoped>
.home-page {
  min-height: 100vh;
  background: #f7faf9;
}

.home-bg {
  background-image: url('@/static/icon/home_bg.jpg');
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
  padding: 30rpx;
  position: relative;

  .icon-hua {
    width: 100%;
    text-align: center;
    display: block;
    padding-top: 20rpx;

    .icon-hua-img {
      width: 100%;
      height: 160rpx;
    }
  }
}

.search-bar {
  background-color: transparent !important;
}

.content-wrapper {
  padding-bottom: 40rpx;
  height: calc(100vh - 240px);
}

.mine-block {
  padding: 20rpx;
  display: flex;
  gap: 20rpx;
  align-items: center;
  justify-content: space-between;

  .mine-1,
  .mine-2 {
    height: 290rpx;
    border-radius: 15rpx;
    padding: 30rpx;
    position: relative;

    .mine-title {
      font-size: 32rpx;
      color: #333;
      line-height: 32rpx;
    }

    .mine-more {
      position: absolute;
      top: 30rpx;
      right: 5rpx;
      font-size: 28rpx;
      line-height: 34rpx;
      color: #999;

      image {
        display: inline-block;
        vertical-align: text-bottom;
        width: 34rpx;
        height: 34rpx;
      }
    }

    .mine-1-list {
      width: 260rpx;
      overflow: hidden;
      display: flex;
      align-items: center;

      .mine-item {
        width: 110rpx;
        text-align: center;
        margin: 20rpx 25rpx 0 0;

        image {
          width: 110rpx;
          height: 135rpx;
          border-radius: 10rpx;
        }

        text {
          display: block;
          width: 120rpx;
          font-size: 28rpx;
          color: #333;
          line-height: 32rpx;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          padding-top: 10rpx;
        }
      }
    }

    .recommend-list {
      width: 310rpx;
      height: 164rpx;
      margin-top: 20rpx;

      .recommend-item {
        display: flex;
        align-items: center;

        image {
          width: 120rpx;
          height: 164rpx;
          border-radius: 10rpx;
        }

        text {
          display: block;
          width: 190rpx;
          font-size: 28rpx;
          color: #333;
          line-height: 40rpx;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          padding-left: 15rpx;
        }
      }
    }
  }

  .mine-1 {
    background-image: linear-gradient(60deg, #fff9e9 20%, #fffbf2 100%);
  }

  .mine-2 {
    background-image: linear-gradient(60deg, #fef0f0 20%, #fdf9f8 100%);
  }
}

.activity-block {
  margin: 0 20rpx;
  padding: 20rpx;
  background: #fff;
  border-radius: 15rpx;
  min-height: 445rpx;

  .activity-title {
    display: block;
    font-size: 38rpx;
    color: #333;
    line-height: 40rpx;
    padding: 15rpx 0 20rpx;
  }

  .activity-label-list {
    display: flex;
    align-items: center;
    margin-top: 10rpx;
    padding-left: 10rpx;

    .activity-label-item {
      display: flex;
      align-items: center;
      background-color: #d7ece8;
      border-radius: 10rpx;
      margin-right: 20rpx;
      padding: 0 10rpx;
      flex-shrink: 0;

      text {
        display: inline-block;
        text-align: center;
        min-width: 110rpx;
        height: 58rpx;
        line-height: 58rpx;
        color: #55aa7f;
        font-size: 30rpx;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }

    .active-label {
      background-color: #55aa7f;

      text {
        color: #fff;
      }
    }
  }

  .activity-list {
    width: 100%;
    padding-left: 10rpx;
    display: flex;
    align-items: center;

    .activity-item {
      margin-right: 25rpx;
      text-align: center;
      flex-shrink: 0;

      image {
        width: 160rpx;
        height: 200rpx;
        border-radius: 10rpx;
      }

      .activity-text {
        display: block;
        width: 160rpx;
        font-size: 28rpx;
        color: #333;
        padding-top: 10rpx;
        line-height: 40rpx;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
}

.book-block {
  padding: 20rpx 20rpx 0;
  .book-tab-one {
    display: flex;
    align-items: center;

    .tab-one-item {
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #d7ece8;
      border-radius: 15rpx;
      margin-right: 15rpx;
      text-align: center;
      min-width: 25%;
      height: 160rpx;
      flex-shrink: 0;

      text {
        display: flex;
        width: 98%;
        font-size: 32rpx;
        color: #55aa7f;
        line-height: 50rpx;
        overflow: hidden;
      }
    }

    .tab-one-item:last-child {
      margin-right: 0;
    }

    .tab-one-active {
      background-color: #55aa7f;

      text {
        color: #fff;
      }
    }
  }

  .book-tab-two {
    display: flex;
    align-items: center;
    height: 70rpx;
    border-radius: 10rpx;

    .tab-two-item {
      min-width: 25%;
      display: flex;
      align-items: center;
      justify-content: center;
      border-right: 1rpx solid #acacac33;
      flex-shrink: 0;

      text {
        display: block;
        text-align: center;
        width: 165rpx;
        font-size: 28rpx;
        line-height: 48rpx;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }

    .tab-two-item:last-child {
      border-right: none;
    }

    .tab-two-active {
      text {
        color: #55aa7f;
        font-weight: bold;
      }
    }
  }

  .book-list {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;

    .book-item {
      width: 49%;
      background-color: #fff;
      border-radius: 15rpx;
      height: 575rpx;
      position: relative;
      margin-bottom: 20rpx;

      image {
        width: 85%;
        margin: 25rpx auto 0;
        border-radius: 15rpx;
        height: 380rpx;
        display: block;
      }

      .book-text {
        display: block;
        font-size: 28rpx;
        color: #333;
        line-height: 36rpx;
        width: 80%;
        margin: 15rpx auto 0;
        max-height: 72rpx;
        overflow: hidden;
      }

      .book-price-container {
        width: 80%;
        margin: 15rpx auto 0;
      }
    }
  }
}

.zanwu {
  display: block;
  text-align: center;
  font-size: 28rpx;
  color: #999;
  padding: 40rpx 0;
}

.scroll-view {
  white-space: nowrap;
}
</style>
