<template>
  <view class="page-container">
    <!-- 顶部标签导航 -->
    <view class="header-tabs">
      <view 
        class="tab-item" 
        :class="{ active: currentTab === 0 }" 
        @click="handleTabChange(0)"
      >
        <text>农技知识</text>
        <view class="tab-line" :class="{ active: currentTab === 0 }"></view>
      </view>
      <view 
        class="tab-item" 
        :class="{ active: currentTab === 1 }" 
        @click="handleTabChange(1)"
      >
        <text>政策解读</text>
        <view class="tab-line" :class="{ active: currentTab === 1 }"></view>
      </view>
    </view>

    <!-- 内容区域 -->
    <scroll-view
      scroll-y
      class="content-container"
      @scrolltolower="loadMore"
	  @refresherrefresh="onRefresh"
      refresher-enabled
      :refresher-triggered="isRefreshing"
    >
      <!-- 主内容区域 -->
      <view class="cards-section">
        <!-- 农技知识内容 -->
        <block v-if="currentTab === 0">
          <navigator 
            class="content-card"
            v-for="(item, index) in techList"
            :key="`tech-${item.id}-${index}`"
            :url="`/pages/knowledge/detail?id=${item.id}&type=tech`"
            hover-class="card-hover"
          >
            <view class="content-thumbnail">
              <image 
                :src="item.imageUrl" 
                mode="aspectFill"
                class="thumbnail-image"
                lazy-load
              />
              <!-- 仅视频类型显示时长和播放按钮 -->
              <template v-if="item.contentType === 'video'">
                <view class="video-duration">{{ item.duration || '00:00' }}</view>
                <view class="play-button">
                  <view class="play-icon"></view>
                </view>
                <view class="content-type-tag video">视频</view>
              </template>
              <!-- 文章类型显示标签 -->
              <template v-else>
                <view class="content-type-tag article">文章</view>
              </template>
            </view>
            <view class="content-info">
              <text class="content-title">{{ item.title }}</text>
              <view class="info-row">
                <text class="source-name">{{ item.source }}</text>
                <view class="view-count">
                  <image src="@/static/icons/read.png" style="width: 30rpx;height: 30rpx;"></image>
                  <text>{{ item.viewCount }}</text>
                </view>
              </view>
            </view>
          </navigator>
        </block>

        <!-- 政策解读内容 -->
        <block v-if="currentTab === 1">
          <navigator 
            class="content-card"
            v-for="(item, index) in policyList"
            :key="`policy-${item.id}-${index}`"
            :url="`/pages/knowledge/detail?id=${item.id}&type=policy`"
            hover-class="card-hover"
          >
            <view class="content-thumbnail">
              <image 
                :src="item.imageUrl" 
                mode="aspectFill"
                class="thumbnail-image"
                lazy-load
              />
              <!-- 仅视频类型显示时长和播放按钮 -->
              <template v-if="item.contentType === 'video'">
                <view class="video-duration">{{ item.duration || '00:00' }}</view>
                <view class="play-button">
                  <view class="play-icon"></view>
                </view>
                <view class="content-type-tag video">视频</view>
              </template>
              <!-- 文章类型显示标签 -->
              <template v-else>
                <view class="content-type-tag article">文章</view>
              </template>
            </view>
            <view class="content-info">
              <text class="content-title">{{ item.title }}</text>
              <view class="info-row">
                <text class="source-name">{{ item.source }}</text>
                <view class="view-count">
                  <image src="@/static/icons/read.png" style="width: 30rpx;height: 30rpx;"></image>
                  <text>{{ item.viewCount }}</text>
                </view>
              </view>
            </view>
          </navigator>
        </block>

        <!-- 加载中状态 -->
        <view class="loading-state" v-if="loading">
          <view class="spinner"></view>
          <text class="loading-text">加载中...</text>
        </view>

        <!-- 无数据状态 -->
        <view class="empty-state" v-if="!loading && ((currentTab === 0 && techList.length === 0) || (currentTab === 1 && policyList.length === 0))">
          <image src="/static/images/empty.png" mode="aspectFit" class="empty-image"></image>
          <text class="empty-text">暂无数据</text>
        </view>
      </view>

      <!-- 底部安全区域 -->
      <view style="height: 120rpx;"></view>
    </scroll-view>

    <!-- AI问答悬浮按钮 -->
    <view class="assistant-btn" @click="navigateToAI" hover-class="btn-hover">
      <image src="/static/icons/ai.png" class="assistant-icon" mode="aspectFit"></image>
      <text class="btn-text">问农小禹</text>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue'
