import '../../../core/database/database_service.dart';
import '../models/program.dart';
import '../models/step.dart';

/// 程序服务
/// 封装程序和步骤的数据库操作
class ProgramService {
  static final ProgramService instance = ProgramService._internal();
  final DatabaseService _db = DatabaseService.instance;

  ProgramService._internal();

  /// 获取所有程序
  Future<List<Program>> getAllPrograms() async {
    final database = await _db.database;
    final maps = await database.query('programs', orderBy: 'created_at DESC');
    return maps.map((m) => Program.fromMap(m)).toList();
  }

  /// 根据ID获取程序
  Future<Program?> getProgramById(int id) async {
    final database = await _db.database;
    final maps = await database.query(
      'programs',
      where: 'id = ?',
      whereArgs: [id],
    );
    if (maps.isEmpty) return null;
    return Program.fromMap(maps.first);
  }

  /// 新增程序
  Future<int> addProgram(Program program) async {
    final database = await _db.database;
    return await database.insert('programs', program.toMap());
  }

  /// 更新程序
  Future<bool> updateProgram(Program program) async {
    if (program.id == null) return false;
    final database = await _db.database;
    final count = await database.update(
      'programs',
      program.toMap(),
      where: 'id = ?',
      whereArgs: [program.id],
    );
    return count > 0;
  }

  /// 删除程序（含步骤）
  Future<bool> deleteProgram(int id) async {
    final database = await _db.database;
    // 先删除关联的步骤
    await database.delete('steps', where: 'program_id = ?', whereArgs: [id]);
    // 再删除程序
    final count = await database.delete('programs', where: 'id = ?', whereArgs: [id]);
    return count > 0;
  }

  /// 批量删除程序
  Future<bool> deletePrograms(List<int> ids) async {
    if (ids.isEmpty) return true;
    final database = await _db.database;
    // 先删除关联的步骤
    await database.delete(
      'steps',
      where: 'program_id IN (${ids.map((_) => '?').join(',')})',
      whereArgs: ids,
    );
    // 再删除程序
    final count = await database.delete(
      'programs',
      where: 'id IN (${ids.map((_) => '?').join(',')})',
      whereArgs: ids,
    );
    return count > 0;
  }

  /// 切换程序状态
  Future<bool> toggleProgramStatus(int id) async {
    final database = await _db.database;
    final program = await getProgramById(id);
    if (program == null) return false;
    final count = await database.update(
      'programs',
      {'status': program.status == 1 ? 0 : 1},
      where: 'id = ?',
      whereArgs: [id],
    );
    return count > 0;
  }

  /// 获取程序的步骤列表
  Future<List<Step>> getStepsByProgramId(int programId) async {
    final database = await _db.database;
    final maps = await database.query(
      'steps',
      where: 'program_id = ?',
      whereArgs: [programId],
      orderBy: 'step_no ASC',
    );
    return maps.map((m) => Step.fromMap(m)).toList();
  }

  /// 新增步骤
  Future<int> addStep(Step step) async {
    final database = await _db.database;
    return await database.insert('steps', step.toMap());
  }

  /// 更新步骤
  Future<bool> updateStep(Step step) async {
    if (step.id == null) return false;
    final database = await _db.database;
    final count = await database.update(
      'steps',
      step.toMap(),
      where: 'id = ?',
      whereArgs: [step.id],
    );
    return count > 0;
  }

  /// 删除步骤
  Future<bool> deleteStep(int id) async {
    final database = await _db.database;
    final count = await database.delete('steps', where: 'id = ?', whereArgs: [id]);
    return count > 0;
  }

  /// 批量删除步骤
  Future<bool> deleteSteps(List<int> ids) async {
    if (ids.isEmpty) return true;
    final database = await _db.database;
    final count = await database.delete(
      'steps',
      where: 'id IN (${ids.map((_) => '?').join(',')})',
      whereArgs: ids,
    );
    return count > 0;
  }

  /// 更新步骤排序
  Future<void> reorderSteps(int programId, List<int> stepIds) async {
    final database = await _db.database;
    for (int i = 0; i < stepIds.length; i++) {
      await database.update(
        'steps',
        {'step_no': i + 1},
        where: 'id = ? AND program_id = ?',
        whereArgs: [stepIds[i], programId],
      );
    }
  }
}