const { Device, DeviceAlert, User } = require('../models');

async function createTestData() {
  try {
    console.log('开始创建测试数据...');

    // 获取第一个用户作为创建者
    const user = await User.findOne();
    if (!user) {
      console.log('❌ 没有找到用户，请先创建用户');
      return;
    }

    // 检查是否已有测试设备
    const existingDevice = await Device.findOne({ where: { device_number: 'DEV001' } });
    let devices;
    
    if (existingDevice) {
      console.log('📋 测试设备已存在，使用现有设备');
      devices = await Device.findAll({
        where: {
          device_number: ['DEV001', 'DEV002', 'DEV003']
        }
      });
    } else {
      // 创建测试设备
      devices = await Device.bulkCreate([
      {
        device_number: 'DEV001',
        device_name: '温度传感器A',
        device_type: '温度传感器',
        device_model: 'TMP-100',
        manufacturer: '智能科技',
        installation_location: '1号栏舍',
        installation_date: new Date('2024-01-15'),
        status: 'normal',
        farm_id: 1,
        barn_id: 1,
        created_by: user.id,
        updated_by: user.id
      },
      {
        device_number: 'DEV002',
        device_name: '湿度传感器B',
        device_type: '湿度传感器',
        device_model: 'HUM-200',
        manufacturer: '智能科技',
        installation_location: '2号栏舍',
        installation_date: new Date('2024-01-20'),
        status: 'warning',
        farm_id: 1,
        barn_id: 2,
        created_by: user.id,
        updated_by: user.id
      },
      {
        device_number: 'DEV003',
        device_name: '监控摄像头C',
        device_type: '监控设备',
        device_model: 'CAM-300',
        manufacturer: '安防科技',
        installation_location: '3号栏舍',
        installation_date: new Date('2024-02-01'),
        status: 'error',
        farm_id: 1,
        barn_id: 3,
        created_by: user.id,
        updated_by: user.id
      }
    ]);
    
    console.log(`✅ 创建了 ${devices.length} 个测试设备`);
    }

    console.log(`📊 当前有 ${devices.length} 个测试设备`);

    // 检查是否已有测试预警
    const existingAlert = await DeviceAlert.findOne({ where: { device_id: devices[0].id } });
    let alerts;
    
    if (existingAlert) {
      console.log('📋 测试预警已存在，清除旧数据并创建新数据');
      await DeviceAlert.destroy({ where: { device_id: devices.map(d => d.id) } });
    }
    
    // 创建测试预警
    alerts = await DeviceAlert.bulkCreate([
      {
        device_id: devices[0].id,
        alert_type: 'temperature',
        alert_level: 'warning',
        alert_title: '温度异常',
        alert_content: '1号栏舍温度传感器检测到温度过高，当前温度35°C',
        alert_time: new Date(),
        status: 'pending',
        farm_id: 1,
        barn_id: 1,
        is_read: false
      },
      {
        device_id: devices[1].id,
        alert_type: 'humidity',
        alert_level: 'critical',
        alert_title: '湿度严重异常',
        alert_content: '2号栏舍湿度传感器检测到湿度过低，当前湿度30%',
        alert_time: new Date(Date.now() - 2 * 60 * 60 * 1000), // 2小时前
        status: 'pending',
        farm_id: 1,
        barn_id: 2,
        is_read: false
      },
      {
        device_id: devices[2].id,
        alert_type: 'offline',
        alert_level: 'critical',
        alert_title: '设备离线',
        alert_content: '3号栏舍监控摄像头已离线超过30分钟',
        alert_time: new Date(Date.now() - 4 * 60 * 60 * 1000), // 4小时前
        status: 'pending',
        farm_id: 1,
        barn_id: 3,
        is_read: true,
        read_time: new Date(Date.now() - 3 * 60 * 60 * 1000)
      },
      {
        device_id: devices[0].id,
        alert_type: 'maintenance',
        alert_level: 'info',
        alert_title: '设备维护提醒',
        alert_content: '温度传感器A需要进行定期维护检查',
        alert_time: new Date(Date.now() - 24 * 60 * 60 * 1000), // 1天前
        status: 'resolved',
        handler_id: user.id,
        handle_time: new Date(Date.now() - 20 * 60 * 60 * 1000),
        handle_note: '已完成维护检查，设备运行正常',
        farm_id: 1,
        barn_id: 1,
        is_read: true,
        read_time: new Date(Date.now() - 23 * 60 * 60 * 1000)
      }
    ]);

    console.log(`✅ 创建了 ${alerts.length} 个测试预警`);
    console.log('🎉 测试数据创建完成！');

  } catch (error) {
    console.error('❌ 创建测试数据失败:', error);
  }
}

// 如果直接运行此脚本
if (require.main === module) {
  createTestData().then(() => {
    process.exit(0);
  }).catch(error => {
    console.error(error);
    process.exit(1);
  });
}

module.exports = createTestData;