<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>
	import {getKnowledgeList} from "@/api/services/knowledge.js";
export default {
  data() {
    return {
      // 当前标签
      currentTab: 0,
      
      // 农技知识列表
      techList: [],
      
      // 政策解读列表
      policyList: [],
      
      // 分页参数
      techPageParams: {
        page: 1,
        pageSize: 10,
        hasMore: true
      },
      
      policyPageParams: {
        page: 1,
        pageSize: 10,
        hasMore: true
      },
      
      // 刷新加载状态
      isRefreshing: false,
      loading: false
    };
  },
  
  // 监听标签切换
  // watch: {
  //   currentTab(newVal) {
  //     if (newVal === 0 && this.techList.length === 0) {
  //       this.fetchTechKnowledge();
  //     } else if (newVal === 1 && this.policyList.length === 0) {
  //       this.fetchPolicyData();
  //     }
  //   }
  // },
  
  // 页面加载完成
  mounted() {
    console.log('Page mounted, current tab:', this.currentTab);
    // 初始加载数据
    this.fetchTechKnowledge();
    
    // 监听文章阅读量更新事件
    uni.$on('updateArticleViewCount', this.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 (this.currentTab === 0) {
          this.techList = [...this.techList];
        } else {
          this.policyList = [...this.policyList];
        }
      }
    }
  },
  
  // 页面销毁前
  beforeDestroy() {
    // 移除事件监听
    uni.$off('updateArticleViewCount', this.handleViewCountUpdate);
  },
  
  methods: {
    // 处理Tab切换
    handleTabChange(index) {
      if (this.currentTab === index) return;
      
      this.currentTab = index;
      console.log('Tab changed to:', index);
      
      // 如果切换到的标签没有数据，则加载数据
      if (index === 0 && this.techList.length === 0) {
        this.fetchTechKnowledge();
      } else if (index === 1 && this.policyList.length === 0) {
        this.fetchPolicyData();
      }
    },
    
    // 获取农技知识数据
    async fetchTechKnowledge(refresh = false) {
      if (refresh) {
        this.techPageParams.page = 1;
        this.techPageParams.hasMore = true;
      }
      
      // 如果没有更多数据则不请求
      if (!this.techPageParams.hasMore && !refresh) return;
      
      this.loading = true;
      
      try {
        // 构建请求参数
        const params = {
          page: this.techPageParams.page,
          pageSize: this.techPageParams.pageSize,
          category: '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) {
			    this.techList = list || [];
			  } else {
			    this.techList = [...this.techList, ...(list || [])];
			  }
			  console.log("techList",this.techList);
			  // 更新分页状态
			  this.techPageParams.page++;
			  this.techPageParams.hasMore = this.techList.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 {
        this.loading = false;
        if (refresh) {
          this.isRefreshing = false;
        }
        
        // 如果加载完成后没有更多数据，并且不是刷新操作，显示提示
        if (!this.techPageParams.hasMore && !refresh && this.techList.length > 0) {
          uni.showToast({
            title: '已加载全部内容',
            icon: 'none',
            duration: 2000
          });
        }
      }
    },
    
    // 获取政策解读数据
    async fetchPolicyData(refresh = false) {
      if (refresh) {
        this.policyPageParams.page = 1;
        this.policyPageParams.hasMore = true;
      }
      
      // 如果没有更多数据则不请求
      if (!this.policyPageParams.hasMore && !refresh) return;
      
      this.loading = true;
      
      try {
        // 构建请求参数
        const params = {
          page: this.policyPageParams.page,
          pageSize: this.policyPageParams.pageSize,
          category: '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) {
			    this.policyList = list || [];
			  } else {
			    this.policyList = [...this.policyList, ...(list || [])];
			  }
			  console.log("this.policyList",this.policyList);
			  // 更新分页状态
			  this.policyPageParams.page++;
			  this.policyPageParams.hasMore = this.policyList.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 {
        this.loading = false;
        if (refresh) {
          this.isRefreshing = false;
        }
        
        // 如果加载完成后没有更多数据，并且不是刷新操作，显示提示
        if (!this.policyPageParams.hasMore && !refresh && this.policyList.length > 0) {
          uni.showToast({
            title: '已加载全部内容',
            icon: 'none',
            duration: 2000
          });
        }
      }
    },
    
    // 下拉刷新
    async onRefresh() {
      this.isRefreshing = true;
      
      if (this.currentTab === 0) {
        // 刷新农技知识数据
        await this.fetchTechKnowledge(true);
      } else {
        // 刷新政策解读数据
        await this.fetchPolicyData(true);
      }
    },
    
    // 加载更多
    loadMore() {
      if (this.loading) return;
      
      console.log('Loading more content');
      
      if (this.currentTab === 0) {
        // 检查是否还有更多农技知识数据
        if (!this.techPageParams.hasMore) {
          uni.showToast({
            title: '已加载全部内容',
            icon: 'none',
            duration: 2000
          });
          return;
        }
        // 加载更多农技知识数据
        this.fetchTechKnowledge();
      } else {
        // 检查是否还有更多政策解读数据
        if (!this.policyPageParams.hasMore) {
          uni.showToast({
            title: '已加载全部内容',
            icon: 'none',
            duration: 2000
          });
          return;
        }
        // 加载更多政策解读数据
        this.fetchPolicyData();
      }
    },
    
    // 跳转AI问答
    navigateToAI() {
      uni.navigateTo({
        url: '/pages/knowledge/ai-chat/index'
      });
    },
    
    // 处理文章阅读量更新
    handleViewCountUpdate(data) {
      if (!data || !data.id) return;
      
      // 更新技术文章列表中的阅读量
      if (data.type === 'tech' || !data.type) {
        const index = this.techList.findIndex(item => item.id === data.id);
        if (index !== -1) {
          this.techList[index].viewCount = data.viewCount;
        }
      }
      
      // 更新政策解读列表中的阅读量
      if (data.type === 'policy') {
        const index = this.policyList.findIndex(item => item.id === data.id);
        if (index !== -1) {
          this.policyList[index].viewCount = data.viewCount;
        }
      }
    }
  }
}
</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>