// pages/home/home.js - 首页
const API = require('../../utils/api').API

Page({
  data: {
    activeTab: 'collar',
    stats: {
      notCollected: 0,
      collarCut: 0,
      temperature: 0,
      activityHigh: 0,
      activityLow: 0,
      transferSlow: 0,
      lowBattery: 0
    },
    totalAlerts: 0, // 总预警数量
    loading: false
  },

  onLoad() {
    console.log('首页加载')
    this.loadStats()
  },

  onShow() {
    console.log('首页显示')
  },

  onPullDownRefresh() {
    this.loadStats()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  // 切换预警类型标签
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab
    this.setData({ activeTab: tab })
    // 根据不同标签加载不同数据
    this.loadStats()
  },

  // 加载统计数据
  async loadStats() {
    this.setData({ loading: true })
    
    try {
      if (this.data.activeTab === 'collar') {
        // 调用真实的项圈预警API
        const res = await API.getCollarAlerts({
          page: 1,
          limit: 100, // 获取所有数据用于统计
          search: '',
          alertType: ''
        })

        console.log('项圈预警数据:', res)

        // 根据实际返回的数据结构调整
        const alerts = res.data?.list || res.data || res.list || []
        const total = res.data?.pagination?.total || res.total || alerts.length || 0

        // 统计不同类型的预警数量
        const stats = {
          notCollected: 0,
          collarCut: 0,
          temperature: 0,
          activityHigh: 0,
          activityLow: 0,
          transferSlow: 0,
          lowBattery: 0
        }

        alerts.forEach(alert => {
          const alertType = alert.alertType || ''
          
          // 根据预警类型统计
          if (alertType === 'not_collected') {
            stats.notCollected++
          } else if (alertType === 'collar_cut') {
            stats.collarCut++
          } else if (alertType === 'temperature') {
            stats.temperature++
          } else if (alertType === 'activity_high') {
            stats.activityHigh++
          } else if (alertType === 'activity_low') {
            stats.activityLow++
          } else if (alertType === 'transfer_slow') {
            stats.transferSlow++
          } else if (alertType === 'battery') {
            stats.lowBattery++
          }
        })

        this.setData({
          stats,
          totalAlerts: total,
          loading: false
        })
      } else if (this.data.activeTab === 'eartag') {
        // 调用真实的耳标预警API
        const res = await API.getEartagAlerts({
          page: 1,
          limit: 100, // 获取所有数据用于统计
          search: '',
          alertType: ''
        })

        console.log('耳标预警数据:', res)

        // 根据实际返回的数据结构调整
        const alerts = res.data?.list || res.data || res.list || []
        const total = res.data?.pagination?.total || res.total || alerts.length || 0

        // 统计不同类型的预警数量
        const stats = {
          notCollected: 0,
          collarCut: 0,
          temperature: 0,
          activityHigh: 0,
          activityLow: 0,
          transferSlow: 0,
          lowBattery: 0
        }

        alerts.forEach(alert => {
          const alertType = alert.alertType || ''
          
          // 根据预警类型统计
          if (alertType === 'not_collected') {
            stats.notCollected++
          } else if (alertType === 'collar_cut') {
            stats.collarCut++
          } else if (alertType === 'temperature') {
            stats.temperature++
          } else if (alertType === 'movement') {
            // 运动异常预警归入运动量偏低
            stats.activityLow++
          } else if (alertType === 'activity_high') {
            stats.activityHigh++
          } else if (alertType === 'activity_low') {
            stats.activityLow++
          } else if (alertType === 'transfer_slow') {
            stats.transferSlow++
          } else if (alertType === 'battery') {
            stats.lowBattery++
          }
        })

        this.setData({
          stats,
          totalAlerts: total,
          loading: false
        })
      } else {
        // 其他类型暂时使用模拟数据
        const statsMap = {
          eartag: {
            notCollected: 8,
            collarCut: 1,
            temperature: 2,
            activityHigh: 1,
            activityLow: 2,
            transferSlow: 0,
            lowBattery: 3
          },
          anklet: {
            notCollected: 5,
            collarCut: 0,
            temperature: 1,
            activityHigh: 2,
            activityLow: 1,
            transferSlow: 1,
            lowBattery: 1
          },
          host: {
            notCollected: 0,
            collarCut: 0,
            temperature: 0,
            activityHigh: 0,
            activityLow: 0,
            transferSlow: 0,
            lowBattery: 1
          }
        }
        
        this.setData({
          stats: statsMap[this.data.activeTab] || {},
          loading: false
        })
      }
    } catch (error) {
      console.error('加载统计数据失败:', error)
      
      // 使用默认的统计数据作为降级方案
      const defaultStats = {
        collar: {
          notCollected: 0,
          collarCut: 0,
          temperature: 0,
          activityHigh: 0,
          activityLow: 0,
          transferSlow: 0,
          lowBattery: 0
        },
        eartag: {
          notCollected: 0,
          collarCut: 0,
          temperature: 0,
          activityHigh: 0,
          activityLow: 0,
          transferSlow: 0,
          lowBattery: 0
        },
        anklet: {
          notCollected: 0,
          collarCut: 0,
          temperature: 0,
          activityHigh: 0,
          activityLow: 0,
          transferSlow: 0,
          lowBattery: 0
        },
        host: {
          notCollected: 0,
          collarCut: 0,
          temperature: 0,
          activityHigh: 0,
          activityLow: 0,
          transferSlow: 0,
          lowBattery: 0
        }
      }
      
      this.setData({
        stats: defaultStats[this.data.activeTab] || defaultStats.collar,
        loading: false
      })

      // 根据错误类型显示不同提示
      if (error.statusCode === 502 || error.statusCode === 503 || error.statusCode === 504) {
        // 服务器错误，toast已在api.js中显示
        console.log('服务器暂时不可用，已显示默认数据')
      } else {
        wx.showToast({
          title: '加载失败，显示默认数据',
          icon: 'none',
          duration: 2000
        })
      }
    }
  },

  // 点击预警区域跳转到预警列表
  goToAlertList() {
    console.log('跳转到预警列表，当前类型:', this.data.activeTab)
    
    if (this.data.activeTab === 'collar') {
      wx.navigateTo({
        url: '/pages/alert/collar-alert/collar-alert',
        fail: () => {
          wx.showToast({
            title: '页面开发中',
            icon: 'none'
          })
        }
      })
    } else if (this.data.activeTab === 'eartag') {
      wx.navigateTo({
        url: '/pages/alert/eartag-alert/eartag-alert',
        fail: () => {
          wx.showToast({
            title: '页面开发中',
            icon: 'none'
          })
        }
      })
    } else {
      wx.showToast({
        title: '功能开发中',
        icon: 'none'
      })
    }
  },

  // 跳转到生资保险
  goToInsurance() {
    wx.showToast({
      title: '跳转到保险系统',
      icon: 'none'
    })
    // TODO: 实际跳转逻辑
    // wx.navigateTo({
    //   url: '/pages/insurance/index'
    // })
  },

  // 设备详情
  goToDeviceDetail(e) {
    const type = e.currentTarget.dataset.type
    console.log('跳转到设备详情:', type)
    
    const urlMap = {
      collar: '/pages/device/collar/collar',
      eartag: '/pages/device/eartag/eartag',
      anklet: '/pages/device/eartag/eartag', // 脚环暂时用耳标页面
      host: '/pages/device/host/host',
      monitor: '/pages/device/fence/fence' // 监控暂时用围栏页面
    }
    
    const url = urlMap[type]
    if (url) {
      wx.navigateTo({ 
        url,
        fail: () => {
          wx.showToast({
            title: '页面开发中',
            icon: 'none'
          })
        }
      })
    }
  },

  // 智能工具
  goToTool(e) {
    const type = e.currentTarget.dataset.type
    console.log('跳转到工具:', type)
    
    if (type === 'fence') {
      wx.navigateTo({
        url: '/pages/device/fence/fence',
        fail: () => {
          wx.showToast({
            title: '页面开发中',
            icon: 'none'
          })
        }
      })
    } else {
      wx.showToast({
        title: '功能开发中',
        icon: 'none'
      })
    }
  },

  // 业务办理
  goToBusiness(e) {
    const type = e.currentTarget.dataset.type
    console.log('跳转到业务办理:', type)
    
    wx.showToast({
      title: '功能开发中',
      icon: 'none'
    })
  }
})
