import 'dart:io';

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

import '../../../home/contact/contact_picker/index.dart';
import '../meeting_room_picker/index.dart';
import 'index.dart';

class MeetingFormController extends GetxController {
  MeetingFormController();

  final state = MeetingFormState();
  var isEdit = false; // 修改还是新建

  // 会议标题
  final TextEditingController subjectController = TextEditingController();
  // 在线会议打开的连接
  final TextEditingController  onlineLinkController = TextEditingController();
  // 在线会议房间号
  final TextEditingController onlineRoomController = TextEditingController();
  // 会议描述
  final TextEditingController summaryController = TextEditingController();

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

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final meetingInfo = Get.arguments;
    if (meetingInfo != null && meetingInfo is MeetingInfoModel) {
      isEdit = true;
      state.meetingInfo.value = meetingInfo;
    }
    initData();
    super.onReady();
  }

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

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

  void initData() {
    String? config = SharedPreferenceService.to
        .getString(SharedPreferenceService.meetingConfigKey);
    if (config.isNotEmpty) {
      MeetingConfigModel cModel =
          MeetingConfigModel.fromJson(O2Utils.parseStringToJson(config));
      state.typeList.clear();
      state.typeList.addAll(cModel.typeList ?? []);
      state.showMode = cModel.enableOnline == true;
      state.showOnline = cModel.enableOnline == true && cModel.onlineProduct != '好视通'; // 这里目前是写死的名字，只有这个接入了，好视通不需要输入链接和会议号，其他需要写入。
    }
    subjectController.text = state.meetingInfo.value?.subject ?? '';
    onlineLinkController.text = state.meetingInfo.value?.roomLink ?? '';
    onlineRoomController.text = state.meetingInfo.value?.roomId ?? '';
    summaryController.text = state.meetingInfo.value?.summary ?? '';
    if (!isEdit) {
      // 新建
      final now = DateTime.now();
      var startDate = now.addHours(1);
      final completeDate = now.addHours(2);
      state.meetingInfo.value = MeetingInfoModel(
          startTime: startDate.zeroedMinutes().ymdhms(),
          completedTime: completeDate.zeroedMinutes().ymdhms());
    }
  }

  ///
  /// 保存会议
  /// 
  Future<void> saveMeeting({bool closePage = false}) async {
    final meetingInfo = state.meetingInfo.value?.newInstanceCopyValue();
    if (meetingInfo != null) {
      final subject = subjectController.text;
      if (subject.isEmpty) {
        Loading.toast('meeting_form_subject_not_empty'.tr);
        return;
      }
      meetingInfo.subject = subject;
      meetingInfo.summary = summaryController.text;
      final startTime = meetingInfo.startTime;
      final completedTime = meetingInfo.completedTime;
      if (startTime == null ||
          startTime.isEmpty ||
          completedTime == null ||
          completedTime.isEmpty) {
        Loading.toast('meeting_form_time_not_empty'.tr);
        return;
      }
      final room = meetingInfo.room;
      if (room == null || room.isEmpty) {
        Loading.toast('meeting_form_room_not_empty'.tr);
        return;
      }
      final inviteMemberList = meetingInfo.inviteMemberList;
      if (inviteMemberList == null || inviteMemberList.isEmpty) {
        Loading.toast('meeting_form_member_not_empty'.tr);
        return;
      }
      if (state.showOnline && meetingInfo.mode == MeetingMode.online.getKey()) {
        final link = onlineLinkController.text;
        if (link.isEmpty) {
          Loading.toast('meeting_form_online_link_hint'.tr);
          return;
        }

        final roomId = onlineRoomController.text;
        if (roomId.isEmpty) {
          Loading.toast('meeting_form_online_room_hint'.tr);
          return;
        }
        meetingInfo.roomLink = link;
        meetingInfo.roomId = roomId;
      }

      if (meetingInfo.id == null) {
        // 新增
        // 当前申请人
        meetingInfo.applicant = O2ApiManager.instance.o2User?.distinguishedName;
        final id = await MeetingAssembleService.to.saveMeeting(meetingInfo);
        if (id != null) {
          meetingInfo.id = id.id;
          state.meetingInfo.value = meetingInfo;
          if (closePage) {
            Get.back();
          }
        }
      } else {
        // 更新
        final id = await MeetingAssembleService.to
            .updateMeeting(meetingInfo.id!, meetingInfo);
        if (id != null) {
          meetingInfo.id = id.id;
          state.meetingInfo.value = meetingInfo;
          if (closePage) {
            Get.back();
          }
        }
      }
    }
  }

  // 添加主持人
  void clickPickHostPerson() async {
    var result = await ContactPickerPage.startPicker([ContactPickMode.personPicker]);
    if (result is ContactPickerResult) {
      if (result.users != null && result.users!.isNotEmpty) {
         String hostPerson = result.users![0].distinguishedName!;
         final meetingInfo = state.meetingInfo.value?.newInstanceCopyValue();
          if (meetingInfo != null) {
            meetingInfo.hostPerson = hostPerson;
            state.meetingInfo.value = meetingInfo;
            OLogger.d('meetingInfo: ${meetingInfo.toJson()}');
          }
      }
    }
  }
  // 添加会议室
  void clickPickMeetingRoom() async {
    final room = await MeetingRoomPickerPage.pickMeetingRoom(state.meetingInfo.value?.startTime, state.meetingInfo.value?.completedTime);
    if (room != null && room is MeetingRoom) {
      final meetingInfo = state.meetingInfo.value?.newInstanceCopyValue();
      meetingInfo?.woRoom = room;
      meetingInfo?.room = room.id;
      state.meetingInfo.value = meetingInfo;
    }
  }
  // 添加承办部门
  void clickPickHostUnit() async {
    var result = await ContactPickerPage.startPicker([ContactPickMode.departmentPicker]);
    if (result is ContactPickerResult) {
      if (result.departments != null && result.departments!.isNotEmpty) {
         String hostUnit = result.departments![0].distinguishedName!;
         final meetingInfo = state.meetingInfo.value?.newInstanceCopyValue();
          if (meetingInfo != null) {
            meetingInfo.hostUnit = hostUnit;
            state.meetingInfo.value = meetingInfo;
            OLogger.d('meetingInfo: ${meetingInfo.toJson()}');
          }
      }
    }
  }
  // 添加参会人员、组织
  void clickAddMembers() async {
    final inviteMemberList = state.meetingInfo.value?.inviteMemberList ?? [];
    final orgList = inviteMemberList.where((element) => element.endsWith('@U')).toList();
    final personList = inviteMemberList.where((element) => element.endsWith('@P')).toList();
    var result = await ContactPickerPage.startPicker([ContactPickMode.personPicker, ContactPickMode.departmentPicker], multiple: true, initUserList: personList, initDeptList: orgList);
    if (result is ContactPickerResult) {
      List<String> persons = [];
      List<String> deptList = [];
      if (result.users != null && result.users!.isNotEmpty) {
         persons = result.users!.map((e) => e.distinguishedName!).toList();
      }
      if (result.departments != null && result.departments!.isNotEmpty) {
         deptList = result.departments!.map((e) => e.distinguishedName!).toList();
      }
      final meetingInfo = state.meetingInfo.value?.newInstanceCopyValue();
      if (meetingInfo != null) {
        List<String> inviteMembers = [];
        inviteMembers.addAll(persons);
        inviteMembers.addAll(deptList);
        meetingInfo.inviteMemberList = inviteMembers;
        state.meetingInfo.value = meetingInfo;
        OLogger.d('meetingInfo: ${meetingInfo.toJson()}');
      }
    }
  }
  

  // 删除参会人员、组织
  void removeMember(String person) {
    final meetingInfo = state.meetingInfo.value?.newInstanceCopyValue();
    if (meetingInfo != null) {
      var inviteMemberList = meetingInfo.inviteMemberList ?? [];
      inviteMemberList.remove(person);
      meetingInfo.inviteMemberList = inviteMemberList;
      state.meetingInfo.value = meetingInfo;
      OLogger.d('meetingInfo: ${meetingInfo.toJson()}');
    }
  }

  ///
  /// 上传附件
  /// 
  Future<void> uploadMeetingAttachment() async {
    final id = state.meetingInfo.value?.id;
    if (id == null || id.isEmpty) {
      // 先保存会议数据 获取会议id
      await saveMeeting();
    }
    final meetingId = state.meetingInfo.value?.id;
    if (meetingId == null || meetingId.isEmpty) {
      OLogger.e('无法上传会议材料，会议ID为空！！！');
      return;
    }
    O2Utils.pickerFileOrImage((paths) {
      _uploadMeetingAttaBegin(paths, meetingId);
    });
  }
  Future<void> _uploadMeetingAttaBegin(List<String?> paths, String meetingId) async {
    if (paths.isEmpty) {
      return;
    }
    String path = paths[0] ?? '';
    if (path.isEmpty) {
      return;
    }
    OLogger.d('开始上传文件： $path');
    Loading.show();
    final aId = await MeetingAssembleService.to
        .uploadMeetingAttachment(meetingId, File(path));
    if (aId != null) {
      final meetingAttachment =
          await MeetingAssembleService.to.getMeetingAttachment(aId.id!);
      if (meetingAttachment != null) {
        final meetingInfo = state.meetingInfo.value?.newInstanceCopyValue();
        if (meetingInfo != null) {
          final attaList = meetingInfo.attachmentList ?? [];
          attaList.add(meetingAttachment);
          meetingInfo.attachmentList = attaList;
          state.meetingInfo.value = meetingInfo;
          OLogger.d('meetingInfo: ${meetingInfo.toJson()}');
        }
        Loading.dismiss();
      }
    }
  }

  ///
  /// 删除附件
  /// 
  void removeAttachment(MeetingAttachmentModel atta) async {
    final aId = await MeetingAssembleService.to.deleteMeetingAttachment(atta.id!);
    if (aId != null) {
      final meetingInfo = state.meetingInfo.value?.newInstanceCopyValue();
      if (meetingInfo != null) {
        final attaList = meetingInfo.attachmentList ?? [];
        attaList.remove(atta);
        meetingInfo.attachmentList = attaList;
        state.meetingInfo.value = meetingInfo;
      }
    }
  }
}