import { getKnowledgeList } from "@/api/services/knowledge.js"
import { onShow } from '@dcloudio/uni-app'

// 当前标签
const currentTab = ref(0)

// 农技知识列表
const techList = ref([])

// 政策解读列表
const policyList = ref([])

// 分页参数
const techPageParams = reactive({
  page: 1,
  pageSize: 10,
  hasMore: true
})

const policyPageParams = reactive({
  page: 1,
  pageSize: 10,
  hasMore: true
})

// 刷新加载状态
const isRefreshing = ref(false)
const loading = ref(false)

// 处理Tab切换
const handleTabChange = (index) => {
  if (currentTab.value === index) return
  
  currentTab.value = index
  console.log('Tab changed to:', index)
  
  // 如果切换到的标签没有数据，则加载数据
  if (index === 0 && techList.value.length === 0) {
    fetchTechKnowledge()
  } else if (index === 1 && policyList.value.length === 0) {
    fetchPolicyData()
  }
}

// 获取农技知识数据
const fetchTechKnowledge = async (refresh = false) => {
  if (refresh) {
    techPageParams.page = 1
    techPageParams.hasMore = true
  }
  
  // 如果没有更多数据则不请求
  if (!techPageParams.hasMore && !refresh) return
  
  loading.value = true
  
  try {
    // 构建请求参数
    const params = {
        pageNum: techPageParams.page,
        pageSize: techPageParams.pageSize,
        contentCategory: 'tech'
    };
    
    // 发起请求
    await getKnowledgeList(params).then(response => {
      console.log("response农技", response)
      // 解析响应
      if (response.data.data && response.data.code === 200) {
        const { list, total } = response.data.data
        
        if (refresh) {
          techList.value = list || []
        } else {
          techList.value = [...techList.value, ...(list || [])]
        }
        console.log("techList", techList.value)
        // 更新分页状态
        techPageParams.page++
        techPageParams.hasMore = techList.value.length < total
      } else {
        uni.showToast({
          title: (response.data && response.data.message) || '获取数据失败',
          icon: 'none'
        })
      }
    }).catch(err => [err, null])
       
  } catch (error) {
    console.error('获取农技知识数据失败:', error)
    uni.showToast({
      title: '网络异常，请稍后再试',
      icon: 'none'
    })
  } finally {
    loading.value = false
    if (refresh) {
      isRefreshing.value = false
    }
    
    // 如果加载完成后没有更多数据，并且不是刷新操作，显示提示
    if (!techPageParams.hasMore && !refresh && techList.value.length > 0) {
      uni.showToast({
        title: '已加载全部内容',
        icon: 'none',
        duration: 2000
      })
    }
  }
}

// 获取政策解读数据
const fetchPolicyData = async (refresh = false) => {
  if (refresh) {
    policyPageParams.page = 1
    policyPageParams.hasMore = true
  }
  
  // 如果没有更多数据则不请求
  if (!policyPageParams.hasMore && !refresh) return
  
  loading.value = true
  
  try {
	// 构建请求参数
    const params = {
        pageNum: policyPageParams.page,
        pageSize: policyPageParams.pageSize,
        contentCategory: 'policy'
    };
    
    // 发起请求
    getKnowledgeList(params).then(response => {
      console.log("response农技333", response)
      // 解析响应
      if (response.data.data && response.data.code === 200) {
        const { list, total } = response.data.data
        
        if (refresh) {
          policyList.value = list || []
        } else {
          policyList.value = [...policyList.value, ...(list || [])]
        }
        console.log("policyList", policyList.value)
        // 更新分页状态
        policyPageParams.page++
        policyPageParams.hasMore = policyList.value.length < total
      } else {
        uni.showToast({
          title: (response.data && response.data.message) || '获取数据失败',
          icon: 'none'
        })
      }
    }).catch(err => [err, null])
  } catch (error) {
    console.error('获取政策解读数据失败:', error)
    uni.showToast({
      title: '网络异常，请稍后再试',
      icon: 'none'
    })
  } finally {
    loading.value = false
    if (refresh) {
      isRefreshing.value = false
    }
    
    // 如果加载完成后没有更多数据，并且不是刷新操作，显示提示
    if (!policyPageParams.hasMore && !refresh && policyList.value.length > 0) {
      uni.showToast({
        title: '已加载全部内容',
        icon: 'none',
        duration: 2000
      })
    }
  }
}

