const config = require('../config/index');
const mysql = require('mysql2/promise');

// 初始化无害化场所表
async function initHarmlessPlaceTable() {
  let connection = null;
  try {
    // 创建数据库连接
    console.log('测试数据库连接...');
    connection = await mysql.createConnection({
      host: config.DB_CONFIG.host,
      port: config.DB_CONFIG.port,
      user: config.DB_CONFIG.user,
      password: config.DB_CONFIG.password,
      database: config.DB_CONFIG.database
    });
    console.log('数据库连接成功');
    
    // 检查表是否存在
    console.log('检查无害化场所表是否存在...');
    const [tables] = await connection.execute(
      "SHOW TABLES LIKE 'government_harmless_places'"
    );
    
    // 如果表存在，删除它
    if (tables.length > 0) {
      console.log('无害化场所表已存在，删除它...');
      await connection.execute('DROP TABLE government_harmless_places');
      console.log('无害化场所表删除成功');
    }
    
    // 创建无害化场所表
    console.log('创建无害化场所表...');
    await connection.execute(`
      CREATE TABLE government_harmless_places (
        id VARCHAR(36) PRIMARY KEY NOT NULL,
        name VARCHAR(100) NOT NULL COMMENT '场所名称',
        address VARCHAR(255) NOT NULL COMMENT '地址',
        contact_person VARCHAR(50) NOT NULL COMMENT '联系人',
        contact_phone VARCHAR(20) NOT NULL COMMENT '联系电话',
        license_number VARCHAR(50) NOT NULL UNIQUE COMMENT '许可证号',
        status ENUM('正常', '维护中', '停用') NOT NULL DEFAULT '正常' COMMENT '状态',
        create_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
        update_time DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
        INDEX idx_name (name),
        INDEX idx_license_number (license_number),
        INDEX idx_status (status)
      ) COMMENT '无害化场所管理表'
    `);

    console.log('无害化场所表创建成功！');
    
    // 添加测试数据
    console.log('开始添加测试数据...');
    const testData = [
      [
        '1', '银川市无害化处理中心', '宁夏银川市金凤区科技园路88号', 
        '张经理', '13895112345', 'HP20240001', '正常',
        '2024-06-01 10:00:00', '2024-06-01 10:00:00'
      ],
      [
        '2', '石嘴山市无害化处理站', '宁夏石嘴山市大武口区环保路56号', 
        '李站长', '13995123456', 'HP20240002', '正常',
        '2024-06-02 11:30:00', '2024-06-02 11:30:00'
      ],
      [
        '3', '吴忠市无害化处理厂', '宁夏吴忠市利通区产业路34号', 
        '王厂长', '13795134567', 'HP20240003', '维护中',
        '2024-06-03 09:15:00', '2024-06-10 14:20:00'
      ],
      [
        '4', '固原市无害化处理中心', '宁夏固原市原州区生态路12号', 
        '赵主任', '13695145678', 'HP20240004', '正常',
        '2024-06-04 14:45:00', '2024-06-04 14:45:00'
      ],
      [
        '5', '中卫市无害化处理站', '宁夏中卫市沙坡头区环卫路23号', 
        '孙主任', '13595156789', 'HP20240005', '停用',
        '2024-06-05 16:20:00', '2024-06-15 09:30:00'
      ]
    ];
    
    // 批量插入数据
    for (const row of testData) {
      await connection.execute(
        `INSERT INTO government_harmless_places 
        (id, name, address, contact_person, contact_phone, license_number, status, create_time, update_time) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
        row
      );
    }
    
    console.log('测试数据添加成功！');
    console.log('无害化场所表初始化完成！');
  } catch (error) {
    console.error('初始化无害化场所表失败:', error);
    throw error;
  } finally {
    // 关闭数据库连接
    if (connection) {
      await connection.end();
      console.log('数据库连接已关闭');
    }
  }
}

// 执行初始化
if (require.main === module) {
  initHarmlessPlaceTable().catch(err => {
    console.error('程序执行失败:', err);
    process.exit(1);
  });
}

module.exports = initHarmlessPlaceTable;