<template>
  <view class="activity-container">
    <view class="fixed-content">
      <!-- 顶部地块信息卡片 -->
      <view class="plot-info-card">
        <view class="plot-header">
          <text class="plot-name">{{ plotData.name || '未选择地块'}}</text>
          <text class="plot-area">{{ plotData.size || 0 }}亩</text>
        </view>
        <view class="plot-details">
          <view class="plot-item">
            <text class="item-label">作物：</text>
            <text class="item-value">{{ plotData.growCrops || '未选择地块' }}</text>
          </view>
          <view class="plot-item">
            <text class="item-label">负责人：</text>
            <text class="item-value">{{ plotData.managerName || '未选择地块'}}</text>
          </view>
        </view>
      </view>

      <!-- 任务状态筛选 -->
      <view class="tab-filter">
        <view class="tab-container">
            <view 
              class="tab-item" 
              v-for="(status, index) in taskStatus" 
              :key="index"
              :class="{ active: currentStatus === status.value }"
              @click="switchStatus(status.value)"
            >
              <text>{{ status.label }}</text>
              <view class="badge" v-if="status.value === 0 && pendingTaskCount > 0">
                {{ pendingTaskCount > 99 ? '99+' : pendingTaskCount }}
              </view>
              <view class="active-line" v-if="currentStatus === status.value"></view>
            </view>
          </view>
      </view>
    </view>

    <!-- 任务列表 - 可滚动区域 -->
   <scroll-view class="task-list-scroll" scroll-y lower-threshold="120"
      @scrolltolower="loadMore" 
      @refresherrefresh="refreshData" 
      refresher-enabled
      :refresher-triggered="isRefreshing">
      <view class="task-list">
        <view class="task-card" v-for="(task, index) in taskList" :key="task.id" @click="viewTaskDetail(task)">
          <!-- 头部区域：任务名称和状态标签 -->
          <view class="task-header">
            <view class="task-name">{{ task.taskName }}</view>
            <dict-tag 
              dict-type="task_status" 
              :value="task.taskStatus"
              class="task-status-tag"
            />
          </view>
          
          <!-- 信息行：类型、时间、责任人统一放在一行，类型在前 -->
          <view class="task-info-row">
            <!-- 类型标签放在最左侧 -->
            <view class="info-type">
              <image src="/static/icons/task_icon.png" mode="aspectFit" class="info-icon"></image>
              <dict-tag 
                dict-type="task_type" 
                :value="task.typeName"
                :colored="false"
                class="info-type-tag"
              />
            </view>
            
            <!-- 时间信息放在中间 -->
            <view class="info-time">
              <image src="/static/icons/clock_icon.png" mode="aspectFit" class="info-icon"></image>
              <text class="info-text">{{ formatDate(task.executeTime) }}</text>
            </view>
            
            <!-- 责任人信息放在右侧 -->
            <view class="info-person">
              <image src="/static/icons/user.png" mode="aspectFit" class="info-icon"></image>
              <text class="info-text">{{ task.assigneeName || '未分配' }}</text>
            </view>
          </view>
          
          <!-- 备注区域 -->
          <view class="task-remark" v-if="task.remark" @click.stop="toggleRemark(index)">
            <text class="remark-label">备注：</text>
            <text class="remark-content" :class="{'remark-expanded': task.remarkExpanded}">{{ task.remark }}</text>
            <text class="expand-btn" v-if="task.remark.length > 50 && !task.remarkExpanded">展开</text>
            <text class="expand-btn" v-if="task.remarkExpanded">收起</text>
          </view>
        </view>
        
        <view class="loading-more" v-if="isLoading">
          <view class="loading-icon"></view>
          <text>加载中...</text>
        </view>
        <view class="no-more-data" v-if="noMoreData && taskList.length > 0">
          <text>没有更多数据了</text>
        </view>
        <view class="empty-list" v-if="taskList.length === 0 && !isLoading">
          <image src="/static/icons/warning_icon.png" mode="aspectFit"></image>
          <text>暂无农事任务</text>
        </view>
      </view>
    </scroll-view>

    <!-- 新增任务按钮 -->
    <view class="add-task-button" @click="createNewTask">
      <image src="/static/icons/add_task.png" mode="aspectFit" class="add-icon"></image>
    </view>
  </view>
