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/utils/index.dart';
import '../../common/create_form/index.dart';
import 'index.dart';
import 'meeting_accept_list/index.dart';
import 'meeting_detail/index.dart';
import 'meeting_form/index.dart';

class MeetingController extends GetxController {
  MeetingController();

  final state = MeetingState();

  List<MeetingInfoModel> meetingList = [];
  final Map<String, List<MeetingInfoModel>> _meetingMap = {};

  bool openCreate = false; // 是否马上打开会议创建界面

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

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    state.title = Get.parameters['displayName'] ?? "app_name_meeting".tr;
    final args = Get.arguments;
    if (args != null) {
      openCreate = args['openCreate'] ?? false;
    }
    loadConfig();
    loadMeetingList(state.focusedDay);
    super.onReady();
  }

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

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

  Future<void> loadConfig() async {
    final config = await MeetingAssembleService.to.config();
    if (config != null) {
      state.meetingConfig.value = config;
    }
    if (openCreate) {
      openCreateMeeting();
    }
  }

  Future<void> loadMeetingList(DateTime changeDay) async {
    final year = changeDay.year;
    final month = changeDay.month;
    final lastMonthDate = changeDay.addMonths(-1);
    final lastYear = lastMonthDate.year;
    final lastMonth = lastMonthDate.month;
    final nextMonthDate = changeDay.addMonths(1);
    final nextYear = nextMonthDate.year;
    final nextMonth = nextMonthDate.month;

    final lastList = await MeetingAssembleService.to
        .meetingListOnMonth('$lastYear', '$lastMonth');
    final list =
        await MeetingAssembleService.to.meetingListOnMonth('$year', '$month');
    final nextList = await MeetingAssembleService.to
        .meetingListOnMonth('$nextYear', '$nextMonth');
    _meetingMap.clear();
    if (lastList != null && lastList.isNotEmpty) {
      for (final element in lastList) {
        _putInMap(element);
      }
    }
    if (list != null && list.isNotEmpty) {
      for (final element in list) {
        _putInMap(element);
      }
    }
    if (nextList != null && nextList.isNotEmpty) {
      for (final element in nextList) {
        _putInMap(element);
      }
    }
    state.selectedDay = changeDay;
    state.focusedDay = changeDay;
    state.meetingList.clear();
    state.meetingList.addAll(loadEvent(changeDay));
    update();
    OLogger.d('数据加载完成，day: $changeDay');
  }

  void _putInMap(MeetingInfoModel m) {
    final startTime = m.startTime;
    if (startTime != null) {
      String day = startTime.substring(0, 10); // 如：2022-11-07
      if (_meetingMap.containsKey(day)) {
        _meetingMap[day]!.add(m);
      } else {
        _meetingMap[day] = [m];
      }
    }
  }

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

  void onDaySelected(DateTime selectedDay, DateTime focusedDay) {
    OLogger.d('selected :$selectedDay, focused: $focusedDay');
    state.selectedDay = selectedDay;
    state.focusedDay = focusedDay;
    state.meetingList.clear();
    state.meetingList.addAll(loadEvent(selectedDay));
  }

  /// 会议邀请列表
  openAcceptListView() async {
    await MeetingAcceptListPage.open();
    loadMeetingList(state.focusedDay);
  }

  /// 创建会议
  void openCreateMeeting() {
    if (state.meetingConfig.value != null && state.meetingConfig.value?.process != null && state.meetingConfig.value?.process?.id != null) {
      _startMeetingProcess(state.meetingConfig.value!.process!.id!);
      return;
    }
    _startMeetingNormal();
  }
  /// 普通创建会议
  _startMeetingNormal() async {
    await MeetingFormPage.startNew();
    loadMeetingList(state.focusedDay);
  }
  // 启动流程创建会议
  _startMeetingProcess(String processId) async {
    // 考勤配置的流程
    final process = await ProcessSurfaceService.to.getProcess(processId);
    if (process == null) {
      Loading.toast('args_error'.tr);
      return;
    }
    CreateFormPage.startProcess(true, process: process);
  }

  void openMeetingView(MeetingInfoModel info) {
    OLogger.d('查看会议');
    if (info.id == null) {
      OLogger.e('会议id 为空');
      return;
    }
    MeetingDetailPage.openMeeting(info.id!);
  }

  void openMeetingEdit(MeetingInfoModel info) async {
    OLogger.d('修改会议');
    await MeetingFormPage.startEdit(info);
    loadMeetingList(state.focusedDay);
  }

  void deleteMeeting(MeetingInfoModel info) async {
    OLogger.d('删除会议');
    final id = await MeetingAssembleService.to.deleteMeeting(info.id!);
    if (id != null) {
      loadMeetingList(state.focusedDay);
    }
  }

  void acceptInviteMeeting(MeetingInfoModel info) async {
    OLogger.d('接受会议邀请');
    final id = await MeetingAssembleService.to.acceptMeetingInvite(info.id!);
    if (id != null) {
      loadMeetingList(state.focusedDay);
    }
  }

  void rejectInviteMeeting(MeetingInfoModel info) async {
    OLogger.d('拒绝会议邀请');
    final id = await MeetingAssembleService.to.rejectMeetingInvite(info.id!);
    if (id != null) {
      loadMeetingList(state.focusedDay);
    }
  }
}
