export const mysqlSchema = {
  id: 'mysql',
  name: 'MySQL',
  icon: 'Coin',
  category: '数据库',
  description: '世界上最流行的开源关系型数据库',
  format: 'cnf',
  fileName: 'my.cnf',
  groups: [
    {
      title: '基础配置',
      fields: [
        {
          key: 'version',
          label: 'MySQL 版本',
          type: 'select',
          options: [
            { label: 'MySQL 8.0 (推荐)', value: '8.0' },
            { label: 'MySQL 5.7', value: '5.7' },
          ],
          default: '8.0',
        },
        {
          key: 'port',
          label: '监听端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 3306,
        },
        {
          key: 'bindAddress',
          label: '绑定地址',
          type: 'text',
          default: '0.0.0.0',
        },
        {
          key: 'datadir',
          label: '数据目录',
          type: 'text',
          default: '/var/lib/mysql',
        },
        {
          key: 'socket',
          label: 'Socket 文件路径',
          type: 'text',
          default: '/var/run/mysqld/mysqld.sock',
        },
        {
          key: 'characterSet',
          label: '字符集',
          type: 'select',
          options: [
            { label: 'utf8mb4 (推荐，支持完整 Unicode)', value: 'utf8mb4' },
            { label: 'utf8', value: 'utf8' },
            { label: 'latin1', value: 'latin1' },
          ],
          default: 'utf8mb4',
        },
        {
          key: 'collation',
          label: '排序规则',
          type: 'select',
          options: [
            { label: 'utf8mb4_general_ci (通用，性能好)', value: 'utf8mb4_general_ci' },
            { label: 'utf8mb4_unicode_ci (Unicode 标准)', value: 'utf8mb4_unicode_ci' },
            { label: 'utf8mb4_0900_ai_ci (MySQL 8.0 默认)', value: 'utf8mb4_0900_ai_ci' },
          ],
          default: 'utf8mb4_general_ci',
        },
        {
          key: 'timezone',
          label: '时区',
          type: 'select',
          options: [
            { label: '+08:00 (中国标准时间)', value: '+08:00' },
            { label: 'SYSTEM (跟随系统)', value: 'SYSTEM' },
            { label: '+00:00 (UTC)', value: '+00:00' },
          ],
          default: '+08:00',
        },
      ],
    },
    {
      title: '内存与性能',
      fields: [
        {
          key: 'serverMemory',
          label: '服务器总内存',
          type: 'select',
          options: [
            { label: '2GB', value: '2' },
            { label: '4GB', value: '4' },
            { label: '8GB', value: '8' },
            { label: '16GB', value: '16' },
            { label: '32GB', value: '32' },
            { label: '64GB', value: '64' },
          ],
          default: '8',
          tip: '用于自动计算 Buffer Pool 等参数',
        },
        {
          key: 'maxConnections',
          label: '最大连接数',
          type: 'number',
          min: 10,
          max: 10000,
          default: 500,
        },
        {
          key: 'innodbBufferPoolSize',
          label: 'InnoDB Buffer Pool 大小',
          type: 'select',
          options: [
            { label: '自动计算 (推荐)', value: 'auto' },
            { label: '256M', value: '256M' },
            { label: '512M', value: '512M' },
            { label: '1G', value: '1G' },
            { label: '2G', value: '2G' },
            { label: '4G', value: '4G' },
            { label: '8G', value: '8G' },
            { label: '16G', value: '16G' },
          ],
          default: 'auto',
          tip: '通常设为服务器内存的 60-80%',
        },
        {
          key: 'innodbLogFileSize',
          label: 'Redo Log 文件大小',
          type: 'select',
          options: [
            { label: '256M', value: '256M' },
            { label: '512M', value: '512M' },
            { label: '1G', value: '1G' },
          ],
          default: '256M',
        },
        {
          key: 'innodbFlushLogAtTrxCommit',
          label: '事务日志刷盘策略',
          type: 'select',
          options: [
            { label: '1 - 每次事务提交都刷盘 (最安全)', value: '1' },
            { label: '2 - 每秒刷盘 (性能与安全平衡)', value: '2' },
            { label: '0 - 由操作系统决定 (性能最高)', value: '0' },
          ],
          default: '1',
        },
        {
          key: 'innodbIoCapacity',
          label: 'IO 容量 (IOPS)',
          type: 'select',
          options: [
            { label: '200 (HDD 机械硬盘)', value: '200' },
            { label: '1000 (普通 SSD)', value: '1000' },
            { label: '2000 (高性能 SSD)', value: '2000' },
            { label: '10000 (NVMe SSD)', value: '10000' },
          ],
          default: '2000',
        },
      ],
    },
    {
      title: '查询优化',
      fields: [
        {
          key: 'queryCacheType',
          label: '查询缓存 (仅 5.7)',
          type: 'select',
          options: [
            { label: '关闭 (MySQL 8.0 已移除)', value: '0' },
            { label: '按需开启', value: '1' },
            { label: '全部开启', value: '2' },
          ],
          default: '0',
          dependsOn: { key: 'version', value: '5.7' },
        },
        {
          key: 'tmpTableSize',
          label: '临时表最大大小',
          type: 'select',
          options: [
            { label: '16M', value: '16M' },
            { label: '32M', value: '32M' },
            { label: '64M', value: '64M' },
            { label: '128M', value: '128M' },
          ],
          default: '64M',
        },
        {
          key: 'maxHeapTableSize',
          label: '内存临时表最大大小',
          type: 'select',
          options: [
            { label: '16M', value: '16M' },
            { label: '32M', value: '32M' },
            { label: '64M', value: '64M' },
            { label: '128M', value: '128M' },
          ],
          default: '64M',
        },
        {
          key: 'sortBufferSize',
          label: '排序缓冲区大小',
          type: 'select',
          options: [
            { label: '256K', value: '256K' },
            { label: '512K', value: '512K' },
            { label: '1M', value: '1M' },
            { label: '2M', value: '2M' },
            { label: '4M', value: '4M' },
          ],
          default: '1M',
        },
        {
          key: 'joinBufferSize',
          label: 'JOIN 缓冲区大小',
          type: 'select',
          options: [
            { label: '256K', value: '256K' },
            { label: '512K', value: '512K' },
            { label: '1M', value: '1M' },
            { label: '2M', value: '2M' },
          ],
          default: '512K',
        },
      ],
    },
    {
      title: '日志配置',
      fields: [
        {
          key: 'enableSlowQueryLog',
          label: '开启慢查询日志',
          type: 'switch',
          default: true,
        },
        {
          key: 'slowQueryLogTime',
          label: '慢查询阈值 (秒)',
          type: 'number',
          min: 0,
          max: 60,
          default: 2,
          dependsOn: { key: 'enableSlowQueryLog', value: true },
          tip: '超过该时间的 SQL 会被记录',
        },
        {
          key: 'enableGeneralLog',
          label: '开启通用查询日志',
          type: 'switch',
          default: false,
          tip: '记录所有 SQL，生产环境不建议开启',
        },
        {
          key: 'enableBinlog',
          label: '开启 Binlog',
          type: 'switch',
          default: true,
          tip: '用于主从复制和数据恢复',
        },
        {
          key: 'binlogFormat',
          label: 'Binlog 格式',
          type: 'select',
          options: [
            { label: 'ROW (推荐，数据一致性最好)', value: 'ROW' },
            { label: 'STATEMENT (记录 SQL 语句)', value: 'STATEMENT' },
            { label: 'MIXED (混合模式)', value: 'MIXED' },
          ],
          default: 'ROW',
          dependsOn: { key: 'enableBinlog', value: true },
        },
        {
          key: 'binlogExpireDays',
          label: 'Binlog 过期天数',
          type: 'number',
          min: 1,
          max: 365,
          default: 15,
          dependsOn: { key: 'enableBinlog', value: true },
        },
      ],
    },
    {
      title: '主从复制',
      fields: [
        {
          key: 'enableReplication',
          label: '开启主从复制',
          type: 'switch',
          default: false,
        },
        {
          key: 'serverId',
          label: 'Server ID',
          type: 'number',
          min: 1,
          max: 4294967295,
          default: 1,
          dependsOn: { key: 'enableReplication', value: true },
          tip: '每个 MySQL 实例必须唯一',
          required: true,
        },
        {
          key: 'replicationRole',
          label: '角色',
          type: 'select',
          options: [
            { label: 'Master (主库)', value: 'master' },
            { label: 'Slave (从库)', value: 'slave' },
          ],
          default: 'master',
          dependsOn: { key: 'enableReplication', value: true },
        },
        {
          key: 'masterHost',
          label: '主库地址',
          type: 'text',
          placeholder: '192.168.1.100',
          default: '',
          dependsOn: { key: 'replicationRole', value: 'slave' },
          required: true,
        },
        {
          key: 'masterPort',
          label: '主库端口',
          type: 'number',
          min: 1,
          max: 65535,
          default: 3306,
          dependsOn: { key: 'replicationRole', value: 'slave' },
        },
        {
          key: 'replicateDoDb',
          label: '复制的数据库',
          type: 'text',
          placeholder: 'mydb (留空复制所有)',
          default: '',
          dependsOn: { key: 'enableReplication', value: true },
        },
      ],
    },
  ],
}

