part of utils;

class SqlManager {

  static const _version = 1;

  static const _name= "zi_jing_app_flutter.db";

  static Database? _database;



  ///初始化
  static init() async {
    // open the database
    var databasesPath = await getDatabasesPath();
    // var databasesPath = await Tools.getDirectory();
    String dbName = _name;
    Console.log('Sql-----------databasesPath---------$databasesPath');
    if(databasesPath != null) {
      String path = databasesPath + dbName;
      if (Platform.isIOS) {
        path = "$databasesPath/$dbName";
      }
      _database = await openDatabase(path, version: _version,
          onCreate: (Database db, int version) async {
            // When creating the db, create the table
            // await db.execute("CREATE TABLE Test (id INTEGER PRIMARY KEY, name TEXT, value INTEGER, num REAL)");
            // 笔记表
            await db.execute("CREATE TABLE $kNoteTable ("
                "id INTEGER PRIMARY KEY, "
                "types INTEGER, "
                "book_id INTEGER, "
                "chapter_id INTEGER, "
                "node_id INTEGER, "
                "is_open INTEGER, "
                "color TEXT, "
                "content TEXT, "
                "upload INTEGER, "
                "positioning TEXT, "
                "note_content TEXT)"
            );
            // // 阅读章节表
            await db.execute("CREATE TABLE $kReadTable ("
                "id INTEGER PRIMARY KEY, "
                "book_id INTEGER, "
                "chapter_id INTEGER)"
            );
          });
    }
  }

  // 关闭数据库
  static Future<void> closeDatabase() async {
    await _database?.close();
  }

  // 查询所有没有上传的数据
  static Future<List<Map<String, dynamic>>> queryNoUploadData() async {
    List<Map<String, dynamic>> results = await _database!.query(
      'members_book_notes',
      where: 'upload = ?',
      whereArgs: [0],
    );
    return results.isNotEmpty ? results : [];
  }
  // 将所有 upload 为 0 的数据的 upload 字段值更新为 1
  static Future<void> updateUploadStatus() async {
    final result =  await _database!.update(
      'members_book_notes',
      {'upload': 1},
      where: 'upload = ?',
      whereArgs: [0],
    );
    Console.log('Sql---------------更新数据----------------$result');
  }
  // 根据 book_id 查询当前读到的 章节
  static Future<String> queryReadHistoryByBookId(int bookId) async {

    List<Map<String, dynamic>> results = await _database!.query(
      'read_history',
      where: 'book_id = ?',
      whereArgs: [bookId],
    );
    return results.isNotEmpty ? results.first['chapter_id'].toString() : '';
  }

  // 根据 book_id 写入当前读到的 章节
  static Future<int> updateReadHistoryByBookId(int bookId ,int chapterId) async {

     final queryResult = await queryReadHistoryByBookId(bookId);
     if (queryResult.isEmpty){
       Console.log('Sql----------没有当前书籍的数据----------------------');
       final result =  await _database!.insert(
         'read_history',
         {'chapter_id':chapterId, 'book_id':bookId},
         conflictAlgorithm: ConflictAlgorithm.replace,
       );
       Console.log('Sql----------插入数据结果：$result----------------------');
       return result;
     }
     else{
       Console.log('Sql----------有当前书籍的数据----------------------');
       final result =  await _database!.update(
         'read_history',
         {'chapter_id':chapterId},
         where: 'book_id = ?',
         whereArgs: [bookId],
       );
       Console.log('Sql----------更新数据结果：$result----------------------');
       return result;
     }
  }



  // 插入数据
  static Future<bool> insertData(Map<String, dynamic> data) async {
    final result =  await _database?.insert(
      'members_book_notes',
      data,
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
    if (result !=null){
      return true;
    }
    return false;
    Console.log('插入数据-------------------------------$result');
  }


  // 查询所有数据
  static Future<List<Map<String, dynamic>>?> queryAllData() async {
    return await _database?.query('members_book_notes');
  }

  // 根据 ID 查询数据
  static Future<Map<String, dynamic>?> queryDataById(int id) async {
    List<Map<String, dynamic>> results = await _database!.query(
      'members_book_notes',
      where: 'id = ?',
      whereArgs: [id],
    );
    return results.isNotEmpty ? results.first : null;
  }

  // 更新数据
  static Future<void> updateData(int id, Map<String, dynamic> newData) async {
    await _database?.update(
      'members_book_notes',
      newData,
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  // 删除数据
  static Future<void> deleteData(int id) async {
    await _database?.delete(
      'members_book_notes',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

}
