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

import 'index.dart';

class MeetingPage extends GetView<MeetingController> {
  const MeetingPage({Key? key}) : super(key: key);

  /// 打开会议管理， [openCreate]参数是启动会议管理后马上打开创建会议的界面
  static Future<void> startMeetingApp({bool openCreate = false}) async {
    await Get.toNamed(O2OARoutes.appMeeting, arguments: {"openCreate": openCreate});
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MeetingController>(
      builder: (_) {
        return Obx(() {
          final config = controller.state.meetingConfig.value;
          final isCreate =
              (config != null && config.mobileCreateEnable == true);
          return Scaffold(
            appBar: AppBar(title: Obx(()=>Text(controller.state.title)), actions: [
              TextButton(
                onPressed: () => controller.openAcceptListView(),
                child: Text('meeting_accept_list'.tr,
                    style: AppTheme.whitePrimaryTextStyle)),
            ],),
            body: SafeArea(
              child: Column(
                children: [
                  calendarView(context),
                  Expanded(
                    flex: 1,
                    child: meetingListView(context),
                  )
                ],
              ),
            ),
            floatingActionButton: isCreate
                ? FloatingActionButton(
                    onPressed: controller.openCreateMeeting,
                    tooltip: 'meeting_menu_apply_label'.tr,
                    backgroundColor: Theme.of(context).primaryColor,
                    child: const Icon(Icons.add, color: Colors.white))
                : null,
          );
        });
      },
    );
  }

  ///
  /// 日历控件
  ///
  Widget calendarView(BuildContext context) {
    final now = DateTime.now();
    final first = DateTime(now.year - 1, now.month, now.day);
    final end = DateTime(now.year + 1, now.month, now.day);
    var language = 'zh_CN';
    if (Get.locale != null) {
      language = '${Get.locale?.languageCode}_${Get.locale?.countryCode}';
    }
    OLogger.d('语言：$language');
    return Obx(() => TableCalendar<MeetingInfoModel>(
          calendarStyle: CalendarStyle(
              markersMaxCount: 1,
              markerDecoration: BoxDecoration(
                color: Theme.of(context).colorScheme.primary,
                shape: BoxShape.circle,
              )),
          headerStyle: const HeaderStyle(
            headerPadding: EdgeInsets.symmetric(horizontal: 8, vertical: 8),
            leftChevronVisible: false,
            rightChevronVisible: false,
          ),
          focusedDay: controller.state.focusedDay,
          firstDay: first,
          lastDay: end,
          locale: language,
          calendarFormat: controller.state.format,
          onFormatChanged: (format) => controller.state.format = format,
          availableCalendarFormats: {
            CalendarFormat.week: 'meeting_week_view'.tr,
            CalendarFormat.month: 'meeting_month_view'.tr
          },
          eventLoader: (day) => controller.loadEvent(day),
          onDaySelected: ((selectedDay, focusedDay) =>
              controller.onDaySelected(selectedDay, focusedDay)),
          selectedDayPredicate: (day) {
            return isSameDay(controller.state.selectedDay, day);
          },
          onPageChanged: ((focusedDay) {
            OLogger.d('翻页： ${focusedDay.toLocal()}');
            controller.loadMeetingList(focusedDay);
          }),
        ));
  }

  ///
  /// 会议列表
  ///
  Widget meetingListView(BuildContext context) {
    return Obx(() => ListView.builder(
        itemCount: controller.state.meetingList.length,
        itemBuilder: ((context, index) {
          final item = controller.state.meetingList[index];
          final time =
              '${item.startTime?.substring(11, 16)} - ${item.completedTime?.substring(11, 16)}';
          final members =
              item.inviteMemberList?.map((e) => e.o2NameCut()).join(',') ??
                  '';
          final status = item.status;
          var statusText = 'meeting_status_completed'.tr;
          var statusColor = AppColor.meetingCompletedColor;
          if (status == 'wait') {
            statusText = 'meeting_status_wait'.tr;
            statusColor = AppColor.meetingWaitColor;
            if (item.myWaitAccept == true) {
              statusText = 'meeting_status_wait_accept'.tr;
              statusColor = AppColor.meetingAcceptColor;
            }
          } else if (status == 'processing') {
            statusText = 'meeting_status_processing'.tr;
            statusColor = AppColor.meetingProcessingColor;
          }
          return InkWell(
              onTap: () => tapMeeting(item, context),
              child: Padding(
                  padding: const EdgeInsets.only(
                      left: 16, right: 16, top: 10, bottom: 10),
                  child: Row(
                    children: [
                      Expanded(
                          flex: 2,
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text(time),
                              const SizedBox(height: 10),
                              Text(item.subject ?? ''),
                              const SizedBox(height: 10),
                              O2UI.oneLineText(
                                  'meeting_member_label'.trArgs([members])),
                            ],
                          )),
                      Expanded(
                          flex: 1,
                          child: SizedBox(
                              height: 72,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.end,
                                mainAxisSize: MainAxisSize.max,
                                children: [
                                  Container(
                                    height: 24,
                                    width: 64,
                                    decoration: BoxDecoration(
                                        borderRadius: const BorderRadius.all(
                                            Radius.circular(12)),
                                        color: statusColor),
                                    child: Center(
                                        child: Text(
                                      statusText,
                                      style: const TextStyle(
                                          color: Colors.white, fontSize: 12),
                                    )),
                                  ),
                                  const Spacer(),
                                  O2UI.oneLineText(item.woRoom?.name ?? ''),
                                ],
                              )))
                    ],
                  )));
        })));
  }

  void tapMeeting(MeetingInfoModel info, BuildContext context) {
    final status = info.status;
    List<Widget> menus = [];
    if (status == 'wait') {
      if (info.myApply == true) {
        // 我申请的 添加 修改、删除
        menus.add(ListTile(
          onTap: () {
            Navigator.of(context).pop();
            controller.openMeetingEdit(info);
          },
          leading: const Icon(Icons.edit),
          title: Text('meeting_menu_edit_label'.tr,
              style: Theme.of(context).textTheme.bodyMedium),
        ));
        menus.add(ListTile(
          onTap: () {
            Navigator.of(context).pop();
            controller.deleteMeeting(info);
          },
          leading: const Icon(Icons.delete),
          title: Text('meeting_menu_delete_label'.tr,
              style: Theme.of(context).textTheme.bodyMedium),
        ));
      }
      if (info.myWaitAccept == true) {
        // 添加 接受邀请、拒绝邀请
        menus.add(ListTile(
          onTap: () {
            Navigator.of(context).pop();
            controller.acceptInviteMeeting(info);
          },
          leading: const Icon(Icons.check),
          title: Text('meeting_menu_invited_accept_label'.tr,
              style: Theme.of(context).textTheme.bodyMedium),
        ));
        menus.add(ListTile(
          onTap: () {
            Navigator.of(context).pop();
            controller.rejectInviteMeeting(info);
          },
          leading: const Icon(Icons.close),
          title: Text('meeting_menu_invited_reject_label'.tr,
              style: Theme.of(context).textTheme.bodyMedium),
        ));
      }
    }
    if (menus.isNotEmpty) {
      menus.add(ListTile(
        onTap: () {
          Navigator.of(context).pop();
          controller.openMeetingView(info);
        },
        leading: const Icon(Icons.remove_red_eye),
        title: Text('meeting_menu_view_label'.tr,
            style: Theme.of(context).textTheme.bodyMedium),
      ));
      O2UI.showBottomSheetWithCancel(context, menus);
    } else {
      controller.openMeetingView(info);
    }
  }
}
