section_bloc.dart 8.57 KB
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wow_english/common/request/dao/lesson_dao.dart';
import 'package:wow_english/common/request/exception.dart';
import 'package:wow_english/common/request/dao/listen_dao.dart';
import 'package:wow_english/models/course_process_entity.dart';
import 'package:wow_english/utils/loading.dart';
import 'package:wow_english/utils/toast_util.dart';

import '../../../models/course_section_entity.dart';
import '../../../models/course_unit_entity.dart';
import '../../../utils/list_ext.dart';

part 'section_event.dart';

part 'section_state.dart';

class SectionBloc extends Bloc<SectionEvent, SectionState> {
  PageController _pageController;

  PageController get pageController => _pageController;

  ///当前页索引
  int _currentPage = 0;

  int get currentPage => _currentPage;

  ScrollController _listController;

  ScrollController get listController => _listController;

  ScrollController _indicatorSrollController;

  ScrollController get indicatorSrollController => _indicatorSrollController;

  CourseUnitEntity _courseUnitEntity;

  CourseUnitEntity get courseUnitEntity => _courseUnitEntity;

  ///courseUnitId与课程环节列表的映射
  final Map<int, List<CourseSectionEntity>?> _courseSectionDatasMap = {};

  Map<int, List<CourseSectionEntity>?> get courseSectionDatasMap =>
      _courseSectionDatasMap;

  CourseProcessEntity? _processEntity;

  CourseProcessEntity? get processEntity => _processEntity;

  SectionBloc(this._courseUnitEntity, this._currentPage, this._pageController,
      this._listController, this._indicatorSrollController)
      : super(LessonInitial()) {
    on<RequestDataEvent>(_requestSectionsData);
    on<RequestEndClassEvent>(_requestEndClass);
    on<RequestEnterClassEvent>(_requestEnterClass);
    on<RequestVideoLessonEvent>(_requestVideoLesson);
    on<CurrentUnitIndexChangeEvent>(_pageControllerChange);
  }

  void _requestSectionsData(
      RequestDataEvent event, Emitter<SectionState> emitter) async {
    try {
      await loading(() async {
        _courseSectionDatasMap[event.courseUnitId] =
            await LessonDao.courseSection(courseUnitId: event.courseUnitId);
        emitter(LessonDataLoadState());
      });
    } catch (e) {
      if (e is ApiException) {
        showToast(e.message.toString());
      }
    }
  }

  void _requestVideoLesson(
      RequestVideoLessonEvent event, Emitter<SectionState> emitter) async {
    try {
      await loading(() async {
        _processEntity = await ListenDao.process(event.courseLessonId);
        emitter(
            RequestVideoLessonState(event.courseLessonId, event.courseType));
      });
    } catch (e) {
      if (e is ApiException) {
        showToast(e.message ?? '请求失败,请检查网络连接');
      }
    }
  }

  void _requestEnterClass(
      RequestEnterClassEvent event, Emitter<SectionState> emitter) async {
    try {
      await loading(() async {
        await ListenDao.enterClass(event.courseLessonId);
        emitter(RequestEnterClassState(event.courseLessonId, event.courseType));
      });
    } catch (e) {
      if (e is ApiException) {
        showToast(e.message ?? '请求失败,请检查网络连接');
      }
    }
  }

  void _requestEndClass(
      RequestEndClassEvent event, Emitter<SectionState> emitter) async {
    if (event.isCompleted) {
      await await ListenDao.endClass(event.courseLessonId,
          currentStep: event.currentStep, currentTime: event.currentTime);
    } else {
      await await ListenDao.exitClass(event.courseLessonId,
          currentStep: event.currentStep, currentTime: event.currentTime);
    }
    if (event.autoNextSection) {
      final nextCourseSection =
          await getNextCourseSection(int.parse(event.courseLessonId), emitter);
      if (nextCourseSection != null) {
        ///进入课堂
        add(RequestEnterClassEvent(
            nextCourseSection.id.toString(), nextCourseSection.courseType));
      }
    }
  }

