import 'package:fis_common/extensions/index.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_i18n/i18n.dart';
import 'index.dart';

class PastVideoPlayerController extends GetxController {
  PastVideoPlayerController();

  final state = PastVideoPlayerState();

  void initData() async {
    Map<String, String> parameters;
    if (kIsMobile) {
      parameters = router.getParams() ?? {};
    } else {
      parameters = router.getParams(NavIds.HOME) ?? {};
    }

    if (!(parameters['code'] is String)) return;
    CourseInfoDetailDTO videoInfo = await rpc.education.findCourseByCodeAsync(
      FindCourseByCodeRequest(
        token: Store.user.token,
        languageCode: i18nBook.locale.toCodeString('-'),
        code: parameters['code'],
      ),
    );

    state.videoUrl = videoInfo.defaultVideoToken ?? '';
    state.videoTitle = videoInfo.name ?? '';
    state.videoDescription = videoInfo.courseIntro ?? '';
    state.videoCreateTimeStr =
        videoInfo.createTime!.toLocal().toString().substring(0, 11);
    state.videoStarLevel = videoInfo.sort;
    // 过滤移除非 mp4 格式的资源
    if (!state.videoUrl.endsWith('.mp4')) {
      state.videoUrl = '';
    }
    if (state.videoUrl.isNullOrEmpty) {
      state.isLoading = false;
    }
  }

  void onWebviewLoadFinished() {
    state.isLoading = false;
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
    initData();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }
}
