import 'dart:async';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flyinsono/architecture/services/entity/local_setting.dart';
import 'package:flyinsono/architecture/services/modules/local_setting_configurations.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/managers/base_manager.dart';
import 'package:flyinsono/pages/college/state.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'interfaces/entities/classInfo.dart';
import 'interfaces/entities/media_library.dart';
import 'interfaces/flyinsono_college.dart';
import 'package:fis_common/event/event_type.dart';
import 'package:fis_common/logger/logger.dart';

class FlyinsonoCollegeManager extends BaseManager
    implements IFlyinsonoCollegeManager {
  final onUpdateLibrary = FEventHandler<bool>();
  final onRecordFilePathUpdate = FEventHandler<String>();
  @override
  String statusTranslation(LiveCourseStatus status) {
    switch (status) {
      case LiveCourseStatus.NotStart:
        return i18nBook.college.notStarted.t;
      case LiveCourseStatus.Replay:
        return i18nBook.college.replay.t;
      case LiveCourseStatus.Livestreaming:
        return i18nBook.college.liveOngoing.t;
    }
  }

  @override
  Future<UserGroupList> getClassInfos({
    ClassRoleType? roleType,
    String? keyword,
    int pageIndex = 1,
    int pageCount = 100,
  }) async {
    final result;
    print(roleType?.index);
    if (roleType == ClassRoleType.Teacher) {
      result = await rpc.education
          .getUserGroupListsByCreatorCodeAsync(QueryUserGroupPageRequest(
        token: Store.user.token,
        pageIndex: pageIndex,
        pageSize: pageCount,
        keyword: keyword,
      ));
      return UserGroupList(
        userGroup: result.pageData,
        totalCount: result.totalCount,
      );
    } else {
      result = await rpc.education.findUserGroupByStudentAsync(
        QueryUserGroupPageRequest(
          token: Store.user.token,
          pageIndex: pageIndex,
          pageSize: pageCount,
          keyword: keyword,
        ),
      );
      return UserGroupList(
        userGroup: result.pageData,
        totalCount: result.totalCount,
      );
    }
  }

  @override
  Future<List<MediaLibrary>> getMediaLibrarys({
    String? keyword,
    int pageIndex = 1,
    int pageCount = 100,
  }) async {
    final result = await rpc.education.findVideosPagesAsync(
      FindVideoPagesRequest(
        token: Store.user.token,
        pageIndex: pageIndex,
        pageSize: pageCount,
        keyword: keyword,
        isJustQueryMyUpload: true,
      ),
    );
    List<MediaLibrary> mediaLibraryList = [];
    result.pageData?.forEach((element) {
      mediaLibraryList.add(
        MediaLibrary(
          name: element.name!,
          fileId: element.code,
          fileType: element.fodderType,
          fileToken: element.videoToken!,
          previewFileToken: element.poster,
        ),
      );
    });
    return mediaLibraryList;
  }

  @override
  Future<bool> createVideosAsync({required List<SaveVideoRequest> videoList
      // required String name,
      // required String videoToken,
      // required String vodFileId,
      // String? poster,
      // bool isPublic = false,
      }) async {
    if (videoList.isEmpty) {
      return false;
    }
    final result = await rpc.education.createVideosAsync(
      CreateVideosRequest(
        token: Store.user.token,
        videoList: videoList,
        //   name: name,
        //   videoToken: videoToken,
        //   vodFileId: vodFileId,
        //   poster: poster,
        //   isPublic: isPublic,
      ),
    );

    return result;
  }

  @override
  Future<List<UserGroupStudentsDTO>> getApplyStudent({
    required String classCode,
  }) async {
    return await getClassStudents(
      classCode: classCode,
      learnerStatus: LearnerStatusEnum.NoApproval,
    );
  }

  @override
  Future<bool> changeVideoName(String name, String code) async {
    return await rpc.education.changeVideoNameAsync(
        ChangeVideoNameRequest(newName: name, token: token, videoCode: code));
  }

  /// 这边接口需要替换
  ///获取学生集合
  @override
  Future<PageResult<UserExtendDTO>> getStudents({
    String? keyword,
    int? pageIndex,
  }) async {
    try {
      final result = await rpc.education.getAllStudentsAsync(
        GetUserPagesRequest(
          keyword: keyword,
          pageIndex: pageIndex!,
          pageSize: 20,
          token: Store.user.token,
        ),
      );
      return result;
    } catch (e) {
      logger.e('FlyinsonoCollegeManager getStudents ex:', e);
    }
    return PageResult<UserExtendDTO>();
  }

  /// 这边接口需要替换
  @override
  Future<List<UserExtendDTO>> getTeachers({
    String? keyword,
  }) async {
    final result = await rpc.user.getUserListAsync(
      GetUserListRequest(
        token: Store.user.token,
        language: i18nBook.locale.toCodeString('-'),
        organizationCode: Store.user.rootOrganizationCode,
        // 全部和待分配的枚举
        organizationQueryType: OrganizationQueryTypeEnum.All,
      ),
    );
    return result;
  }

  @override
  Future<List<UserGroupStudentsDTO>> getClassStudents({
    required String classCode,
    required LearnerStatusEnum learnerStatus,
  }) async {
    final result = await rpc.education.findStudentListAsync(
      FindStudentListRequest(
        userGroupCode: classCode,
        token: Store.user.token,
        learnerStatus: learnerStatus,
      ),
    );
    return result;
  }

  @override
  Future<bool> setRecordFilePath(String path) async {
    onRecordFilePathUpdate.emit(this, path);
    LocalSetting.ins.liveRecordPath = path;
    var localSettingService = Get.find<LocalSettingService>();
    localSettingService.save();
    return true;
  }
}