// 下拉刷新
const onRefresh = async () => {
  isRefreshing.value = true
  
  if (currentTab.value === 0) {
    // 刷新农技知识数据
    await fetchTechKnowledge(true)
  } else {
    // 刷新政策解读数据
    await fetchPolicyData(true)
  }
}

// 加载更多
const loadMore = () => {
  if (loading.value) return
  
  console.log('Loading more content')
  
  if (currentTab.value === 0) {
    // 检查是否还有更多农技知识数据
    if (!techPageParams.hasMore) {
      uni.showToast({
        title: '已加载全部内容',
        icon: 'none',
        duration: 2000
      })
      return
    }
    // 加载更多农技知识数据
    fetchTechKnowledge()
  } else {
    // 检查是否还有更多政策解读数据
    if (!policyPageParams.hasMore) {
      uni.showToast({
        title: '已加载全部内容',
        icon: 'none',
        duration: 2000
      })
      return
    }
    // 加载更多政策解读数据
    fetchPolicyData()
  }
}

// 跳转AI问答
const navigateToAI = () => {
  uni.navigateTo({
    url: '/pages/knowledge/ai-chat/index'
  })
}

// 处理文章阅读量更新
const handleViewCountUpdate = (data) => {
  if (!data || !data.id) return
  
  // 更新技术文章列表中的阅读量
  if (data.type === 'tech' || !data.type) {
    const index = techList.value.findIndex(item => item.id === data.id)
    if (index !== -1) {
      techList.value[index].viewCount = data.viewCount
    }
  }
  
  // 更新政策解读列表中的阅读量
  if (data.type === 'policy') {
    const index = policyList.value.findIndex(item => item.id === data.id)
    if (index !== -1) {
      policyList.value[index].viewCount = data.viewCount
    }
  }
}

// 页面加载完成
onMounted(() => {
  console.log('Page mounted, current tab:', currentTab.value)
  // 初始加载数据
  fetchTechKnowledge()
  
  // 监听文章阅读量更新事件
  uni.$on('updateArticleViewCount', handleViewCountUpdate)
})

// 页面显示时触发
onShow(() => {
  // 获取当前页面路由信息，判断是否是从详情页返回
  const pages = getCurrentPages()
  if (pages.length > 1) {
    const prePage = pages[pages.length - 2]
    // 如果前一个页面是详情页，检查是否需要刷新数据
    if (prePage && prePage.route && prePage.route.includes('knowledge/detail')) {
      console.log('从详情页返回，更新阅读量显示')
      // 由于已经通过事件机制更新了列表，这里只需要触发一下视图更新
      if (currentTab.value === 0) {
        techList.value = [...techList.value]
      } else {
        policyList.value = [...policyList.value]
      }
    }
  }
})

// 页面销毁前
onBeforeUnmount(() => {
  // 移除事件监听
  uni.$off('updateArticleViewCount', handleViewCountUpdate)
})
</script>

<style scoped>
/* 引入字体图标 */
@font-face {
  font-family: 'iconfont';
  src: url('//at.alicdn.com/t/font_3266846_kxscvlm9qpp.woff2') format('woff2');
}

.iconfont {
  font-family: "iconfont" !important;
  font-size: 22rpx;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.icon-robot:before {
  content: "\e64b";
}

.icon-eye:before {
  content: "\e614";
}

/* 页面容器 */
.page-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  position: relative;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
}