</template>

<script>
import storage from "@/utils/storage.js";
import { getAgriculturalTasksList, countStatusTypeTasks } from '@/api/services/activity.js';
import dictMixin from '@/utils/mixins/dictMixin';
import DictTag from '@/components/common/dict-tag';

export default {
  components: {
    DictTag
  },
  mixins: [dictMixin],
  data() {
    return {
      // 需要加载的字典类型
      dictTypeList: ['task_type','task_status'],
      
      // 地块数据
      plotData: {
        
      },

      // 待完成任务数
      pendingTaskCount: 0,

      // 当前筛选状态
      currentStatus: 'all',

      // 筛选相关数据
      taskStatus: [
        { label: '全部', value: 'all' },
        { label: '待完成', value: 0 },
        { label: '已完成', value: 1 }
      ],
      
      // 任务列表数据
      taskList: [],
      isLoading: false,
      isRefreshing: false,
      noMoreData: false,
      pageNum: 1,
      pageSize: 10,
    }
  },
  
  methods: {
    // 格式化日期
    formatDate(dateStr) {
      if (!dateStr) return '';
      
      // 如果是时间戳，转换为日期对象
      let date;
      if (typeof dateStr === 'number') {
        date = new Date(dateStr);
      } else {
        date = new Date(dateStr.replace(/-/g, '/'));
      }
      
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      
      return `${year}-${month}-${day}`;
    },
    
    // 切换任务状态筛选
    switchStatus(status) {
      if (this.currentStatus === status) return;
      
      this.currentStatus = status;
      this.pageNum = 1;
      this.noMoreData = false;
      this.loadTaskData();
    },
    
    // 加载任务数据
    loadTaskData() {
      // this.plotData = JSON.parse(storage.getPlots() || '{}')
	  this.plotData = JSON.parse(storage.getPlots() || '{}')
	  const plotId = this.plotData?.id;
	  // 判断地块是否存在且有 id
	  if (plotId == undefined) {
	    uni.showToast({
	      title: '请选择地块！',
	      icon: 'none'
	    });
	    return
	  }
	  console.log("this.plotData",this.plotData);
      this.isLoading = true;
      
      // 构建查询参数
      const params = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        plotId: plotId
      };
      
      // 如果不是查询全部，添加状态过滤条件
      if (this.currentStatus !== 'all') {
        params.taskStatus = this.currentStatus;
      }
      
      getAgriculturalTasksList(params).then(res => {
        if (res.data.code === 200) {
          const { rows, total } = res.data;
          
          // 处理返回的数据
          const tasks = rows.map(item => {
            // 确保每个任务都有remarkExpanded属性
            item.remarkExpanded = false;
            return item;
          });
          
          if (this.pageNum === 1) {
            this.taskList = tasks;
          } else {
            this.taskList = [...this.taskList, ...tasks];
          }
          
          // 判断是否还有更多数据
          this.noMoreData = this.taskList.length >= total;
          
          // 统计待完成任务数量
          this.countPendingTasks();
        } else {
          uni.showToast({
            title: res.data.msg || '获取任务列表失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error('获取任务列表失败:', err);
        uni.showToast({
          title: '获取任务列表失败',
          icon: 'none'
        });
      }).finally(() => {
        this.isLoading = false;
        this.isRefreshing = false;
      });
    },
    
    // 统计待完成任务数量
    countPendingTasks() {
      // 如果当前已经是按状态筛选，直接使用当前列表长度
      if (this.currentStatus === 'pending') {
        this.pendingTaskCount = this.taskList.length;
        return;
      }
      
      // 否则，请求获取待完成任务数量
      const params = {
        plotId: this.plotData.id,
        taskStatus: 0
      };
      
      countStatusTypeTasks(params).then(res => {
		  console.log("nongsh",res);
        if (res.data.code === 200) {
          this.pendingTaskCount = res.data.data || 0;
        }
      });
    },

    // 下拉刷新
    refreshData(plotId) {
      this.isRefreshing = true;
      this.pageNum = 1;
      this.noMoreData = false;
      this.loadTaskData(plotId);
    },

    // 上拉加载更多
    loadMore() {
      if (!this.isLoading && !this.noMoreData) {
        this.pageNum++;
        this.loadTaskData();
      }
    },

    // 查看任务详情
    viewTaskDetail(task) {
      // 根据任务状态决定跳转到不同模式的页面
      let mode = '';
      if (task.taskStatus === '0') {
        // 待完成任务跳转到编辑页面
        mode = 'edit';
      } else if (task.taskStatus === '1') {
        // 已完成任务跳转到查看页面
        mode = 'view';
      }
      console.log("this.plotData",this.plotData);
      // 使用简化的URL参数传递
      const url = `/pages/activity/activity-detail?id=${task.id}&mode=${mode}&fieldName=${encodeURIComponent(this.plotData.name)}&growCrops=${encodeURIComponent(this.plotData.growCrops)}&farmId=${encodeURIComponent(this.plotData.farmId)}&manager=${encodeURIComponent(this.plotData.managerName)}&plotId=${this.plotData.id}`;
      
      uni.navigateTo({
        url: url
      });
    },

    // 创建新任务
    createNewTask() {
      // 使用简化的URL参数传递
      const url = `/pages/activity/activity-detail?id=new&mode=create&fieldName=${encodeURIComponent(this.plotData.name)}&growCrops=${encodeURIComponent(this.plotData.growCrops)}&farmId=${encodeURIComponent(this.plotData.farmId)}&manager=${encodeURIComponent(this.plotData.managerName)}&plotId=${this.plotData.id}`;
      
      uni.navigateTo({
        url: url
      });
    },
    
    // 切换备注展开/收起状态
    toggleRemark(index) {
      if (this.taskList[index].remark && this.taskList[index].remark.length > 50) {
        this.$set(this.taskList[index], 'remarkExpanded', !this.taskList[index].remarkExpanded);
      }
    }
  },
  
  // 页面加载时获取数据
  onLoad() {
	this.loadTaskData();
  },
  
  // 页面显示时刷新数据
  onShow() {
	this.refreshData()
  }
}
</script>

<style scoped>
.activity-container {
  position: relative;
  height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 固定内容区域 */
.fixed-content {
  flex-shrink: 0;
  width: 100%;
}

/* 地块信息卡片 */
.plot-info-card {
  margin: 20rpx 30rpx 30rpx;
  padding: 30rpx;
  background: linear-gradient(135deg, #3BB44A, #2D8C3C);
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(59, 180, 74, 0.2);
  position: relative;
  color: #fff;
  width: calc(100% - 60rpx);
  box-sizing: border-box;
}

.plot-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.plot-name {
  font-size: 32rpx;
  font-weight: bold;
}

.plot-area {
  font-size: 28rpx;
  background-color: rgba(255, 255, 255, 0.2);
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
}

.plot-details {
  display: flex;
  flex-wrap: wrap;
}

.plot-item {
  display: flex;
  align-items: center;
  margin-right: 40rpx;
  margin-bottom: 10rpx;
}

.item-label {
  font-size: 26rpx;
  opacity: 0.8;
}

.item-value {
  font-size: 28rpx;
  font-weight: 500;
}

/* 任务状态筛选 */
.tab-filter {
  margin: 0 30rpx 20rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
  z-index: 10;
  width: calc(100% - 60rpx);
  box-sizing: border-box;
}

.tab-container {
  display: flex;
  width: 100%;
  height: 90rpx;
}

.tab-item {
  flex: 1;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-width: 150rpx;
  transition: all 0.3s ease;
}

.tab-item text {
  font-size: 28rpx;
  color: #666;
  transition: color 0.3s ease;
}

.tab-item.active text {
  color: #3BB44A;
  font-weight: bold;
}

.active-line {
  position: absolute;
  bottom: 0;
  left: 25%;
  width: 50%;
  height: 4rpx;
  background-color: #3BB44A;
  border-radius: 4rpx;
  transition: all 0.3s ease;
}

.badge {
  position: absolute;
  top: 16rpx;
  right: 20%;
  min-width: 32rpx;
  height: 32rpx;
  line-height: 32rpx;
  border-radius: 16rpx;
  background: linear-gradient(135deg, #FF5252, #FF7676);
  color: #fff;
  font-size: 20rpx;
  padding: 0 8rpx;
  text-align: center;
  box-shadow: 0 2rpx 4rpx rgba(255, 82, 82, 0.2);
  transform: scale(0.9);
}

/* 滚动区域 */
.task-list-scroll {
  flex: 1;
  height: 0; /* 关键属性：使滚动区域占据剩余高度 */
  overflow: hidden;
}

.task-list {
  padding: 0 30rpx;
  /* 预留底部空间，避免被悬浮新增按钮遮挡，并兼容安全区 */
  padding-bottom: 160rpx;
  padding-bottom: calc(160rpx + constant(safe-area-inset-bottom));
  padding-bottom: calc(160rpx + env(safe-area-inset-bottom));
  box-sizing: border-box;
  width: 100%;
}

.task-card {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  position: relative;
  transition: transform 0.3s ease;
  width: calc(100% - 0rpx);
  box-sizing: border-box;
  overflow: hidden;
}

.task-card:active {
  transform: scale(0.98);
}

/* 任务卡片头部样式优化 */
.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
}

.task-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  padding-right: 80rpx; /* 为右侧状态标签留出空间 */
}

.task-status {
  position: absolute;
  top: 24rpx;
  right: 24rpx;
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
  background: linear-gradient(135deg, rgba(255, 82, 82, 0.8), rgba(255, 82, 82, 0.6));
  color: #fff;
  z-index: 1;
  max-width: 120rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.status-completed {
  background: linear-gradient(135deg, rgba(59, 180, 74, 0.8), rgba(59, 180, 74, 0.6));
}

/* 信息行样式优化 */
.task-info-row {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  padding: 6rpx 0;
  width: 100%;
}

.info-type, .info-time, .info-person {
  display: flex;
  align-items: center;
}

.info-type {
  flex: 0 0 auto;
  margin-right: 30rpx;
}

.info-time {
  flex: 0 0 auto;
  margin-right: 30rpx;
}

.info-person {
  flex: 0 0 auto;
  min-width: 100rpx;
}

.info-icon {
  width: 28rpx;
  height: 28rpx;
  margin-right: 8rpx;
  opacity: 0.7;
  flex-shrink: 0;
}

.info-text {
  font-size: 26rpx;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 删除旧的类型标签样式 */
.type-tag {
  display: none;
}

.task-remark {
  background-color: rgba(0, 0, 0, 0.03);
  padding: 16rpx;
  border-radius: 10rpx;
  display: flex;
  margin-bottom: 10rpx;
  position: relative;
  flex-wrap: wrap;
}

.remark-label {
  font-size: 26rpx;
  color: #999;
  margin-right: 8rpx;
}

.remark-content {
  flex: 1;
  font-size: 26rpx;
  color: #666;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}

.remark-expanded {
  -webkit-line-clamp: unset;
  line-clamp: unset;
}

.expand-btn {
  font-size: 24rpx;
  color: #3BB44A;
  margin-left: auto;
  padding-left: 20rpx;
}

.loading-more, .no-more-data, .empty-list {
  text-align: center;
  padding: 30rpx 0;
}

.loading-icon {
  display: inline-block;
  width: 40rpx;
  height: 40rpx;
  border: 3rpx solid #f3f3f3;
  border-top: 3rpx solid #3BB44A;
  border-radius: 50%;
  vertical-align: middle;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-more text, .no-more-data text {
  font-size: 24rpx;
  color: #999;
  margin-left: 10rpx;
}

.empty-list {
  padding: 100rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.empty-list image {
  width: 120rpx;
  height: 120rpx;
  margin-bottom: 20rpx;
  opacity: 0.5;
}

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

/* 新增任务按钮 */
.add-task-button {
  position: fixed;
  right: 40rpx;
  bottom: 120rpx;
  width: 100rpx;
  height: 100rpx;
  border-radius: 50%;
  background: linear-gradient(135deg, #3BB44A, #2D8C3C);
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 6rpx 16rpx rgba(59, 180, 74, 0.3);
  z-index: 100;
  transition: transform 0.2s ease;
}

.add-task-button:active {
  transform: scale(0.95);
}

.add-icon {
  width: 48rpx;
  height: 48rpx;
}

/* 添加字典标签相关样式 */
.task-status-tag {
  position: absolute;
  top: 24rpx;
  right: 24rpx;
  z-index: 1;
  max-width: 120rpx;
}

/* 移除空规则 .info-type-tag 以避免 linter 警告 */
</style>