import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/data/repositories/agenda_repository.dart';
import 'package:electronic_assistant/module/agenda/utils.dart';
import 'package:electronic_assistant/popup/agenda_time_popup.dart';
import 'package:electronic_assistant/utils/error_handler.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../data/api/request/agenda_request.dart';
import '../../data/bean/agenda.dart';
import '../../utils/time_utils.dart';
import 'detail/view.dart';

class AgendaController extends BaseController {
  AgendaTimeType? _timeFilterType;
  final _filterTxt = ''.obs;

  String get filterTxt => _filterTxt.value;

  final agendaDetailPopupTag = 'agendaDetailPopupTag';
  final todoIsExpanded = true.obs;
  final doneIsExpanded = true.obs;
  final refreshController = RefreshController(initialRefresh: false);

  final RxList<Agenda> agendaTodoList = <Agenda>[].obs;
  final RxList<Agenda> agendaDoneList = <Agenda>[].obs;

  final doneSize = 0.obs;
  final int limit = 10;

  AgendaTimeType? get timeFilterType => _timeFilterType;
  DateRange? searchTime;

  @override
  void onReady() {
    reset();
    refreshTodoTaskList();
    agendaDonePage(0, limit, isClearAll: true);
  }

  void reset() {
    _setTimeFilterType(AgendaTimeType.nearlyAWeek);
  }

  void onClickTimeType(AgendaTimeType type) {
    _setTimeFilterType(type);
    refreshTodoTaskList();
    agendaDonePage(0, limit, isClearAll: true);
  }

  void _setTimeFilterType(AgendaTimeType type) {
    _timeFilterType = type;
    _filterTxt.value = getAgendaFilterTxt(type);
    switch (type) {
      case AgendaTimeType.nearlyAWeek:
        searchTime = TimeUtils.getLastDates(const Duration(days: 7));
        break;
      case AgendaTimeType.nearlyTwoWeek:
        searchTime = TimeUtils.getLastDates(const Duration(days: 14));
        break;
      case AgendaTimeType.nearlyAMonth:
        searchTime = TimeUtils.getLastDates(const Duration(days: 31));
        break;
      case AgendaTimeType.customTime:
        searchTime = TimeUtils.getLastDates(const Duration());
        break;
    }
  }

  void onLoadMoreDoneData() {
    agendaDonePage(agendaDoneList.length, limit);
  }

  agendaDonePage(int offset, int limit, {bool? isClearAll}) {
    agendaRepository
        .agendaPage(
      offset, limit,
      completeStatus: TaskStatus.DONE,
      // startTime: searchTime?.startTime.millisecondsSinceEpoch,
      // endTime: searchTime?.endTime.millisecondsSinceEpoch
    )
        .then((response) {
      doneSize.value = response.count;
      if (isClearAll == true) {
        agendaDoneList.clear();
      }
      if (response.list != null) {
        agendaDoneList.addAll(response.list!);
      }
      if (agendaDoneList.length >= response.count) {
        debugPrint("refreshAgendaPage-没有更多数据了");
        refreshController.loadNoData();
      } else {
        refreshController.loadComplete();
      }
      refreshController.refreshCompleted();
    }).catchError((error) {
      refreshController.loadFailed();
      refreshController.refreshFailed();
      ErrorHandler.toastError(error);
    });
  }

  refreshTodoTaskList() {
    agendaRepository
        .agendaPage(
      0, 999,
      completeStatus: TaskStatus.TODO,
      // startTime: searchTime?.startTime.millisecondsSinceEpoch,
      // endTime: searchTime?.endTime.millisecondsSinceEpoch
    )
        .then((response) {
      agendaTodoList.clear();
      if (response.list != null) {
        agendaTodoList.addAll(response.list!);
      }
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  void onClickTodoGroup() {
    todoIsExpanded.value = !todoIsExpanded.value;
  }

  void onClickDoneGroup() {
    doneIsExpanded.value = !doneIsExpanded.value;
  }

  void agendaComplete(Agenda item, bool isComplete) {
    agendaRepository.agendaFinish(item.id, isComplete).then((data) {
      agendaRepository.requestHomeAgendaData();
      _refreshData();
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  void _refreshData() {
    refreshTodoTaskList();
    int size;
    if (agendaDoneList.isEmpty || agendaDoneList.length < limit) {
      size = limit;
    } else {
      size = agendaDoneList.length;
    }
    agendaDonePage(0, size, isClearAll: true);
  }

  void onAgendaCancel(Agenda item) {
    agendaRepository.agendaTodo(item.id, false).then((value) {
      agendaRepository.requestHomeAgendaData();
      _refreshData();
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

  void onAgendaUpdate(Agenda item) {
    AgendaDetailPage.start(item);
  }

  void clearFilterTime() {
    _timeFilterType = null;
    _filterTxt.value = '';
    searchTime = null;
    refreshTodoTaskList();
    agendaDonePage(0, limit, isClearAll: true);
  }
}
