/**
 * 智能耳标预警API使用示例
 * @file smart-eartag-alert-usage.js
 * @description 展示如何在其他程序中调用智能耳标预警API
 */

const axios = require('axios');

// 配置API基础URL
const API_BASE_URL = 'http://localhost:5350/api/smart-alerts/public';

// 创建API客户端类
class SmartEartagAlertClient {
  constructor(baseURL = API_BASE_URL) {
    this.client = axios.create({
      baseURL,
      timeout: 10000,
      headers: {
        'Content-Type': 'application/json'
      }
    });
  }

  /**
   * 获取预警统计
   */
  async getAlertStats() {
    try {
      const response = await this.client.get('/eartag/stats');
      return response.data;
    } catch (error) {
      console.error('获取预警统计失败:', error.message);
      throw error;
    }
  }

  /**
   * 获取预警列表
   * @param {Object} options - 查询选项
   */
  async getAlerts(options = {}) {
    try {
      const params = {
        page: options.page || 1,
        limit: options.limit || 10,
        search: options.search,
        alertType: options.alertType,
        alertLevel: options.alertLevel,
        status: options.status,
        startDate: options.startDate,
        endDate: options.endDate
      };
      
      const response = await this.client.get('/eartag', { params });
      return response.data;
    } catch (error) {
      console.error('获取预警列表失败:', error.message);
      throw error;
    }
  }

  /**
   * 获取预警详情
   * @param {string} alertId - 预警ID
   */
  async getAlertById(alertId) {
    try {
      const response = await this.client.get(`/eartag/${alertId}`);
      return response.data;
    } catch (error) {
      console.error('获取预警详情失败:', error.message);
      throw error;
    }
  }

  /**
   * 处理预警
   * @param {string} alertId - 预警ID
   * @param {Object} data - 处理数据
   */
  async handleAlert(alertId, data = {}) {
    try {
      const response = await this.client.post(`/eartag/${alertId}/handle`, data);
      return response.data;
    } catch (error) {
      console.error('处理预警失败:', error.message);
      throw error;
    }
  }

  /**
   * 批量处理预警
   * @param {Array} alertIds - 预警ID列表
   * @param {Object} data - 处理数据
   */
  async batchHandleAlerts(alertIds, data = {}) {
    try {
      const requestData = {
        alertIds,
        ...data
      };
      const response = await this.client.post('/eartag/batch-handle', requestData);
      return response.data;
    } catch (error) {
      console.error('批量处理预警失败:', error.message);
      throw error;
    }
  }

  /**
   * 导出预警数据
   * @param {Object} options - 导出选项
   */
  async exportAlerts(options = {}) {
    try {
      const params = {
        search: options.search,
        alertType: options.alertType,
        alertLevel: options.alertLevel,
        startDate: options.startDate,
        endDate: options.endDate,
        format: options.format || 'json'
      };
      
      const response = await this.client.get('/eartag/export', { params });
      return response.data;
    } catch (error) {
      console.error('导出预警数据失败:', error.message);
      throw error;
    }
  }
}

// 使用示例
async function demonstrateUsage() {
  console.log('🚀 智能耳标预警API使用示例\n');
  
  const client = new SmartEartagAlertClient();
  
  try {
    // 1. 获取预警统计
    console.log('1. 获取预警统计...');
    const stats = await client.getAlertStats();
    console.log('预警统计:', stats.data);
    console.log('');

    // 2. 获取预警列表
    console.log('2. 获取预警列表...');
    const alerts = await client.getAlerts({
      page: 1,
      limit: 5,
      alertType: 'battery' // 只获取低电量预警
    });
    console.log(`找到 ${alerts.total} 条预警，当前页显示 ${alerts.data.length} 条`);
    console.log('');

    // 3. 获取预警详情
    if (alerts.data.length > 0) {
      console.log('3. 获取预警详情...');
      const alertId = alerts.data[0].id;
      const alertDetail = await client.getAlertById(alertId);
      console.log('预警详情:', alertDetail.data);
      console.log('');

      // 4. 处理预警
      console.log('4. 处理预警...');
      const handleResult = await client.handleAlert(alertId, {
        action: 'acknowledged',
        notes: '通过API自动处理',
        handler: 'system'
      });
      console.log('处理结果:', handleResult.data);
      console.log('');
    }

    // 5. 批量处理预警
    if (alerts.data.length > 1) {
      console.log('5. 批量处理预警...');
      const alertIds = alerts.data.slice(0, 2).map(alert => alert.id);
      const batchResult = await client.batchHandleAlerts(alertIds, {
        action: 'acknowledged',
        notes: '批量处理',
        handler: 'system'
      });
      console.log(`批量处理结果: 成功处理 ${batchResult.data.processedCount} 个预警`);
      console.log('');
    }

    // 6. 导出预警数据
    console.log('6. 导出预警数据...');
    const exportData = await client.exportAlerts({
      alertType: 'battery',
      format: 'json'
    });
    console.log(`导出数据: ${exportData.data.length} 条预警记录`);
    console.log('');

    console.log('✅ 所有示例执行完成！');

  } catch (error) {
    console.error('❌ 示例执行失败:', error.message);
  }
}

