// pages/alert/alert.js
const { get, post } = require('../../utils/api')
const { formatDate, formatTime } = require('../../utils/index')
// 引入预警相关真实接口
const { alertApi } = require('../../services/api')

Page({
  data: {
    alertList: [],
    loading: false,
    refreshing: false,
    searchKeyword: '',
    typeFilter: 'all',
    statusFilter: 'all',
    page: 1,
    pageSize: 20,
    hasMore: true,
    total: 0,
    // 详情弹窗
    detailVisible: false,
    detailData: null,
    detailPairs: [],
    alertTypes: [
      { value: 'eartag', label: '耳标预警', icon: '🏷️' },
      { value: 'collar', label: '项圈预警', icon: '📱' },
      { value: 'fence', label: '围栏预警', icon: '🚧' },
      { value: 'health', label: '健康预警', icon: '🏥' }
    ],
    alertStatuses: [
      { value: 'pending', label: '待处理', color: '#faad14' },
      { value: 'processing', label: '处理中', color: '#1890ff' },
      { value: 'resolved', label: '已解决', color: '#52c41a' },
      { value: 'ignored', label: '已忽略', color: '#909399' }
    ]
  },

  onLoad(options) {
    // 允许通过URL参数设置默认筛选：?type=eartag&status=pending
    const { type, status } = options || {}
    const validTypes = this.data.alertTypes.map(t => t.value)
    const validStatuses = this.data.alertStatuses.map(s => s.value)

    if (type && validTypes.includes(type)) {
      this.setData({ typeFilter: type })
    }
    if (status && validStatuses.includes(status)) {
      this.setData({ statusFilter: status })
    }

    this.loadAlertList()
  },

  onShow() {
    this.loadAlertList()
  },

  onPullDownRefresh() {
    this.setData({
      page: 1,
      hasMore: true,
      alertList: []
    })
    this.loadAlertList().then(() => {
      wx.stopPullDownRefresh()
    })
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMoreAlerts()
    }
  },

  // 加载预警列表
  async loadAlertList() {
    this.setData({ loading: true })
    
    try {
      // 当类型为耳标预警时，改用智能耳标公开接口
      if (this.data.typeFilter === 'eartag') {
        const params = {
          search: this.data.searchKeyword || '',
          alertType: '',
          page: this.data.page,
          limit: this.data.pageSize
        }
        const res = await alertApi.getEartagAlerts(params)
        let newList = []
        if (Array.isArray(res)) {
          newList = res
        } else if (res && Array.isArray(res.data)) {
          newList = res.data
        }
        // 将远程数据映射为页面展示所需结构
        const mappedList = newList.map(item => this.mapEartagAlertToListItem(item))
        const alertList = this.data.page === 1 ? mappedList : [...this.data.alertList, ...mappedList]
        this.setData({
          alertList,
          total: alertList.length,
          hasMore: newList.length === this.data.pageSize
        })
        return
      }

      // 当类型为项圈预警时，改用智能项圈公开接口
      if (this.data.typeFilter === 'collar') {
        const params = {
          search: this.data.searchKeyword || '',
          alertType: '',
          page: this.data.page,
          limit: this.data.pageSize
        }
        const res = await alertApi.getCollarAlerts(params)
        let newList = []
        if (Array.isArray(res)) {
          newList = res
        } else if (res && Array.isArray(res.data)) {
          newList = res.data
        }
        const mappedList = newList.map(item => this.mapCollarAlertToListItem(item))
        const alertList = this.data.page === 1 ? mappedList : [...this.data.alertList, ...mappedList]
        this.setData({
          alertList,
          total: alertList.length,
          hasMore: newList.length === this.data.pageSize
        })
        return
      }

      // 其他类型维持原有接口逻辑
      const params = {
        page: this.data.page,
        pageSize: this.data.pageSize,
        type: this.data.typeFilter === 'all' ? '' : this.data.typeFilter,
        status: this.data.statusFilter === 'all' ? '' : this.data.statusFilter
      }
      
      if (this.data.searchKeyword) {
        params.search = this.data.searchKeyword
      }
      
      const response = await get('/alerts', params)
      
      if (response.success) {
        const newList = response.data.list || []
        const alertList = this.data.page === 1 ? newList : [...this.data.alertList, ...newList]
        
        this.setData({
          alertList,
          total: response.data.total || 0,
          hasMore: alertList.length < (response.data.total || 0)
        })
      } else {
        wx.showToast({
          title: response.message || '获取数据失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('获取预警列表失败:', error)
      wx.showToast({
        title: '获取数据失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 加载更多预警
  async loadMoreAlerts() {
    if (!this.data.hasMore || this.data.loading) return
    
    this.setData({
      page: this.data.page + 1
    })
    
    await this.loadAlertList()
  },

  // 搜索输入
  onSearchInput(e) {
    this.setData({
      searchKeyword: e.detail.value
    })
  },

  // 执行搜索
  onSearch() {
    this.setData({
      page: 1,
      hasMore: true,
      alertList: []
    })
    this.loadAlertList()
  },

  // 清空搜索
  onClearSearch() {
    this.setData({
      searchKeyword: '',
      page: 1,
      hasMore: true,
      alertList: []
    })
    this.loadAlertList()
  },

  // 类型筛选
  onTypeFilter(e) {
    const type = e.currentTarget.dataset.type
    this.setData({
      typeFilter: type,
      page: 1,
      hasMore: true,
      alertList: []
    })
    this.loadAlertList()
  },

  // 状态筛选
  onStatusFilter(e) {
    const status = e.currentTarget.dataset.status
    this.setData({
      statusFilter: status,
      page: 1,
      hasMore: true,
      alertList: []
    })
    this.loadAlertList()
  },

  // 查看预警详情（在当前页弹窗展示）
  async viewAlertDetail(e) {
    const id = e.currentTarget.dataset.id
    const type = e.currentTarget.dataset.type

    try {
      wx.showLoading({ title: '加载详情...' })

      let res
      if (type === 'eartag') {
        res = await alertApi.getEartagAlertDetail(id)
      } else if (type === 'collar') {
        res = await alertApi.getCollarAlertDetail(id)
      } else {
        // 其他类型暂未实现，给出提示
        wx.showToast({ title: '该类型详情暂未实现', icon: 'none' })
        return
      }

      const detail = res?.data || res
      const detailPairs = this.mapAlertDetail(type, detail)

      this.setData({
        detailVisible: true,
        detailData: detail,
        detailPairs
      })
    } catch (err) {
      console.error('加载预警详情失败:', err)
      wx.showToast({ title: '加载详情失败', icon: 'none' })
    } finally {
      wx.hideLoading()
    }
  },

  // 关闭详情弹窗
  closeDetail() {
    this.setData({ detailVisible: false, detailData: null, detailPairs: [] })
  },

  // 处理预警
  async handleAlert(e) {
    const id = e.currentTarget.dataset.id
    const type = e.currentTarget.dataset.type
    
    const result = await wx.showModal({
      title: '处理预警',
      content: '确定要处理这个预警吗？',
      confirmText: '处理',
      confirmColor: '#3cc51f'
    })
    
    if (result.confirm) {
      try {
        wx.showLoading({ title: '处理中...' })
        
        const response = await post(`/alerts/${id}/handle`, {
          type: type,
          action: 'process'
        })
        
        if (response.success) {
          wx.showToast({
            title: '处理成功',
            icon: 'success'
          })
          
          // 刷新列表
          this.setData({
            page: 1,
            hasMore: true,
            alertList: []
          })
          this.loadAlertList()
        } else {
          wx.showToast({
            title: response.message || '处理失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('处理预警失败:', error)
        wx.showToast({
          title: '处理失败',
          icon: 'none'
        })
      } finally {
        wx.hideLoading()
      }
    }
  },

  // 忽略预警
  async ignoreAlert(e) {
    const id = e.currentTarget.dataset.id
    const type = e.currentTarget.dataset.type
    
    const result = await wx.showModal({
      title: '忽略预警',
      content: '确定要忽略这个预警吗？',
      confirmText: '忽略',
      confirmColor: '#909399'
    })
    
    if (result.confirm) {
      try {
        wx.showLoading({ title: '忽略中...' })
        
        const response = await post(`/alerts/${id}/handle`, {
          type: type,
          action: 'ignore'
        })
        
        if (response.success) {
          wx.showToast({
            title: '已忽略',
            icon: 'success'
          })
          
          // 刷新列表
          this.setData({
            page: 1,
            hasMore: true,
            alertList: []
          })
          this.loadAlertList()
        } else {
          wx.showToast({
            title: response.message || '操作失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('忽略预警失败:', error)
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        })
      } finally {
        wx.hideLoading()
      }
    }
  },

  // 批量处理预警
  async batchHandleAlerts() {
    const selectedAlerts = this.data.alertList.filter(alert => alert.selected)
    
    if (selectedAlerts.length === 0) {
      wx.showToast({
        title: '请选择要处理的预警',
        icon: 'none'
      })
      return
    }
    
    const result = await wx.showModal({
      title: '批量处理',
      content: `确定要处理选中的${selectedAlerts.length}个预警吗？`,
      confirmText: '处理',
      confirmColor: '#3cc51f'
    })
    
    if (result.confirm) {
      try {
        wx.showLoading({ title: '处理中...' })
        
        const alertIds = selectedAlerts.map(alert => alert.id)
        const response = await post('/alerts/batch-handle', {
          alertIds: alertIds,
          action: 'process'
        })
        
        if (response.success) {
          wx.showToast({
            title: '处理成功',
            icon: 'success'
          })
          
          // 刷新列表
          this.setData({
            page: 1,
            hasMore: true,
            alertList: []
          })
          this.loadAlertList()
        } else {
          wx.showToast({
            title: response.message || '处理失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('批量处理预警失败:', error)
        wx.showToast({
          title: '处理失败',
          icon: 'none'
        })
      } finally {
        wx.hideLoading()
      }
    }
  },

  // 获取预警类型信息
  getAlertTypeInfo(type) {
    return this.data.alertTypes.find(item => item.value === type) || { label: '未知', icon: '❓' }
  },

  // 获取状态信息
  getStatusInfo(status) {
    return this.data.alertStatuses.find(item => item.value === status) || { label: '未知', color: '#909399' }
  },

  // 获取优先级文本
  getPriorityText(priority) {
    const priorityMap = {
      'low': '低',
      'medium': '中',
      'high': '高',
      'urgent': '紧急'
    }
    return priorityMap[priority] || '未知'
  },

  // 获取优先级颜色
  getPriorityColor(priority) {
    const colorMap = {
      'low': '#52c41a',
      'medium': '#faad14',
      'high': '#f5222d',
      'urgent': '#722ed1'
    }
    return colorMap[priority] || '#909399'
  },

  // 将远程耳标预警数据转换为页面列表所需字段
  mapEartagAlertToListItem(item) {
    const titleMap = {
      temperature: '温度异常',
      movement: '运动量异常',
      position: '位置异常',
      battery: '电量偏低'
    }
    const titleBase = titleMap[item.alertType] || '耳标预警'
    const levelText = item.alertLevel ? `（${item.alertLevel}）` : ''
    return {
      id: item.id || `${item.deviceId || 'unknown'}_${item.alertType || 'eartag'}`,
      type: 'eartag',
      title: `${titleBase}${levelText}`,
      content: item.description || '',
      deviceName: item.deviceName || item.eartagNumber || '未知',
      createTime: item.alertTime || item.createTime || '',
      status: 'pending',
      priority: item.alertLevel || 'medium'
    }
  },

  // 将远程项圈预警数据转换为页面列表所需字段
  mapCollarAlertToListItem(item) {
    const titleMap = {
      temperature: '温度异常',
      movement: '运动量异常',
      battery: '电量偏低',
      offline: '设备离线',
      gps: '定位异常',
      wear: '佩戴异常'
    }
    const titleBase = titleMap[item.alertType] || '项圈预警'
    const levelText = item.alertLevel ? `（${item.alertLevel}）` : ''
    return {
      id: item.id || `${item.deviceId || 'unknown'}_${item.alertType || 'collar'}`,
      type: 'collar',
      title: `${titleBase}${levelText}`,
      content: item.description || '',
      deviceName: item.deviceName || item.collarNumber || '未知',
      createTime: item.alertTime || item.createTime || '',
      status: 'pending',
      priority: item.alertLevel || 'medium'
    }
  },

  // 映射预警详情字段为键值对用于展示
  mapAlertDetail(type, d) {
    if (!d) return []

    // 通用映射函数
    const levelText = {
      low: '低',
      medium: '中',
      high: '高',
      urgent: '紧急'
    }
    const typeText = {
      temperature: '温度',
      battery: '电量',
      movement: '运动',
      offline: '离线',
      gps: '定位',
      eartag: '耳标',
      collar: '项圈'
    }

    const pairs = []
    // 基本信息
    pairs.push({ label: '预警ID', value: d.id || '-' })
    pairs.push({ label: '异常类型', value: typeText[d.alertType] || (d.alertType || '-') })
    pairs.push({ label: '异常等级', value: levelText[d.alertLevel] || (d.alertLevel || '-') })
    pairs.push({ label: '预警时间', value: d.alertTime ? this.formatTime(d.alertTime) : '-' })

    if (type === 'eartag') {
      pairs.push({ label: '耳标编号', value: d.eartagNumber || d.deviceName || '-' })
      pairs.push({ label: '设备ID', value: d.deviceId || '-' })
      pairs.push({ label: '设备状态', value: d.deviceStatus || '-' })
      // 传感数据
      if (d.temperature !== undefined) pairs.push({ label: '温度(°C)', value: d.temperature })
      if (d.battery !== undefined) pairs.push({ label: '电量(%)', value: d.battery })
      if (d.gpsSignal) pairs.push({ label: 'GPS信号', value: d.gpsSignal })
      if (d.longitude !== undefined) pairs.push({ label: '经度', value: d.longitude })
      if (d.latitude !== undefined) pairs.push({ label: '纬度', value: d.latitude })
      if (d.movementStatus) pairs.push({ label: '运动状态', value: d.movementStatus })
      if (d.dailySteps !== undefined) pairs.push({ label: '今日步数', value: d.dailySteps })
      if (d.yesterdaySteps !== undefined) pairs.push({ label: '昨日步数', value: d.yesterdaySteps })
      if (d.totalSteps !== undefined) pairs.push({ label: '总步数', value: d.totalSteps })
      if (d.description) pairs.push({ label: '描述', value: d.description })
    } else if (type === 'collar') {
      // 项圈详情字段（完整展示你提供的示例数据）
      pairs.push({ label: '项圈编号', value: d.collarNumber || d.deviceName || '-' })
      pairs.push({ label: '设备ID', value: d.deviceId || '-' })
      pairs.push({ label: '设备名称', value: d.deviceName || '-' })
      pairs.push({ label: '设备状态', value: d.deviceStatus || '-' })
      if (d.wearStatus) pairs.push({ label: '佩戴状态', value: d.wearStatus })
      if (d.temperature !== undefined) pairs.push({ label: '温度(°C)', value: d.temperature })
      if (d.battery !== undefined) pairs.push({ label: '电量(%)', value: d.battery })
      if (d.gpsSignal) pairs.push({ label: 'GPS信号', value: d.gpsSignal })
      if (d.longitude !== undefined) pairs.push({ label: '经度', value: d.longitude })
      if (d.latitude !== undefined) pairs.push({ label: '纬度', value: d.latitude })
      if (d.movementStatus) pairs.push({ label: '运动状态', value: d.movementStatus })
      if (d.dailySteps !== undefined) pairs.push({ label: '今日步数', value: d.dailySteps })
      if (d.yesterdaySteps !== undefined) pairs.push({ label: '昨日步数', value: d.yesterdaySteps })
      if (d.totalSteps !== undefined) pairs.push({ label: '总步数', value: d.totalSteps })
      if (d.description) pairs.push({ label: '描述', value: d.description })
    }

    return pairs
  },

  // 格式化日期
  formatDate(date) {
    return formatDate(date)
  },

  // 格式化时间
  formatTime(time) {
    return formatTime(time)
  }
})
