import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/router/mobile/names.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/common_util.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'index.dart';

class PastVideosController extends GetxController {
  PastVideosController();

  final state = PastVideosState();

  /// 搜索框控制器
  final TextEditingController searchBarTextController = TextEditingController();

  /// 输入框焦点
  final FocusNode textFieldFocusNode = FocusNode();

  /// 滑动控制器
  final ScrollController listViewScrollController = ScrollController();

  /// 当前页码
  int _currentPage = 1;

  /// 每页条数
  int _pageSize = kIsMobile ? 10 : 12;

  /// 总条数
  int _totalCount = 0;
  int get totalCount => _totalCount;

  /// 搜索关键词
  String get _searchKeyword => searchBarTextController.text;

  void onClickSearch() async {
    HapticFeedback.mediumImpact();
    if (textFieldFocusNode.hasPrimaryFocus) {
      FocusScope.of(Get.context!).requestFocus(FocusNode());
    }
    // 滚动回顶部
    listViewScrollController.animateTo(
      0,
      duration: Duration(milliseconds: 300),
      curve: Curves.ease,
    );
    try {
      _updateVideoList();
    } catch (e) {
      logger.e("handleSearch exception:", e);
    }
  }

  // 点击所有视频
  void onClickAllVideo() async {
    HapticFeedback.mediumImpact();
    if (state.selectedTopLevelLabelId.isEmpty) return;
    state.selectedTopLevelLabelId = "";
    state.selectedSecondLevelLabelId = "";
    state.isExpandSecondLevelLabel = false;
    state.secondLevelLabelList = [];
    _updateVideoList();
  }

  // 点击一级视频标签
  void onClickTopLabel(CourseLabelDTO label) async {
    HapticFeedback.mediumImpact();
    state.selectedTopLevelLabelId = label.code ?? "";
    _updateVideoList();
    // 判断是否需要展开二级标签
    if (label.childLabels == null || label.childLabels!.isEmpty) return;
    List<CourseLabelDTO> result =
        await rpc.education.getCourseLabelsAsync(QueryCourseLabelListRequest(
      token: Store.user.token,
      parentCode: label.code,
      languageCode: i18nBook.locale.toCodeString('-'),
      type: LabelTypeEnum.CourseLabel,
    ));
    state.secondLevelLabelList = result;
    state.isExpandSecondLevelLabel = true;
  }

  // 点击二级视频标签
  void onClickSecondLevelLabel(CourseLabelDTO label) async {
    HapticFeedback.mediumImpact();
    if (state.selectedSecondLevelLabelId == label.code) {
      state.selectedSecondLevelLabelId = "";
    } else {
      state.selectedSecondLevelLabelId = label.code ?? "";
    }
    _updateVideoList();
  }

  // 收起二级视频标签
  void onClickCollapseSecondLevelLabel() async {
    HapticFeedback.mediumImpact();
    state.isExpandSecondLevelLabel = false;
    state.secondLevelLabelList = [];
    if (state.selectedSecondLevelLabelId.isNotEmpty) {
      state.selectedSecondLevelLabelId = "";
      _updateVideoList();
    }
  }

  /// 点击视频卡片
  void onClickVideoCard(int index) {
    HapticFeedback.mediumImpact();
    print("handleConsultationDetail $index");

    /// 查看视频
    router.to(
      MobileRouteNames.College.PastVideoPlayer,
      parameters: {'code': state.videosList[index].code ?? ""},
      id: kIsMobile ? null : NavIds.HOME,
    );
  }

  /// 下拉刷新
  Future<void> refreshList() async {
    HapticFeedback.mediumImpact();
    try {
      _updateVideoList();
    } catch (e) {
      logger.e("refreshList exception:", e);
    }
  }

  /// 监听滑动事件
  void addScrollListener() {
    listViewScrollController.addListener(() async {
      // 判断当前焦点是否在搜索框，如果是则取消焦点
      if (textFieldFocusNode.hasPrimaryFocus) {
        FocusScope.of(Get.context!).requestFocus(FocusNode());
      }
      // 如果滑动到底部
      try {
        if (listViewScrollController.position.atEdge) {
          if (listViewScrollController.position.pixels != 0) {
            if (state.videosList.length < _totalCount) {
              HapticFeedback.mediumImpact();
              CommonUtil.debounce(() {
                _currentPage = _currentPage + 1;
                _fetchData();
              });
            }
          }
        }
      } catch (e) {
        logger.e("listViewScrollController exception:", e);
      }
    });
  }

  /// 获取视频列表
  Future<void> _fetchData() async {
    try {
      state.videosList.addAll(await _getVideosList());
    } catch (e) {
      logger.e("getPatients exception:", e);
    }
  }

  /// 查询视频列表
  Future<List<CourseInfoDetailDTO>> _getVideosList() async {
    int currentPage = _currentPage;
    int pageSize = _pageSize;
    String keyword = _searchKeyword;
    state.isLoading = true;
    print(
        "查询视频列表 currentPage:$currentPage pageSize:$pageSize keyword:$keyword");
    PageResult<CourseInfoDetailDTO> result =
        await rpc.education.findCoursePagesAsync(FindCoursePagesRequest(
      token: Store.user.token,
      courseLabels: state.selectedSecondLevelLabelId.isNotEmpty
          ? [state.selectedSecondLevelLabelId]
          : state.selectedTopLevelLabelId.isNotEmpty
              ? [state.selectedTopLevelLabelId]
              : [],
      languageCode: i18nBook.locale.toCodeString('-'),
      pageIndex: currentPage,
      pageSize: pageSize,
      keyword: keyword,
      queryCourseType: QueryCourseTypeEnum.VideoCourse,
      // courseApprovalStatus: QueryCourseApprovalStatusEnum.Approved,
      // justPastVideo: true,
    ));
    _totalCount = result.totalCount;
    if (result.pageData != null) {
      state.isLoading = false;
      return result.pageData!;
    } else {
      state.isLoading = false;
      return [];
    }
  }

  /// 回到顶部并用当前状态刷新列表
  void _updateVideoList() async {
    _currentPage = 1;
    _totalCount = 0;
    state.videosList = [];
    state.videosList = await _getVideosList();
  }

  /// 初始化标签
  void _initLabels() async {
    List<CourseLabelDTO> result = await rpc.education.getCourseLabelsAsync(
      QueryCourseLabelListRequest(
        token: Store.user.token,
        languageCode: i18nBook.locale.toCodeString('-'),
        type: LabelTypeEnum.CourseLabel,
      ),
    );
    state.topLevelLabelList = result;
  }

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() async {
    super.onInit();
    state.videosList = await _getVideosList();
    _initLabels();
  }

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

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

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