// 高级使用示例：监控预警变化
class AlertMonitor {
  constructor(client, options = {}) {
    this.client = client;
    this.interval = options.interval || 30000; // 30秒检查一次
    this.lastStats = null;
    this.callbacks = {
      onNewAlert: options.onNewAlert || (() => {}),
      onAlertChange: options.onAlertChange || (() => {}),
      onError: options.onError || (() => {})
    };
  }

  start() {
    console.log('🔍 开始监控预警变化...');
    this.monitorInterval = setInterval(() => {
      this.checkAlerts();
    }, this.interval);
  }

  stop() {
    if (this.monitorInterval) {
      clearInterval(this.monitorInterval);
      console.log('⏹️ 停止监控预警变化');
    }
  }

  async checkAlerts() {
    try {
      const stats = await this.client.getAlertStats();
      
      if (this.lastStats) {
        // 检查是否有新的预警
        const newAlerts = stats.data.totalAlerts - this.lastStats.totalAlerts;
        if (newAlerts > 0) {
          console.log(`🚨 发现 ${newAlerts} 个新预警！`);
          this.callbacks.onNewAlert(newAlerts, stats.data);
        }

        // 检查各类预警数量变化
        const changes = this.detectChanges(this.lastStats, stats.data);
        if (changes.length > 0) {
          console.log('📊 预警统计变化:', changes);
          this.callbacks.onAlertChange(changes, stats.data);
        }
      }

      this.lastStats = stats.data;
    } catch (error) {
      console.error('监控预警失败:', error.message);
      this.callbacks.onError(error);
    }
  }

  detectChanges(oldStats, newStats) {
    const changes = [];
    const fields = ['lowBattery', 'offline', 'highTemperature', 'abnormalMovement'];
    
    fields.forEach(field => {
      const oldValue = oldStats[field] || 0;
      const newValue = newStats[field] || 0;
      const diff = newValue - oldValue;
      
      if (diff !== 0) {
        changes.push({
          type: field,
          oldValue,
          newValue,
          diff
        });
      }
    });
    
    return changes;
  }
}

// 监控示例
async function demonstrateMonitoring() {
  console.log('\n🔍 预警监控示例\n');
  
  const client = new SmartEartagAlertClient();
  const monitor = new AlertMonitor(client, {
    interval: 10000, // 10秒检查一次
    onNewAlert: (count, stats) => {
      console.log(`🚨 发现 ${count} 个新预警！当前总计: ${stats.totalAlerts}`);
    },
    onAlertChange: (changes, stats) => {
      changes.forEach(change => {
        const direction = change.diff > 0 ? '增加' : '减少';
        console.log(`📊 ${change.type} 预警${direction} ${Math.abs(change.diff)} 个`);
      });
    },
    onError: (error) => {
      console.error('监控错误:', error.message);
    }
  });

  // 开始监控
  monitor.start();

  // 30秒后停止监控
  setTimeout(() => {
    monitor.stop();
    console.log('监控示例结束');
  }, 30000);
}

// 如果直接运行此文件
if (require.main === module) {
  // 运行基本使用示例
  demonstrateUsage().then(() => {
    // 运行监控示例
    return demonstrateMonitoring();
  }).catch(console.error);
}

// 导出类和函数
module.exports = {
  SmartEartagAlertClient,
  AlertMonitor,
  demonstrateUsage,
  demonstrateMonitoring
};
