// 首页
const app = getApp();

Page({
  data: {
    userInfo: null,
    farmStats: {
      farmCount: 0,
      animalCount: 0,
      healthRate: 0,
      totalValue: 0
    },
    recentActivities: [],
    weatherInfo: null,
    loading: true,
    refreshing: false
  },

  onLoad() {
    this.checkLogin();
  },

  onShow() {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      });
      this.loadData();
    }
  },

  onPullDownRefresh() {
    this.setData({ refreshing: true });
    this.loadData().finally(() => {
      this.setData({ refreshing: false });
      wx.stopPullDownRefresh();
    });
  },

  // 检查登录状态
  checkLogin() {
    if (!app.globalData.userInfo) {
      wx.navigateTo({
        url: '/pages/auth/login'
      });
      return;
    }
    
    this.setData({
      userInfo: app.globalData.userInfo
    });
    this.loadData();
  },

  // 加载数据
  async loadData() {
    try {
      this.setData({ loading: true });
      
      await Promise.all([
        this.loadFarmStats(),
        this.loadRecentActivities(),
        this.loadWeatherInfo()
      ]);
    } catch (error) {
      console.error('加载数据失败：', error);
      app.showError('加载数据失败');
    } finally {
      this.setData({ loading: false });
    }
  },

  // 加载养殖场统计
  async loadFarmStats() {
    try {
      const res = await app.request({
        url: '/statistics/personal',
        method: 'GET'
      });
      
      this.setData({
        farmStats: {
          farmCount: res.data.overview.farm_count || 0,
          animalCount: res.data.overview.animal_count || 0,
          healthRate: res.data.farm_stats[0]?.health_rate || 0,
          totalValue: res.data.overview.total_income || 0
        }
      });
    } catch (error) {
      console.error('加载养殖场统计失败：', error);
    }
  },

  // 加载最近活动
  async loadRecentActivities() {
    try {
      const res = await app.request({
        url: '/messages',
        method: 'GET',
        data: { limit: 5 }
      });
      
      this.setData({
        recentActivities: res.data.list || []
      });
    } catch (error) {
      console.error('加载最近活动失败：', error);
    }
  },

  // 加载天气信息
  async loadWeatherInfo() {
    try {
      // 获取位置信息
      const location = await this.getLocation();
      
      // 这里应该调用天气API，暂时使用模拟数据
      this.setData({
        weatherInfo: {
          temperature: 15,
          humidity: 65,
          weather: '晴',
          location: '北京市朝阳区'
        }
      });
    } catch (error) {
      console.error('加载天气信息失败：', error);
    }
  },

  // 获取位置信息
  getLocation() {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        success: resolve,
        fail: reject
      });
    });
  },

  // 导航到养殖场列表
  goToFarmList() {
    wx.switchTab({
      url: '/pages/farm/list'
    });
  },

  // 导航到动物列表
  goToAnimalList() {
    wx.switchTab({
      url: '/pages/animal/list'
    });
  },

  // 导航到统计页面
  goToStatistics() {
    wx.switchTab({
      url: '/pages/statistics/farm'
    });
  },

  // 导航到消息中心
  goToMessages() {
    wx.navigateTo({
      url: '/pages/message/index'
    });
  },

  // 快捷操作
  quickActions: [
    {
      name: '添加动物',
      icon: 'add-animal',
      url: '/pages/animal/add'
    },
    {
      name: '健康记录',
      icon: 'health',
      url: '/pages/animal/health'
    },
    {
      name: '数据统计',
      icon: 'chart',
      url: '/pages/statistics/farm'
    },
    {
      name: '设置',
      icon: 'settings',
      url: '/pages/settings/index'
    }
  ],

  // 快捷操作点击
  onQuickAction(e) {
    const { url } = e.currentTarget.dataset;
    if (url.includes('tab')) {
      wx.switchTab({ url });
    } else {
      wx.navigateTo({ url });
    }
  },

  // 查看活动详情
  onActivityTap(e) {
    const { item } = e.currentTarget.dataset;
    wx.navigateTo({
      url: `/pages/message/detail?id=${item.id}`
    });
  }
});