import 'dart:developer' as dev;
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';

/// 数据库服务：管理电池数据持久化
class DatabaseService {
  static Database? _database;
  static const String _tableName = 'battery_data';

  /// 获取数据库实例（单例）
  Future<Database> get database async {
    if (_database != null) return _database!;
    _database = await _initDatabase();
    return _database!;
  }

  /// 初始化数据库
  Future<Database> _initDatabase() async {
    final dbPath = await getDatabasesPath();
    final path = join(dbPath, 'battery_health.db');

    return await openDatabase(
      path,
      version: 1,
      onCreate: (db, version) async {
        await db.execute('''
          CREATE TABLE $_tableName (
            date TEXT PRIMARY KEY,
            capacity INTEGER NOT NULL,
            volt_max REAL NOT NULL,
            volt_min REAL NOT NULL,
            updated_at TEXT NOT NULL
          )
        ''');
        await db.execute('''
          CREATE INDEX idx_date ON $_tableName (date DESC)
        ''');
        dev.log('✅ 数据库表创建成功', name: 'DatabaseService');
      },
    );
  }

  /// 插入或更新数据
  Future<void> insertOrUpdate(
    String date,
    int capacity,
    double voltMax,
    double voltMin,
  ) async {
    final db = await database;
    final now = DateTime.now().toIso8601String();

    await db.insert(_tableName, {
      'date': date,
      'capacity': capacity,
      'volt_max': voltMax,
      'volt_min': voltMin,
      'updated_at': now,
    }, conflictAlgorithm: ConflictAlgorithm.replace);
    dev.log('📝 数据已保存: $date, cap=$capacity', name: 'DatabaseService');
  }

  /// 查询最近 N 条数据（按日期倒序）
  Future<List<Map<String, dynamic>>> queryRecentData(int limit) async {
    final db = await database;
    try {
      final result = await db.query(
        _tableName,
        orderBy: 'date DESC',
        limit: limit,
      );
      return result;
    } catch (e) {
      dev.log('⚠️ 查询数据失败: $e', name: 'DatabaseService');
      return [];
    }
  }

  /// 🟢 1.4.5 新增：查询指定日期数据
  Future<Map<String, dynamic>?> queryByDate(String date) async {
    final db = await database;
    try {
      final result = await db.query(
        _tableName,
        where: 'date = ?',
        whereArgs: [date],
      );
      return result.isNotEmpty ? result.first : null;
    } catch (e) {
      dev.log('⚠️ 查询单日数据失败: $e', name: 'DatabaseService');
      return null;
    }
  }

  /// 删除指定日期数据
  Future<void> deleteByDate(String date) async {
    final db = await database;
    await db.delete(_tableName, where: 'date = ?', whereArgs: [date]);
  }

  /// 获取数据库中所有日期列表
  Future<List<String>> getAllDates() async {
    final db = await database;
    try {
      final result = await db.query(
        _tableName,
        columns: ['date'],
        orderBy: 'date DESC',
      );
      return result.map((row) => row['date'] as String).toList();
    } catch (e) {
      return [];
    }
  }

  /// 清空所有数据
  Future<void> clearAll() async {
    final db = await database;
    await db.delete(_tableName);
    dev.log('🗑️ 所有数据已清空', name: 'DatabaseService');
  }

  /// 关闭数据库
  Future<void> close() async {
    if (_database != null) {
      await _database!.close();
      _database = null;
    }
  }
}
