// pages/statistics/statistics.js
const app = getApp();
const apiService = require('../../utils/api.js');

Page({
  data: {
    statusBarHeight: 0,
    loading: true,
    
    // 统计数据
    todayStats: {
      totalFarmers: 0,
      activeFarmers: 0,
      totalAnimals: 0,
      alertCount: 0
    },
    
    // 趋势数据
    trendData: {
      farmerGrowth: 0,
      animalGrowth: 0,
      alertTrend: 0
    },
    
    // 快捷操作
    quickActions: [
      {
        id: 'farmer_manage',
        title: '养殖户管理',
        icon: 'farmer',
        color: '#2c5aa0',
        path: '/pages/farmer/farmer'
      },
      {
        id: 'device_monitor',
        title: '设备监控',
        icon: 'settings',
        color: '#52c41a',
        path: '/pages/statistics/statistics'
      },
      {
        id: 'epidemic_control',
        title: '疫情防控',
        icon: 'epidemic',
        color: '#fa8c16',
        path: '/pages/statistics/statistics'
      },
      {
        id: 'data_analysis',
        title: '数据分析',
        icon: 'home',
        color: '#722ed1',
        path: '/pages/statistics/statistics'
      }
    ],
    
    // 最新动态
    recentActivities: [],
    
    // 市场价格
    marketPrice: {
      beef: { price: 0, trend: 0 },
      mutton: { price: 0, trend: 0 },
      milk: { price: 0, trend: 0 }
    }
  },

  onLoad() {
    // 获取状态栏高度
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight
    });
    
    // 检查登录状态
    this.checkLoginStatus();
  },

  onShow() {
    // 每次显示页面时刷新数据
    this.loadData();
  },

  // 检查登录状态
  checkLoginStatus() {
    const token = wx.getStorageSync('token');
    if (!token) {
      wx.reLaunch({
        url: '/pages/login/login'
      });
      return false;
    }
    return true;
  },

  // 加载数据
  async loadData() {
    if (!this.checkLoginStatus()) return;
    
    this.setData({ loading: true });
    
    try {
      // 并行加载多个数据
      const [statsResult, marketResult] = await Promise.allSettled([
        this.loadStatisticsData(),
        this.loadMarketPrice()
      ]);
      
      // 处理统计数据结果
      if (statsResult.status === 'fulfilled') {
        console.log('统计数据加载成功');
      } else {
        console.error('统计数据加载失败:', statsResult.reason);
        this.loadMockStatistics();
      }
      
      // 处理市场价格结果
      if (marketResult.status === 'fulfilled') {
        console.log('市场价格加载成功');
      } else {
        console.error('市场价格加载失败:', marketResult.reason);
        this.loadMockMarketPrice();
      }
      
    } catch (error) {
      console.error('数据加载失败:', error);
      // 加载模拟数据作为备用
      this.loadMockData();
    } finally {
      this.setData({ loading: false });
    }
  },

  // 加载统计数据
  async loadStatisticsData() {
    try {
      const result = await apiService.getDataCenterStats();
      
      if (result.code === 200 || result.code === 0) {
        const data = result.data || result;
        
        this.setData({
          todayStats: {
            totalFarmers: data.totalFarmers || 0,
            activeFarmers: data.activeFarmers || 0,
            totalAnimals: data.totalAnimals || 0,
            alertCount: data.alertCount || 0
          },
          trendData: {
            farmerGrowth: data.farmerGrowth || 0,
            animalGrowth: data.animalGrowth || 0,
            alertTrend: data.alertTrend || 0
          }
        });
        
        // 如果有最新动态数据
        if (data.recentActivities) {
          this.setData({
            recentActivities: data.recentActivities
          });
        }
      }
    } catch (error) {
      console.error('获取统计数据失败:', error);
      throw error;
    }
  },

  // 加载市场价格
  async loadMarketPrice() {
    try {
      const result = await apiService.getMarketPrice();
      
      if (result.code === 200 || result.code === 0) {
        const data = result.data || result;
        
        this.setData({
          marketPrice: {
            beef: data.beef || { price: 0, trend: 0 },
            mutton: data.mutton || { price: 0, trend: 0 },
            milk: data.milk || { price: 0, trend: 0 }
          }
        });
      }
    } catch (error) {
      console.error('获取市场价格失败:', error);
      throw error;
    }
  },

  // 加载模拟统计数据
  loadMockStatistics() {
    this.setData({
      todayStats: {
        totalFarmers: 156,
        activeFarmers: 142,
        totalAnimals: 3248,
        alertCount: 8
      },
      trendData: {
        farmerGrowth: 12,
        animalGrowth: 156,
        alertTrend: -3
      },
      recentActivities: [
        {
          id: 1,
          type: 'farmer',
          title: '新增养殖户',
          content: '张三申请加入养殖户管理',
          time: '2小时前'
        },
        {
          id: 2,
          type: 'alert',
          title: '设备告警',
          content: '智能项圈001离线超过30分钟',
          time: '3小时前'
        },
        {
          id: 3,
          type: 'epidemic',
          title: '疫情防控',
          content: '完成第三季度疫苗接种统计',
          time: '5小时前'
        }
      ]
    });
  },

  // 加载模拟市场价格
  loadMockMarketPrice() {
    this.setData({
      marketPrice: {
        beef: { price: 68.5, trend: 2.3 },
        mutton: { price: 72.8, trend: -1.2 },
        milk: { price: 4.2, trend: 0.8 }
      }
    });
  },

  // 加载所有模拟数据
  loadMockData() {
    this.loadMockStatistics();
    this.loadMockMarketPrice();
  },

  // 快捷操作点击
  onQuickActionTap(e) {
    const { action } = e.currentTarget.dataset;
    const actionItem = this.data.quickActions.find(item => item.id === action);
    
    if (actionItem && actionItem.path) {
      if (actionItem.path.startsWith('/pages/')) {
        // 如果是tabBar页面，使用switchTab
        if (actionItem.path.includes('/farmer/farmer')) {
          wx.switchTab({
            url: actionItem.path
          });
        } else {
          wx.navigateTo({
            url: actionItem.path
          });
        }
      }
    } else {
      wx.showToast({
        title: '功能开发中',
        icon: 'none'
      });
    }
  },

  // 查看更多动态
  onViewMoreActivities() {
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.loadData().finally(() => {
      wx.stopPullDownRefresh();
    });
  },

  // 分享页面
  onShareAppMessage() {
    return {
      title: '政府监管端 - 数据统计',
      path: '/pages/statistics/statistics'
    };
  }
});