import 'package:get/get.dart';
import 'package:o2oa_all_platform/common/extension/index.dart';

import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/routers/index.dart';
import '../../../common/utils/index.dart';
import 'calendar_list/index.dart';
import 'create_calendar_event/index.dart';
import 'index.dart';

class CalendarController extends GetxController {
  CalendarController();

  final state = CalendarState();
  final Map<String, List<EventInfo>> _eventListMap = {};
  
  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    state.title = Get.parameters['displayName'] ?? "calendar_title".tr;
    loadEventFromNet(state.focusedDay);
    super.onReady();
  }

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

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

  Future<void> loadEventFromNet(DateTime changeDay) async {
    final lastMonthDate = changeDay.addMonths(-1);
    final nextMonthDate = changeDay.addMonths(1);
    _eventListMap.clear();
    Loading.show();
    // 上个月
    final lastList = await CalendarAssembleControlService.to.eventListWithFilter('${lastMonthDate.monthFirstDate().ymd()} 00:00:00', '${lastMonthDate.monthLastDate().ymd()} 23:59:59');
    if (lastList != null) {
      putEventInMap(lastList);
    }
    // 本月
    final eventList = await CalendarAssembleControlService.to.eventListWithFilter('${changeDay.monthFirstDate().ymd()} 00:00:00', '${changeDay.monthLastDate().ymd()} 23:59:59');
    if (eventList != null) {
      putEventInMap(eventList);
    }
    // 下个月
    final nextList = await CalendarAssembleControlService.to.eventListWithFilter('${nextMonthDate.monthFirstDate().ymd()} 00:00:00', '${nextMonthDate.monthLastDate().ymd()} 23:59:59');
    if (nextList != null) {
      putEventInMap(nextList);
    }
    Loading.dismiss();
    state.selectedDay = changeDay;
    state.focusedDay = changeDay;
    state.eventList.clear();
    state.eventList.addAll(loadEvent(changeDay));
    update();
  }

  /// 计算全天事件持续的日期
  List<DateTime> _tilAllDate(DateTime start, DateTime end) {
    List<DateTime> allDates = [];
    DateTime currentDate = start;
    while (currentDate.isBefore(end) || currentDate.isAtSameMomentAs(end)) {
      allDates.add(currentDate);
      currentDate = currentDate.add(const Duration(days: 1));
    }
    return allDates;
  }
  /// 查询的日程数据存入 map 中
  void putEventInMap(EventFilterList eventList) {
    final wholeEvent = eventList.wholeDayEvents ?? [];
      for (var event in wholeEvent) {
        final startDate = DateTime.tryParse(event.startTime ?? '');
        final endDate = DateTime.tryParse(event.endTime ?? '');
        if (startDate != null && endDate != null) {
          List<DateTime> dates = _tilAllDate(startDate, endDate);
          for (var element in dates) { 
            final eDate = element.ymd();
            if (_eventListMap.containsKey(eDate)) {
              _eventListMap[eDate]?.add(event);
            } else {
              _eventListMap[eDate] = [event];
            }
          }
        }
      }
      final oneDayEvent = eventList.inOneDayEvents ?? [];
      for (var element in oneDayEvent) {
        if (element.eventDate == null || element.eventDate?.isEmpty == true) {
          continue;
        }
        if (_eventListMap.containsKey(element.eventDate!)) {
          _eventListMap[element.eventDate!]?.addAll(element.inOneDayEvents ?? []);
        } else {
          _eventListMap[element.eventDate!] = element.inOneDayEvents??[];
        }
      }
  }


  List<EventInfo> loadEvent(DateTime day) {
    String key = day.ymd();
    return _eventListMap[key] ?? [];
  }

  void onDaySelected(DateTime selectedDay, DateTime focusedDay) {
    OLogger.d('selected :$selectedDay, focused: $focusedDay');
    state.selectedDay = selectedDay;
    state.focusedDay = focusedDay;
    state.eventList.clear();
    state.eventList.addAll(loadEvent(selectedDay));
  }
  /// 日历页面
  void enterCalendarListPage() {
    CalendarListPage.open();
  }
  /// 更新日程
  void enterEventUpdate(EventInfo info) async {
    await CreateCalendarEventPage.openUpdate(info);
    loadEventFromNet(state.focusedDay);
  }
  /// 创建日程
  void enterCreateEvent() async {
    await Get.toNamed(O2OARoutes.appCalendarEventCreate);
    loadEventFromNet(state.focusedDay);
  }

}
