import 'package:get/get.dart';

import '../../../../common/api/index.dart';
import '../../../../common/models/index.dart';
import '../create_calendar/index.dart';
import 'index.dart';

class CalendarListController extends GetxController {
  CalendarListController();

  final state = CalendarListState();
  
  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final map = Get.arguments;
    if (map != null) {
      state.isSelectMode = map["isSelectMode"] ?? false;
    }
    if (state.isSelectMode) {
      state.title = "calendar_choose_title".tr;
    } else {
      state.title = "calendar_action_calendar".tr;
    }
    loadCalendarList();
    super.onReady();
  }
 
  loadCalendarList() async {
    final myCalendar = await CalendarAssembleControlService.to.listMyCalendar();
    if (myCalendar != null) {
      state.calendarList.clear();
      final list1 = myCalendar.myCalendars ?? [];
      putCalendars('calendar_type_my'.tr, list1);
      final list2 = myCalendar.unitCalendars ?? [];
      putCalendars('calendar_type_unit'.tr, list2);
      final list3 = myCalendar.followCalendars ?? [];
      putCalendars('calendar_type_follow'.tr, list3);
    }
  }

  void putCalendars(String tag, List<CalendarInfo> list) {
    for (var element in list) {
      element.groupedTag = tag;
      state.calendarList.add(element);
    }
  }
  /// 点击日历 选择器模式 就返回日历对象 否则进入更新日历的界面
  void clickCalendar(CalendarInfo calendarInfo) {
    if (state.isSelectMode) {
      Get.back(result: calendarInfo);
    } else {
      if (calendarInfo.manageable == true) {
        _updateCalendar(calendarInfo);
      }
    }
  }

  void _updateCalendar(CalendarInfo info) async {
    await CreateCalendarPage.open(calendar: info);
    loadCalendarList();
  }
  
  void clickCreateCalendar() async {
    await CreateCalendarPage.open();
    loadCalendarList();
  }
}