  void _pageControllerChange(
      CurrentUnitIndexChangeEvent event, Emitter<SectionState> emitter) async {
    _currentPage = event.unitIndex;
    double indicatorWidth = 30.0.w; // 指示器宽度

    // 计算选中项的偏移量
    double offset = _currentPage * indicatorWidth -
        (_indicatorSrollController.position.viewportDimension -
                indicatorWidth) /
            2;

    // 确保偏移量在合理范围内
    if (offset < 0) {
      offset = 0;
    } else if (offset >
        unlockPageCount() * indicatorWidth -
            _indicatorSrollController.position.viewportDimension) {
      offset = unlockPageCount() * indicatorWidth -
          _indicatorSrollController.position.viewportDimension;
    }
    _indicatorSrollController.animateTo(
      offset,
      duration: const Duration(milliseconds: 250),
      curve: Curves.easeInOut,
    );
    emitter(CurrentPageIndexState());
  }

  ///未锁定的页(单元)数
  int unlockPageCount() {
    return _courseUnitEntity.courseUnitVOList
            ?.indexWhereOrNull((element) => element.lock == true) ??
        _courseUnitEntity.courseUnitVOList?.length ??
        0;
  }

  ///当前页的课程详情
  CourseUnitDetail getCourseUnitDetail({int? pageIndex}) {
    return _courseUnitEntity.courseUnitVOList![pageIndex ?? _currentPage];
  }

  ///根据courseLessonId查找对应的courseSection
  CourseSectionEntity? findCourseSectionById(int courseLessonId) {
    for (var entry in courseSectionDatasMap.entries) {
      var sectionList = entry.value;
      if (sectionList != null) {
        for (var section in sectionList) {
          if (section.id == courseLessonId) {
            return section;
          }
        }
      }
    }
    return null;
  }

  ///根据sortOrder查找对应的courseSection
  CourseSectionEntity? findCourseSectionBySort(int sortOrder) {
    for (var entry in courseSectionDatasMap.entries) {
      var sectionList = entry.value;
      if (sectionList != null) {
        for (var section in sectionList) {
          if (section.sortOrder == sortOrder) {
            return section;
          }
        }
      }
    }
    return null;
  }

  ///根据courseLessonId查找对应的CourseUnitDetail
  CourseUnitDetail? findCourseUnitDetailById(int courseLessonId) {
    final curCourseSectionEntity = findCourseSectionById(courseLessonId);
    if (curCourseSectionEntity != null) {
      final curCourseUnitDetail = _courseUnitEntity.courseUnitVOList
          ?.firstWhere(
              (element) => element.id == curCourseSectionEntity.courseUnitId);
      return curCourseUnitDetail;
    }
    return null;
  }

  ///根据courseLessonId查找下一个courseSection
  Future<CourseSectionEntity?> getNextCourseSection(
      int courseLessonId, Emitter<SectionState> emitter) async {
    final curCourseSectionEntity = findCourseSectionById(courseLessonId);
    final curSectionSort = curCourseSectionEntity?.sortOrder ?? 0;

    ///查找下一个section
    final nextCourseSectionEntity = findCourseSectionBySort(curSectionSort + 1);
    if (nextCourseSectionEntity != null) {
      return nextCourseSectionEntity;
    } else {
      ///section为空说明当前unit学完了,找下一个unit。(跨unit选lesson)
      ///先根据courseLessonId找出当前的unit
      final curCourseUnitDetail = findCourseUnitDetailById(courseLessonId);
      if (curCourseUnitDetail != null) {
        ///再根据当前unit找出下一个unit
        final nextCourseUnitDetail = _courseUnitEntity.courseUnitVOList
            ?.firstWhere((element) =>
                element.sortOrder == (curCourseUnitDetail.sortOrder! + 1));
        if (nextCourseUnitDetail != null) {
          final courseUnitId = nextCourseUnitDetail.id!;
          try {
            await loading(() async {
              _courseSectionDatasMap[courseUnitId] =
                  await LessonDao.courseSection(courseUnitId: courseUnitId);
              emitter(LessonDataLoadState());
            });
            _pageController.nextPage(
              duration: const Duration(milliseconds: 500),
              curve: Curves.ease,
            );
            return _courseSectionDatasMap[courseUnitId]!.first;
          } catch (e) {
            if (e is ApiException) {
              showToast(e.message.toString());
            }
            return null;
          }
        } else {
          ///最后一个unit了
          return null;
        }
      } else {
        ///找不到对应的unitDetail,理论上不可能
        return null;
      }
    }
  }
}