const mysql = require('mysql');

// 创建数据库连接池
const pool = mysql.createPool({
  host: 'localhost',
  user: 'root',
  password: 'root',
  database: 'plan'
});

// 封装查询方法
function query(sql, values) {
  return new Promise((resolve, reject) => {
    pool.getConnection(function(err, connection) {
      if (err) {
        reject(err);
        return;
      }

      connection.query(sql, values, function(error, results, fields) {
        connection.release(); // 释放连接
        if (error) {
          reject(error);
        } else {
          resolve(results);
        }
      });
    });
  });
}

// 查询表结构
async function getTableStructure(tableName) {
  try {
    const results = await query(`SHOW COLUMNS FROM ${tableName}`);
    const fields = {};
    results.forEach(row => {
      const fieldName = row.Field;
      const fieldType = row.Type;
      const fieldLength = fieldType.match(/\((\d+)\)/)[1];
      const isUnsigned = fieldType.includes('unsigned');
      const defaultValue = row.Default;
      const comment = row.Comment;

      // 将字段类型转换为统一的类型
      let type = '';
      if (fieldType.includes('int')) {
        type = 'integer';
      } else if (fieldType.includes('char') || fieldType.includes('text')) {
        type = 'string';
      } else if (fieldType.includes('date') || fieldType.includes('time')) {
        type = 'date';
      }

      fields[fieldName] = {
        type,
        length: fieldLength,
        unsigned: isUnsigned,
        default: defaultValue,
        meta: {
          comment: comment
        }
      };
    });

    return fields;
  } catch (err) {
    console.error(err);
    return null;
  }
}

// 获取数据库中的所有表
async function getAllTables() {
  try {
    const results = await query('SHOW TABLES');
    const tables = [];
    results.forEach(row => {
      console.log("row",row.Tables_in_plan)
      tables.push(row.Tables_in_plan);
    });
    return tables;
  } catch (err) {
    // console.error(err);
    return null;
  }
}

// 主函数
async function parseSql() {
  const tables = {};
  const tableNames = await getAllTables();

  // 遍历每张表，获取表结构
  for (const tableName of tableNames) {
    const fields = await getTableStructure(tableName);
    if (fields) {
      tables[tableName] = {
        mode: 'simple',
        modelCn: tableName,
        fields,
        foreign: {},
        extendActions: {},
        primaryKey: '',
        middlewares: ['loginRequired']
      };
    }
  }

  return tables;
}

// 调用主函数
parseSql().then(tables => {
  console.log(tables);
}).catch(err => {
  console.error(err);
});
