/**
 * 种子数据: farm_data
 * 创建时间: 2023-01-02T00:00:00.000Z
 * 描述: 农场、动物、设备和预警数据
 */
'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    // 插入农场数据
    await queryInterface.bulkInsert('farms', [
      {
        name: '阳光农场',
        type: '养猪场',
        location: JSON.stringify({ lat: 39.9042, lng: 116.4074 }),
        address: '北京市朝阳区农场路1号',
        contact: '张三',
        phone: '13800138001',
        status: 'active',
        created_at: new Date(),
        updated_at: new Date()
      },
      {
        name: '绿野牧场',
        type: '养牛场',
        location: JSON.stringify({ lat: 31.2304, lng: 121.4737 }),
        address: '上海市浦东新区牧场路2号',
        contact: '李四',
        phone: '13800138002',
        status: 'active',
        created_at: new Date(),
        updated_at: new Date()
      },
      {
        name: '山谷羊场',
        type: '养羊场',
        location: JSON.stringify({ lat: 23.1291, lng: 113.2644 }),
        address: '广州市天河区山谷路3号',
        contact: '王五',
        phone: '13800138003',
        status: 'active',
        created_at: new Date(),
        updated_at: new Date()
      }
    ]);

    // 获取农场ID
    const farms = await queryInterface.sequelize.query(
      'SELECT id, name FROM farms',
      { type: Sequelize.QueryTypes.SELECT }
    );

    const sunnyFarm = farms.find(farm => farm.name === '阳光农场');
    const greenFarm = farms.find(farm => farm.name === '绿野牧场');
    const valleyFarm = farms.find(farm => farm.name === '山谷羊场');

    // 插入动物数据
    const animalData = [];
    if (sunnyFarm) {
      animalData.push(
        {
          type: '猪',
          count: 1500,
          farmId: sunnyFarm.id,
          health_status: 'healthy',
          last_inspection: new Date(),
          notes: '生长良好',
          created_at: new Date(),
          updated_at: new Date()
        },
        {
          type: '猪',
          count: 300,
          farmId: sunnyFarm.id,
          health_status: 'sick',
          last_inspection: new Date(),
          notes: '需要治疗',
          created_at: new Date(),
          updated_at: new Date()
        }
      );
    }

    if (greenFarm) {
      animalData.push(
        {
          type: '牛',
          count: 800,
          farmId: greenFarm.id,
          health_status: 'healthy',
          last_inspection: new Date(),
          notes: '健康状况良好',
          created_at: new Date(),
          updated_at: new Date()
        },
        {
          type: '牛',
          count: 50,
          farmId: greenFarm.id,
          health_status: 'quarantine',
          last_inspection: new Date(),
          notes: '隔离观察',
          created_at: new Date(),
          updated_at: new Date()
        }
      );
    }

    if (valleyFarm) {
      animalData.push(
        {
          type: '羊',
          count: 600,
          farmId: valleyFarm.id,
          health_status: 'healthy',
          last_inspection: new Date(),
          notes: '状态良好',
          created_at: new Date(),
          updated_at: new Date()
        }
      );
    }

    await queryInterface.bulkInsert('animals', animalData);

    // 插入设备数据
    const deviceData = [];
    const deviceTypes = ['温度传感器', '湿度传感器', '摄像头', '喂食器'];
    const deviceStatuses = ['online', 'offline', 'maintenance'];

    farms.forEach(farm => {
      deviceTypes.forEach((type, index) => {
        const count = Math.floor(Math.random() * 20) + 10; // 10-30个设备
        for (let i = 0; i < count; i++) {
          const status = deviceStatuses[Math.floor(Math.random() * deviceStatuses.length)];
          deviceData.push({
            name: `${type}_${farm.name}_${i + 1}`,
            type: type,
            status: status,
            farmId: farm.id,
            last_maintenance: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000), // 随机过去30天内
            installation_date: new Date(Date.now() - Math.random() * 365 * 24 * 60 * 60 * 1000), // 随机过去一年内
            metrics: JSON.stringify({
              temperature: Math.round((Math.random() * 10 + 20) * 10) / 10,
              humidity: Math.round((Math.random() * 30 + 50) * 10) / 10
            }),
            created_at: new Date(),
            updated_at: new Date()
          });
        }
      });
    });

    await queryInterface.bulkInsert('devices', deviceData);

    // 获取设备ID
    const devices = await queryInterface.sequelize.query(
      'SELECT id, farmId FROM devices',
      { type: Sequelize.QueryTypes.SELECT }
    );

    // 插入预警数据
    const alertData = [];
    const alertTypes = ['温度异常', '湿度异常', '设备故障', '电源异常'];
    const alertLevels = ['low', 'medium', 'high', 'critical'];
    const alertStatuses = ['active', 'acknowledged', 'resolved'];

    farms.forEach(farm => {
      // 每个农场生成5-15个预警
      const alertCount = Math.floor(Math.random() * 10) + 5;
      for (let i = 0; i < alertCount; i++) {
        const type = alertTypes[Math.floor(Math.random() * alertTypes.length)];
        const level = alertLevels[Math.floor(Math.random() * alertLevels.length)];
        const status = alertStatuses[Math.floor(Math.random() * alertStatuses.length)];
        const farmDevices = devices.filter(device => device.farmId === farm.id);
        const device = farmDevices[Math.floor(Math.random() * farmDevices.length)];

        alertData.push({
          type: type,
          level: level,
          message: `${type}：${farm.name}发生${type}`,
          status: status,
          farmId: farm.id,
          deviceId: device ? device.id : null,
          resolved_at: status === 'resolved' ? new Date() : null,
          resolved_by: status === 'resolved' ? 1 : null,
          resolution_notes: status === 'resolved' ? '问题已解决' : null,
          created_at: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000), // 随机过去7天内
          updated_at: new Date()
        });
      }
    });

    await queryInterface.bulkInsert('alerts', alertData);
  },

  down: async (queryInterface, Sequelize) => {
    // 按照依赖关系的相反顺序删除数据
    await queryInterface.bulkDelete('alerts', null, {});
    await queryInterface.bulkDelete('devices', null, {});
    await queryInterface.bulkDelete('animals', null, {});
    await queryInterface.bulkDelete('farms', null, {});
  }
};