import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:o2oa_all_platform/common/extension/string_extension.dart';

import '../../../../common/api/index.dart';
import '../../../../common/models/index.dart';
import '../../../../common/utils/index.dart';
import '../../../../common/widgets/index.dart';
import '../../../home/contact/contact_picker/index.dart';
import '../calendar_const.dart';
import 'index.dart';

class CreateCalendarController extends GetxController {
  CreateCalendarController();

  final state = CreateCalendarState();
  final titleController = TextEditingController();
  final summaryController = TextEditingController();

  List<String> manageablePersonList = [];
  List<String> publishableGroupList = [];
  List<String> publishablePersonList = [];
  List<String> publishableUnitList = [];
  List<String> viewableGroupList = [];
  List<String> viewablePersonList = [];
  List<String> viewableUnitList = [];

  CalendarInfo? _calendar;

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final map = Get.arguments;
    if (map != null &&
        map["calendar"] != null &&
        map["calendar"] is CalendarInfo) {
      _getCalendarInfo((map["calendar"] as CalendarInfo).id!);
      state.isUpdate = true;
    } else {
      state.eventColor = O2Calendar.deepColors[0];
      state.calendarType = O2Calendar.calendarTypes.keys.first;
      state.isUpdate = false;
    }
    super.onReady();
  }
  /// 先查询日历对象 然后赋值
  _getCalendarInfo(String id) async {
    Loading.show();
    final result = await CalendarAssembleControlService.to.getCalendar(id);
    if (result != null) {
      Loading.dismiss();
      _calendar = result;
      titleController.text = _calendar?.name ?? '';
      summaryController.text = _calendar?.description ?? '';
      state.calendarType = _calendar?.type ?? '';
      state.isPublic = _calendar?.isPublic ?? false;
      state.eventColor = _calendar?.color ?? O2Calendar.deepColors[0];
      if (_calendar?.type == 'UNIT') {
        state.target = _calendar?.target ?? '';
      } else {
        state.target = '';
      }
      manageablePersonList = _calendar?.manageablePersonList ?? [] ;
      viewableGroupList = _calendar?.viewableGroupList ?? [] ;
      viewablePersonList = _calendar?.viewablePersonList ?? [] ;
      viewableUnitList = _calendar?.viewableUnitList ?? [] ;
      publishableGroupList = _calendar?.publishableGroupList ?? [] ;
      publishableUnitList = _calendar?.publishableUnitList ?? [] ;
      publishablePersonList = _calendar?.publishablePersonList ?? [] ;
      state.manageablePersonName =
          manageablePersonList.map((e) => e.o2NameCut()).join(',');
      List<String> names = [];
      names.addAll(viewablePersonList.map((e) => e.o2NameCut()));
      names.addAll(viewableUnitList.map((e) => e.o2NameCut()));
      names.addAll(viewableGroupList.map((e) => e.o2NameCut()));
      state.viewableName = names.join(',');
      List<String> names2 = [];
      names2.addAll(publishablePersonList.map((e) => e.o2NameCut()));
      names2.addAll(publishableUnitList.map((e) => e.o2NameCut()));
      names2.addAll(publishableGroupList.map((e) => e.o2NameCut()));
      state.publishableName = names2.join(',');
    } else {
      Get.back();
    }
  }

  /// 检查表单输入情况
  CalendarInfo? _checkForm() {
    final title = titleController.text;
    if (title.isEmpty) {
      Loading.showError('calendar_event_form_title_hint'.tr);
      return null;
    }
    if (state.calendarType.isEmpty) {
      Loading.showError('calendar_edit_form_type_hint'.tr);
      return null;
    }
    if (state.calendarType == 'UNIT' && state.target.isEmpty) {
      Loading.showError('calendar_edit_form_target_not_empty'.tr);
      return null;
    }
    CalendarInfo info = CalendarInfo();
    info.name = title;
    info.color = state.eventColor;
    info.isPublic = state.isPublic;
    info.type = state.calendarType;
    if (state.calendarType == 'PERSON'  ) {
      info.target = O2ApiManager.instance.o2User?.distinguishedName;
    } else {
      info.target = state.target;
    }
    info.description = summaryController.text;
    info.manageablePersonList = manageablePersonList;
    info.viewableGroupList = viewableGroupList;
    info.viewablePersonList = viewablePersonList;
    info.viewableUnitList = viewableUnitList;
    info.publishableGroupList = publishableGroupList;
    info.publishablePersonList = publishablePersonList;
    info.publishableUnitList = publishableUnitList;
    return info;
  }
  /// 保存日历
  void saveCalendar() async {
    final info = _checkForm();
    if (info == null) {
      return;
    }
    final result = await CalendarAssembleControlService.to.saveCalendar(info);
    if (result != null) {
      Get.back();
    }
  }
  /// 更新日历
  void updateCalendar() async {
    final info = _checkForm();
    if (info == null) {
      return;
    }
    if (_calendar == null || _calendar?.id == null) {
      return ;
    }
    info.id = _calendar?.id;
    final result = await CalendarAssembleControlService.to.saveCalendar(info);
    if (result != null) {
      Get.back();
    }
  }
  /// 删除日历
  void deleteCalendar() {
    if (_calendar == null || _calendar?.id == null) {
      return ;
    }
    final context = Get.context;
    if (context == null) {
      return;
    }
    O2UI.showConfirm(context, 'calendar_delete_confirm'.tr, okPressed: () {
      deleteCalendarOnline();
    });
  }
  deleteCalendarOnline() async {
    final result = await CalendarAssembleControlService.to.deleteCalendar(_calendar!.id!);
    if (result != null) {
      Get.back();
    }
  }

  /// 选择颜色
  void chooseEventColor(String color) {
    state.eventColor = color;
  }

  /// 是否公开
  void changePublic(bool v) {
    state.isPublic = v;
  }

  /// 选择日历类型
  void selectCalendarType() {
    final context = Get.context;
    if (context == null) return;
    final widgets = O2Calendar.calendarTypes.entries
        .map((e) => ListTile(
              onTap: () {
                Navigator.pop(context);
                state.calendarType = e.key;
              },
              title: Align(
                alignment: Alignment.center,
                child: Text(e.value,
                    style: Theme.of(context).textTheme.bodyMedium),
              ),
            ))
        .toList();
    O2UI.showBottomSheetWithCancel(context, widgets);
  }

  /// 选择 所属组织
  void chooseTarget() async {
    var result = await ContactPickerPage.startPicker(
        [ContactPickMode.departmentPicker],
        multiple: false);
    if (result is ContactPickerResult) {
      final unit = result.departments ?? [];
      if (unit.isNotEmpty) {
        state.target = unit.first.distinguishedName ?? '';
      }
    }
  }

  /// 管理人员选择
  void chooseManageAble() async {
    var result = await ContactPickerPage.startPicker(
        [ContactPickMode.personPicker],
        multiple: true, initUserList: manageablePersonList);
    if (result is ContactPickerResult) {
      final users = result.users ?? [];
      manageablePersonList.clear();
      manageablePersonList
          .addAll(users.map((e) => e.distinguishedName ?? '').toList());
      state.manageablePersonName =
          manageablePersonList.map((e) => e.o2NameCut()).join(',');
    }
  }

  /// 可见范围
  void chooseViewAble() async {
    var result = await ContactPickerPage.startPicker([
      ContactPickMode.personPicker,
      ContactPickMode.departmentPicker,
      ContactPickMode.groupPicker
    ],
        multiple: true,
        initDeptList: viewableUnitList,
        initGroupList: viewableGroupList,
        initUserList: viewablePersonList);
    if (result is ContactPickerResult) {
      final users = result.users ?? [];
      viewablePersonList.clear();
      viewablePersonList
          .addAll(users.map((e) => e.distinguishedName ?? '').toList());
      final units = result.departments ?? [];
      viewableUnitList.clear();
      viewableUnitList
          .addAll(units.map((e) => e.distinguishedName ?? '').toList());
      final groups = result.groups ?? [];
      viewableGroupList.clear();
      viewableGroupList
          .addAll(groups.map((e) => e.distinguishedName ?? '').toList());
      
      List<String> names = [];
      names.addAll(viewablePersonList.map((e) => e.o2NameCut()));
      names.addAll(viewableUnitList.map((e) => e.o2NameCut()));
      names.addAll(viewableGroupList.map((e) => e.o2NameCut()));

      state.viewableName = names.join(',');
    }
  }

  /// 可新建范围
  void choosePublishAble() async {
    var result = await ContactPickerPage.startPicker([
      ContactPickMode.personPicker,
      ContactPickMode.departmentPicker,
      ContactPickMode.groupPicker
    ],
        multiple: true,
        initDeptList: publishableUnitList,
        initGroupList: publishableGroupList,
        initUserList: publishablePersonList);
    if (result is ContactPickerResult) {
      final users = result.users ?? [];
      publishablePersonList.clear();
      publishablePersonList
          .addAll(users.map((e) => e.distinguishedName ?? '').toList());
      final units = result.departments ?? [];
      publishableUnitList.clear();
      publishableUnitList
          .addAll(units.map((e) => e.distinguishedName ?? '').toList());
      final groups = result.groups ?? [];
      publishableGroupList.clear();
      publishableGroupList
          .addAll(groups.map((e) => e.distinguishedName ?? '').toList());
      
      List<String> names = [];
      names.addAll(publishablePersonList.map((e) => e.o2NameCut()));
      names.addAll(publishableUnitList.map((e) => e.o2NameCut()));
      names.addAll(publishableGroupList.map((e) => e.o2NameCut()));

      state.publishableName = names.join(',');
    }
  }
}