function calculateBufferPoolSize(serverMemory) {
  const mem = parseInt(serverMemory)
  if (mem <= 2) return '512M'
  if (mem <= 4) return '2G'
  if (mem <= 8) return '5G'
  if (mem <= 16) return '10G'
  if (mem <= 32) return '20G'
  return '40G'
}

export function generateMysqlConf(config) {
  const lines = []
  lines.push(`# MySQL 配置文件 - 由 ConfTemplate 生成`)
  lines.push(`# MySQL ${config.version} | 生成时间: ${new Date().toLocaleString('zh-CN')}`)
  lines.push(``)

  const bufferSize = config.innodbBufferPoolSize === 'auto'
    ? calculateBufferPoolSize(config.serverMemory)
    : config.innodbBufferPoolSize

  lines.push(`[mysqld]`)
  lines.push(``)

  // 基础
  lines.push(`# ======================== 基础配置 ========================`)
  lines.push(`port = ${config.port}`)
  lines.push(`bind-address = ${config.bindAddress}`)
  lines.push(`datadir = ${config.datadir}`)
  lines.push(`socket = ${config.socket}`)
  lines.push(`pid-file = /var/run/mysqld/mysqld.pid`)
  lines.push(`default-storage-engine = InnoDB`)
  lines.push(`character-set-server = ${config.characterSet}`)
  lines.push(`collation-server = ${config.collation}`)
  lines.push(`default-time-zone = '${config.timezone}'`)
  lines.push(`lower_case_table_names = 1`)
  lines.push(`skip-name-resolve`)
  lines.push(`skip-external-locking`)

  if (config.enableReplication) {
    lines.push(`server-id = ${config.serverId}`)
  }

  lines.push(``)

  // 连接
  lines.push(`# ======================== 连接配置 ========================`)
  lines.push(`max_connections = ${config.maxConnections}`)
  lines.push(`max_connect_errors = 100000`)
  lines.push(`wait_timeout = 600`)
  lines.push(`interactive_timeout = 600`)
  lines.push(`connect_timeout = 10`)
  lines.push(`max_allowed_packet = 64M`)
  lines.push(`back_log = 256`)
  lines.push(``)

  // 内存与性能
  lines.push(`# ======================== 内存与性能 ========================`)
  lines.push(`innodb_buffer_pool_size = ${bufferSize}`)
  lines.push(`innodb_buffer_pool_instances = ${parseInt(bufferSize) >= 1 ? Math.min(parseInt(bufferSize), 8) : 1}`)
  lines.push(`innodb_log_file_size = ${config.innodbLogFileSize}`)
  lines.push(`innodb_log_buffer_size = 64M`)
  lines.push(`innodb_flush_log_at_trx_commit = ${config.innodbFlushLogAtTrxCommit}`)
  lines.push(`innodb_io_capacity = ${config.innodbIoCapacity}`)
  lines.push(`innodb_io_capacity_max = ${parseInt(config.innodbIoCapacity) * 2}`)
  lines.push(`innodb_flush_method = O_DIRECT`)
  lines.push(`innodb_file_per_table = 1`)
  lines.push(`innodb_open_files = 65535`)
  lines.push(`innodb_read_io_threads = 4`)
  lines.push(`innodb_write_io_threads = 4`)
  lines.push(`innodb_purge_threads = 4`)
  lines.push(`innodb_thread_concurrency = 0`)
  lines.push(``)

  // 查询优化
  lines.push(`# ======================== 查询优化 ========================`)
  lines.push(`tmp_table_size = ${config.tmpTableSize}`)
  lines.push(`max_heap_table_size = ${config.maxHeapTableSize}`)
  lines.push(`sort_buffer_size = ${config.sortBufferSize}`)
  lines.push(`join_buffer_size = ${config.joinBufferSize}`)
  lines.push(`read_buffer_size = 256K`)
  lines.push(`read_rnd_buffer_size = 512K`)
  lines.push(`thread_cache_size = 64`)
  lines.push(`table_open_cache = 4096`)
  lines.push(`table_definition_cache = 2048`)
  lines.push(``)

  if (config.version === '5.7' && config.queryCacheType !== '0') {
    lines.push(`query_cache_type = ${config.queryCacheType}`)
    lines.push(`query_cache_size = 64M`)
    lines.push(``)
  }

  // 日志
  lines.push(`# ======================== 日志配置 ========================`)

  if (config.enableSlowQueryLog) {
    lines.push(`slow_query_log = 1`)
    lines.push(`slow_query_log_file = /var/log/mysql/slow.log`)
    lines.push(`long_query_time = ${config.slowQueryLogTime}`)
    lines.push(`log_queries_not_using_indexes = 1`)
    lines.push(`min_examined_row_limit = 100`)
  } else {
    lines.push(`slow_query_log = 0`)
  }

  if (config.enableGeneralLog) {
    lines.push(`general_log = 1`)
    lines.push(`general_log_file = /var/log/mysql/general.log`)
  }

  lines.push(`log-error = /var/log/mysql/error.log`)

  if (config.enableBinlog) {
    lines.push(`log_bin = /var/log/mysql/mysql-bin`)
    lines.push(`binlog_format = ${config.binlogFormat}`)
    lines.push(`expire_logs_days = ${config.binlogExpireDays}`)
    lines.push(`max_binlog_size = 256M`)
    lines.push(`binlog_cache_size = 4M`)
    lines.push(`sync_binlog = 1`)
  }
  lines.push(``)

  // 主从复制
  if (config.enableReplication) {
    lines.push(`# ======================== 主从复制 ========================`)

    if (config.replicationRole === 'master') {
      lines.push(`# Master 配置`)
      lines.push(`binlog_do_db = ${config.replicateDoDb || '(所有数据库)'}`)
      lines.push(``)
      lines.push(`# 在主库创建复制用户:`)
      lines.push(`# CREATE USER 'repl'@'%' IDENTIFIED BY 'strong_password';`)
      lines.push(`# GRANT REPLICATION SLAVE ON *.* TO 'repl'@'%';`)
      lines.push(`# FLUSH PRIVILEGES;`)
    } else {
      lines.push(`# Slave 配置`)
      lines.push(`relay-log = /var/log/mysql/relay-bin`)
      lines.push(`read_only = 1`)
      lines.push(`super_read_only = 1`)
      lines.push(`log_slave_updates = 1`)
      if (config.replicateDoDb) {
        lines.push(`replicate-do-db = ${config.replicateDoDb}`)
      }
      lines.push(``)
      lines.push(`# 在从库执行以下命令配置主库信息:`)
      lines.push(`# CHANGE MASTER TO`)
      lines.push(`#   MASTER_HOST='${config.masterHost || 'MASTER_IP'}',`)
      lines.push(`#   MASTER_PORT=${config.masterPort},`)
      lines.push(`#   MASTER_USER='repl',`)
      lines.push(`#   MASTER_PASSWORD='strong_password',`)
      lines.push(`#   MASTER_AUTO_POSITION=1;`)
      lines.push(`# START SLAVE;`)
    }
    lines.push(``)
  }

  // 安全
  lines.push(`# ======================== 安全配置 ========================`)
  lines.push(`sql_mode = STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION`)

  if (config.version === '8.0') {
    lines.push(`authentication_policy = mysql_native_password`)
  }

  lines.push(``)
  lines.push(`[client]`)
  lines.push(`port = ${config.port}`)
  lines.push(`socket = ${config.socket}`)
  lines.push(`default-character-set = ${config.characterSet}`)

  return lines.join('\n')
}
