<template>
  <view class="page-container">
    <!-- 顶部用户信息 -->
    <view class="header-section">
      <view class="user-info" v-if="userInfo">
        <image class="avatar" :src="userInfo.avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
        <view class="user-details">
          <text class="username">{{ userInfo.name || '养殖户' }}</text>
          <text class="user-role">{{ userInfo.role || '普通用户' }}</text>
        </view>
      </view>
      <view class="weather-info" v-if="weatherData">
        <text class="weather-text">{{ weatherData.weather }}</text>
        <text class="temperature">{{ weatherData.temperature }}°C</text>
      </view>
    </view>

    <!-- 数据概览 -->
    <view class="stats-section">
      <view class="stats-grid">
        <view class="stat-item" v-for="(item, index) in statsData" :key="index" @click="onStatClick(item)">
          <view class="stat-icon" :style="{ backgroundColor: item.color }">
            <text class="iconfont" :class="item.icon"></text>
          </view>
          <view class="stat-info">
            <text class="stat-value">{{ item.value }}</text>
            <text class="stat-label">{{ item.label }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 快捷操作 -->
    <view class="quick-actions">
      <view class="section-title">
        <text class="title-text">快捷操作</text>
      </view>
      <view class="actions-grid">
        <view class="action-item" v-for="(action, index) in quickActions" :key="index" @click="onActionClick(action)">
          <view class="action-icon">
            <text class="iconfont" :class="action.icon"></text>
          </view>
          <text class="action-text">{{ action.name }}</text>
        </view>
      </view>
    </view>

    <!-- 最近活动 -->
    <view class="recent-activities">
      <view class="section-title">
        <text class="title-text">最近活动</text>
        <text class="more-text" @click="onViewAllActivities">查看全部</text>
      </view>
      <view class="activity-list">
        <view class="activity-item" v-for="(activity, index) in recentActivities" :key="index" @click="onActivityClick(activity)">
          <view class="activity-icon">
            <text class="iconfont" :class="activity.icon"></text>
          </view>
          <view class="activity-content">
            <text class="activity-title">{{ activity.title }}</text>
            <text class="activity-desc">{{ activity.description }}</text>
            <text class="activity-time">{{ $utils.formatTime(activity.time) }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载组件 -->
    <uni-load-more :status="loadStatus" :content-text="loadText"></uni-load-more>
  </view>
</template>

<script>
export default {
  name: 'Index',
  
  data() {
    return {
      userInfo: null,
      weatherData: null,
      statsData: [
        {
          label: '养殖场',
          value: 0,
          icon: 'icon-farm',
          color: '#2E8B57',
          type: 'farm'
        },
        {
          label: '动物总数',
          value: 0,
          icon: 'icon-animal',
          color: '#FF6B6B',
          type: 'animal'
        },
        {
          label: '健康率',
          value: '0%',
          icon: 'icon-health',
          color: '#4ECDC4',
          type: 'health'
        },
        {
          label: '本月收益',
          value: '¥0',
          icon: 'icon-money',
          color: '#45B7D1',
          type: 'income'
        }
      ],
      quickActions: [
        {
          name: '添加动物',
          icon: 'icon-add-animal',
          url: '/pages/animal/add'
        },
        {
          name: '健康记录',
          icon: 'icon-health-record',
          url: '/pages/health/record'
        },
        {
          name: '饲料管理',
          icon: 'icon-feed',
          url: '/pages/feed/index'
        },
        {
          name: '疫苗接种',
          icon: 'icon-vaccine',
          url: '/pages/vaccine/index'
        },
        {
          name: '生产记录',
          icon: 'icon-production',
          url: '/pages/production/index'
        },
        {
          name: '销售记录',
          icon: 'icon-sale',
          url: '/pages/sale/index'
        }
      ],
      recentActivities: [],
      loadStatus: 'loading',
      loadText: {
        contentdown: '上拉显示更多',
        contentrefresh: '正在加载...',
        contentnomore: '没有更多数据了'
      }
    }
  },
  
  onLoad() {
    this.initPage()
  },
  
  onShow() {
    this.refreshData()
  },
  
  onPullDownRefresh() {
    this.refreshData().finally(() => {
      uni.stopPullDownRefresh()
    })
  },
  
  methods: {
    // 初始化页面
    async initPage() {
      try {
        await this.checkLogin()
        await this.loadData()
      } catch (error) {
        console.error('初始化页面失败：', error)
      }
    },
    
    // 检查登录状态
    async checkLogin() {
      const token = uni.getStorageSync('token')
      if (!token) {
        uni.navigateTo({
          url: '/pages/auth/login'
        })
        return Promise.reject('未登录')
      }
      
      // 获取用户信息
      try {
        const userInfo = uni.getStorageSync('userInfo')
        if (userInfo) {
          this.userInfo = userInfo
        }
      } catch (error) {
        console.error('获取用户信息失败：', error)
      }
    },
    
    // 加载数据
    async loadData() {
      this.loadStatus = 'loading'
      
      try {
        await Promise.all([
          this.loadStatsData(),
          this.loadWeatherData(),
          this.loadRecentActivities()
        ])
        
        this.loadStatus = 'noMore'
      } catch (error) {
        console.error('加载数据失败：', error)
        this.loadStatus = 'noMore'
        uni.showToast({
          title: '加载数据失败',
          icon: 'none'
        })
      }
    },
    
    // 刷新数据
    async refreshData() {
      return this.loadData()
    },
    
    // 加载统计数据
    async loadStatsData() {
      try {
        const res = await this.$request({
          url: '/farming/stats',
          method: 'GET'
        })
        
        if (res.data) {
          this.statsData[0].value = res.data.farmCount || 0
          this.statsData[1].value = res.data.animalCount || 0
          this.statsData[2].value = (res.data.healthRate || 0) + '%'
          this.statsData[3].value = this.$utils.formatMoney(res.data.monthlyIncome || 0)
        }
      } catch (error) {
        console.error('加载统计数据失败：', error)
      }
    },
    
    // 加载天气数据
    async loadWeatherData() {
      try {
        // 获取位置信息
        const location = await this.getCurrentLocation()
        
        // 获取天气信息
        const res = await this.$request({
          url: '/weather/current',
          method: 'GET',
          data: {
            latitude: location.latitude,
            longitude: location.longitude
          }
        })
        
        if (res.data) {
          this.weatherData = res.data
        }
      } catch (error) {
        console.error('加载天气数据失败：', error)
      }
    },
    
    // 加载最近活动
    async loadRecentActivities() {
      try {
        const res = await this.$request({
          url: '/farming/activities',
          method: 'GET',
          data: {
            limit: 10
          }
        })
        
        if (res.data && res.data.list) {
          this.recentActivities = res.data.list
        }
      } catch (error) {
        console.error('加载最近活动失败：', error)
      }
    },
    
    // 获取当前位置
    getCurrentLocation() {
      return new Promise((resolve, reject) => {
        uni.getLocation({
          type: 'gcj02',
          success: resolve,
          fail: reject
        })
      })
    },
    
    // 统计项点击
    onStatClick(item) {
      switch (item.type) {
        case 'farm':
          uni.switchTab({
            url: '/pages/farm/list'
          })
          break
        case 'animal':
          uni.switchTab({
            url: '/pages/animal/list'
          })
          break
        case 'health':
          uni.navigateTo({
            url: '/pages/health/record'
          })
          break
        case 'income':
          uni.switchTab({
            url: '/pages/statistics/index'
          })
          break
      }
    },
    
    // 快捷操作点击
    onActionClick(action) {
      uni.navigateTo({
        url: action.url
      })
    },
    
    // 活动项点击
    onActivityClick(activity) {
      if (activity.url) {
        uni.navigateTo({
          url: activity.url
        })
      }
    },
    
    // 查看全部活动
    onViewAllActivities() {
      uni.navigateTo({
        url: '/pages/activity/list'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

/* 头部区域 */
.header-section {
  padding: 40rpx 30rpx 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  
  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    margin-right: 20rpx;
  }
  
  .user-details {
    display: flex;
    flex-direction: column;
    
    .username {
      font-size: 36rpx;
      font-weight: bold;
      color: #ffffff;
      margin-bottom: 8rpx;
    }
    
    .user-role {
      font-size: 28rpx;
      color: rgba(255, 255, 255, 0.8);
    }
  }
}

.weather-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  
  .weather-text {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.9);
    margin-bottom: 8rpx;
  }
  
  .temperature {
    font-size: 32rpx;
    font-weight: bold;
    color: #ffffff;
  }
}

/* 统计区域 */
.stats-section {
  margin: 0 30rpx 40rpx;
}

.stats-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20rpx;
}

.stat-item {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 30rpx;
  display: flex;
  align-items: center;
  backdrop-filter: blur(10rpx);
  box-shadow: 0 8rpx 32rpx rgba(0, 0, 0, 0.1);
  
  .stat-icon {
    width: 60rpx;
    height: 60rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20rpx;
    
    .iconfont {
      font-size: 32rpx;
      color: #ffffff;
    }
  }
  
  .stat-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    
    .stat-value {
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
      margin-bottom: 8rpx;
    }
    
    .stat-label {
      font-size: 24rpx;
      color: #666666;
    }
  }
}

/* 快捷操作 */
.quick-actions {
  margin: 0 30rpx 40rpx;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30rpx;
  
  .title-text {
    font-size: 36rpx;
    font-weight: bold;
    color: #ffffff;
  }
  
  .more-text {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.actions-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
}

.action-item {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16rpx;
  padding: 30rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  backdrop-filter: blur(10rpx);
  
  .action-icon {
    width: 60rpx;
    height: 60rpx;
    background: linear-gradient(135deg, #2E8B57, #3CB371);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 16rpx;
    
    .iconfont {
      font-size: 32rpx;
      color: #ffffff;
    }
  }
  
  .action-text {
    font-size: 24rpx;
    color: #333333;
    text-align: center;
  }
}

/* 最近活动 */
.recent-activities {
  margin: 0 30rpx 40rpx;
}

.activity-list {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  backdrop-filter: blur(10rpx);
  overflow: hidden;
}

.activity-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
  
  .activity-icon {
    width: 60rpx;
    height: 60rpx;
    background: linear-gradient(135deg, #FF6B6B, #FF8E8E);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20rpx;
    
    .iconfont {
      font-size: 28rpx;
      color: #ffffff;
    }
  }
  
  .activity-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    
    .activity-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333333;
      margin-bottom: 8rpx;
    }
    
    .activity-desc {
      font-size: 28rpx;
      color: #666666;
      margin-bottom: 8rpx;
    }
    
    .activity-time {
      font-size: 24rpx;
      color: #999999;
    }
  }
}
</style>