/* 头部标签样式 */
.header-tabs {
  display: flex;
  background-color: #fff;
  padding: 0 30rpx;
  position: relative;
  border-bottom: 1rpx solid #f2f2f2;
}

.tab-item {
  position: relative;
  padding: 20rpx 30rpx;
  margin-right: 50rpx;
  font-size: 30rpx;
  color: #666;
  transition: all 0.3s ease;
}

.tab-item.active {
  color: #333;
  font-weight: 600;
}

.tab-line {
  position: absolute;
  bottom: 0;
  left: 50%;
  width: 0;
  height: 6rpx;
  background-color: #4dc971;
  border-radius: 3rpx;
  transition: all 0.3s ease;
  transform: translateX(-50%);
}

.tab-line.active {
  width: 40rpx;
}

/* 内容区域样式 */
.content-container {
  height: calc(100vh - 88rpx);
  box-sizing: border-box;
}

.cards-section {
  padding: 12rpx;
}

/* 内容卡片通用样式 */
.content-card {
  background-color: #fff;
  border-radius: 16rpx;
  margin-bottom: 24rpx;
  overflow: hidden;
  transition: all 0.2s ease;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
  position: relative;
}

.card-hover {
  transform: translateY(-2rpx);
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.12);
}

/* 缩略图 */
.content-thumbnail {
  position: relative;
  width: 100%;
  height: 300rpx;
  background-color: #f0f0f0;
}

.thumbnail-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

/* 播放按钮 */
.play-button {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 70rpx;
  height: 70rpx;
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
}

.play-icon {
  width: 0;
  height: 0;
  border-style: solid;
  border-width: 9rpx 0 9rpx 16rpx;
  border-color: transparent transparent transparent #ffffff;
  margin-left: 4rpx;
}

/* 视频时长 */
.video-duration {
  position: absolute;
  bottom: 10rpx;
  right: 10rpx;
  padding: 3rpx 8rpx;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  font-size: 18rpx;
  border-radius: 10rpx;
}

/* 内容类型标签 */
.content-type-tag {
  position: absolute;
  top: 10rpx;
  left: 10rpx;
  padding: 4rpx 10rpx;
  font-size: 20rpx;
  border-radius: 6rpx;
  z-index: 2;
}

.content-type-tag.video {
  background-color: #4dc971;
  color: #fff;
}

.content-type-tag.article {
  background-color: #3498db;
  color: #fff;
}

/* 内容信息 */
.content-info {
  padding: 16rpx;
  position: relative;
}

.content-title {
  font-size: 30rpx;
  font-weight: 600;
  color: #333;
  line-height: 1.4;
  margin-bottom: 10rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.source-name {
  color: #999;
  font-size: 22rpx;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.view-count {
  color: #c0c0c0;
  font-size: 20rpx;
  display: flex;
  align-items: center;
}

.view-count .iconfont {
  margin-right: 4rpx;
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-image {
  width: 180rpx;
  height: 180rpx;
  margin-bottom: 16rpx;
}

.empty-text {
  font-size: 26rpx;
  color: #999;
}

/* 加载中状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 30rpx 0;
}

.spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid rgba(77, 201, 113, 0.2);
  border-radius: 50%;
  border-top-color: #4dc971;
  animation: spin 0.8s linear infinite;
  margin-bottom: 16rpx;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.loading-text {
  font-size: 24rpx;
  color: #999;
}

/* AI按钮 */
.assistant-btn {
  position: fixed;
  right: 30rpx;
  bottom: 100rpx;
  height: 80rpx;
  border-radius: 40rpx;
  background: linear-gradient(135deg, #42b983, #3db160);
  display: flex;
  align-items: center;
  padding: 0 24rpx;
  box-shadow: 0 6rpx 20rpx rgba(66, 185, 131, 0.35);
  z-index: 99;
  transition: all 0.25s ease;
}

.assistant-icon {
  width: 68rpx;
  height: 68rpx;
  margin-right: 10rpx;
}

.btn-hover {
  transform: scale(1.05);
  box-shadow: 0 8rpx 24rpx rgba(66, 185, 131, 0.45);
}

.btn-text {
  font-size: 28rpx;
  color: #fff;
  font-weight: 500;
}
</style>