const sequelize = require('../config/database');
const Slaughterhouse = require('../models/Slaughterhouse');

// 初始化屠宰场表并添加测试数据
const initSlaughterhouseData = async () => {
  try {
    // 先删除旧表，再重新创建
    await Slaughterhouse.drop().catch(() => console.log('旧表不存在，跳过删除'));
    await sequelize.sync({ force: true });
    console.log('数据库同步成功，表已重新创建');

    // 检查是否已有数据
    const existingCount = await Slaughterhouse.count();
    if (existingCount > 0) {
      console.log(`已存在 ${existingCount} 条屠宰场数据，跳过初始化`);
      return;
    }

    // 准备测试数据
    const testData = [
      {
        name: '宁夏银川市第一屠宰场',
        address: '宁夏回族自治区银川市金凤区良田镇植物园路',
        contactPerson: '张明',
        contactPhone: '13800138001',
        licenseNumber: 'SC1234567890123',
        status: 'active',
        createTime: new Date('2023-01-15'),
        created_by: 1,
        updated_by: 1
      },
      {
        name: '宁夏石嘴山市肉类加工厂',
        address: '宁夏回族自治区石嘴山市大武口区星海镇',
        contactPerson: '李强',
        contactPhone: '13900139002',
        licenseNumber: 'SC1234567890124',
        status: 'active',
        createTime: new Date('2023-02-10'),
        created_by: 1,
        updated_by: 1
      },
      {
        name: '宁夏吴忠市清真屠宰场',
        address: '宁夏回族自治区吴忠市利通区金银滩镇',
        contactPerson: '王芳',
        contactPhone: '13700137003',
        licenseNumber: 'SC1234567890125',
        status: 'active',
        createTime: new Date('2023-03-05'),
        created_by: 1,
        updated_by: 1
      },
      {
        name: '宁夏固原市牲畜屠宰场',
        address: '宁夏回族自治区固原市原州区官厅镇',
        contactPerson: '赵伟',
        contactPhone: '13600136004',
        licenseNumber: 'SC1234567890126',
        status: 'inactive',
        createTime: new Date('2023-04-20'),
        created_by: 1,
        updated_by: 1
      },
      {
        name: '宁夏中卫市肉类屠宰加工中心',
        address: '宁夏回族自治区中卫市沙坡头区迎水桥镇',
        contactPerson: '陈静',
        contactPhone: '13500135005',
        licenseNumber: 'SC1234567890127',
        status: 'active',
        createTime: new Date('2023-05-15'),
        created_by: 1,
        updated_by: 1
      }
    ];

    // 批量创建测试数据
    const createdSlaughterhouses = await Slaughterhouse.bulkCreate(testData);
    console.log(`成功创建 ${createdSlaughterhouses.length} 条屠宰场测试数据`);

  } catch (error) {
    console.error('初始化屠宰场数据失败:', error);
  } finally {
    // 关闭数据库连接
    await sequelize.close();
    console.log('数据库连接已关闭');
  }
};

// 执行初始化函数
initSlaughterhouseData();