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

import '../../../../common/models/index.dart';
import '../../../../common/routers/index.dart';
import '../../../../common/style/index.dart';
import '../../../../common/utils/index.dart';
import '../../../../common/values/index.dart';
import '../../../../common/widgets/index.dart';
import 'index.dart';

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

  static Future<void> startNew() async {
    return await Get.toNamed(O2OARoutes.appMeetingForm);
  }
  static Future<void> startEdit(MeetingInfoModel meeting) async {
    return await Get.toNamed(O2OARoutes.appMeetingForm, arguments: meeting);
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MeetingFormController>(
      builder: (_) {
        return Scaffold(
          appBar: AppBar(title: Text("meeting_menu_apply_label".tr), 
          actions: [TextButton(onPressed: ()=> controller.saveMeeting(closePage: true), child: Text('save'.tr , style: AppTheme.whitePrimaryTextStyle))],),
          body: SafeArea(
              child: ListView(children: [
            const SizedBox(height: 8),
            formView(context),
            const SizedBox(height: 8),
            meetingMembersView(context),
            const SizedBox(height: 8),
            attachmentView(context)
          ])),
        );
      },
    );
  }

  // 会议表单1
  Widget formView(BuildContext context) {
    return O2UI.sectionOutBox(Obx(() {
      final time =
          '${controller.state.meetingInfo.value?.startTime?.substring(11, 16)} 至 ${controller.state.meetingInfo.value?.completedTime?.substring(11, 16)}';
      return Column(children: [
        // 会议标题
        TextField(
          controller: controller.subjectController,
          decoration: InputDecoration(
              hintText: "meeting_detail_title_hint".tr, //默认提示文案
              label: Text('meeting_detail_title_label'.tr) //标签
              ),
        ),
        // 日期
        O2UI.lineWidget(
            'meeting_detail_date_label'.tr,
            Text(controller.state.meetingInfo.value?.startTime
                    ?.substring(0, 10) ??
                ''),
            ontap: () => clickPickDay(context)),
        const Divider(height: 1),
        // 会议时间
        O2UI.lineWidget('meeting_detail_time_label'.tr, Text(time),
            ontap: ()=> clickPickTime(context)),
        const Divider(height: 1),
        // 会议室
        O2UI.lineWidget('meeting_detail_room_label'.tr,
            Text(controller.state.meetingInfo.value?.woRoom?.name ?? ''),
            ontap: ()=>controller.clickPickMeetingRoom()),
        const Divider(height: 1),
        // 会议类型，配置文件中获取
        Obx(()=>Visibility(
          visible: controller.state.typeList.length > 0,
          child: O2UI.lineWidget('meeting_detail_type_label'.tr,
            Text(controller.state.meetingInfo.value?.type ?? ''),
            ontap: ()=>clickPickMeetingType(context)))),
         Obx(()=>Visibility(
          visible: controller.state.typeList.length > 0,
          child: const Divider(height: 1))),
        // 会议方式
        Obx(()=>Visibility(
          visible: controller.state.showMode,
          child: O2UI.lineWidget('meeting_detail_mode_label'.tr,
            Text(controller.state.meetingInfo.value?.mode == MeetingMode.online.getKey() ? MeetingMode.online.getName() : MeetingMode.offline.getName() ),
            ontap: ()=>clickPickMeetingMode(context)))),
         Obx(()=>Visibility(
          visible: controller.state.showMode,
          child: const Divider(height: 1))),

        // 在线会议的连接
         Obx(()=>Visibility(
          visible: controller.state.showOnline && controller.state.meetingInfo.value?.mode == MeetingMode.online.getKey(),
          child: TextField(
          controller: controller.onlineLinkController,
          decoration: InputDecoration(
              hintText: "meeting_form_online_link_hint".tr, //默认提示文案
              label: Text('meeting_detail_online_link_label'.tr) //标签
              ),
        ))),
        // 在线会议的房间号
         Obx(()=>Visibility(
          visible: controller.state.showOnline && controller.state.meetingInfo.value?.mode == MeetingMode.online.getKey(),
          child: TextField(
          controller: controller.onlineRoomController,
          decoration: InputDecoration(
              hintText: "meeting_form_online_room_hint".tr, //默认提示文案
              label: Text('meeting_detail_online_room_label'.tr) //标签
              ),
        ))),
        // 主持人 
        O2UI.lineWidget('meeting_detail_host_label'.tr,
            Text(controller.state.meetingInfo.value?.hostPerson?.o2NameCut() ?? ''),
            ontap: ()=>controller.clickPickHostPerson()),
        const Divider(height: 1),
        // 承办部门
        O2UI.lineWidget('meeting_detail_host_unit_label'.tr,
            Text(controller.state.meetingInfo.value?.hostUnit?.o2NameCut() ?? ''),
            ontap: ()=>controller.clickPickHostUnit()),
        const Divider(height: 1),
        // 会议说吗
        TextField(
          controller: controller.summaryController,
          maxLines: 3,
          decoration: InputDecoration(
              hintText: "meeting_detail_describe_hint".tr, //默认提示文案
              label: Text('meeting_detail_describe_label'.tr) //标签
              ),
        ),
        const SizedBox(height: 5),
      ]);
    }), context);
  }

  // 参会人员
  Widget meetingMembersView(BuildContext context) {
    return O2UI.sectionOutBox(Obx(() {
      final members =
          controller.state.meetingInfo.value?.inviteMemberList ?? [];
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text('meeting_detail_member_label'.tr),
              const Spacer(),
              IconButton(
                  onPressed: ()=>controller.clickAddMembers(),
                  icon: Icon(Icons.add,
                      color: Theme.of(context).colorScheme.primary))
            ],
          ),
          const SizedBox(height: 5),
          Padding(
              padding: const EdgeInsets.all(10),
              child: GridView.count(
                  shrinkWrap: true,
                  crossAxisCount: 4,
                  mainAxisSpacing: 8.0, //设置上下之间的间距(Axis.horizontal设置左右之间的间距)
                  crossAxisSpacing: 8.0, //设置左右之间的间距(Axis.horizontal设置上下之间的间距)
                  childAspectRatio: 1.8, //设置宽高比
                  children: members.map((element) {
                    final name = element.o2NameCut();
                    return InkWell(onTap: () =>  controller.removeMember(element), child: Stack(
                      children: [
                        Align(
                          alignment: Alignment.center,
                          child: Text(
                          name,
                          style: const TextStyle(fontSize: 16),
                        ),
                        ),
                        const Positioned(
                            right: 0,
                            top: 0,
                            child: AssetsImageView(
                              'icon_app_del.png',
                              width: 12,
                              height: 12,
                            )),
                      ],
                    ));
                  }).toList()))
        ],
      );
    }), context);
  }

  Widget attachmentView(BuildContext context) {
    return O2UI.sectionOutBox(Obx(() {
      final attachments =
          controller.state.meetingInfo.value?.attachmentList ?? [];
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Text('meeting_detail_attachment_label'.tr),
              const Spacer(),
              IconButton(
                  onPressed: ()=>clickAddAttachment(context),
                  icon: Icon(Icons.add,
                      color: Theme.of(context).colorScheme.primary))
            ],
          ),
          const SizedBox(height: 5),
          Padding(
              padding: const EdgeInsets.all(10),
              child: GridView.count(
                  shrinkWrap: true,
                  crossAxisCount: 4,
                  mainAxisSpacing: 8.0, //设置上下之间的间距(Axis.horizontal设置左右之间的间距)
                  crossAxisSpacing: 8.0, //设置左右之间的间距(Axis.horizontal设置上下之间的间距)
                  childAspectRatio: 0.8, //设置宽高比
                  children: attachments.map((element) {
                    final name = element.name ?? '';
                    String fileIcon = FileIcon.getFileIconAssetsNameByExtension(
                        element.extension ?? '');
                    return InkWell(onTap: () => controller.removeAttachment(element), child: Stack(
                      children: [
                        Column(
                          children: [
                            AssetsImageView(fileIcon, width: 40, height: 40),
                            Expanded(
                                flex: 1,
                                child: Center(
                                    child: Text(
                                  name,
                                  style: const TextStyle(fontSize: 12),
                                )))
                          ],
                        ),
                        const Positioned(
                            right: 0,
                            top: 0,
                            child: AssetsImageView(
                              'icon_app_del.png',
                              width: 12,
                              height: 12,
                            )),
                      ],
                    ));
                  }).toList()))
        ],
      );
    }), context);
  }
  // 选择日期
  void clickPickDay(BuildContext context) async {
    final time = controller.state.meetingInfo.value?.startTime;
    final now = DateTime.now();
    DateTime initDate;
    if (time != null) {
      initDate = DateTime.parse(time);
    } else {
      initDate = now;
    }
    final result = await showDatePicker(context: context, initialDate: initDate, firstDate: now, lastDate: now.addYears(1));
    if (result != null) {
      OLogger.d('result: $result');
      final meetingInfo = controller.state.meetingInfo.value?.newInstanceCopyValue();
      if (meetingInfo != null) {
        final newDay = result.ymd();
        meetingInfo.startTime =  meetingInfo.startTime?.replaceRange(0, 10, newDay);
        meetingInfo.completedTime =  meetingInfo.completedTime?.replaceRange(0, 10, newDay);
        controller.state.meetingInfo.value = meetingInfo;
        OLogger.d('meetingInfo: ${meetingInfo.toJson()}');
      }
    }
  }
  // 选择开始时间和结束时间
  void clickPickTime(BuildContext context) async {
    final time = controller.state.meetingInfo.value?.startTime;
    final cTime = controller.state.meetingInfo.value?.completedTime;
    final now = DateTime.now();
    TimeOfDay initTime;
    TimeOfDay initCTime;
    if (time != null) {
      final date = DateTime.parse(time);
      initTime = TimeOfDay(hour: date.hour, minute: date.minute);
    } else {
      initTime = TimeOfDay(hour: now.hour, minute: now.minute);
    }
    if (cTime != null) {
      final cdate = DateTime.parse(cTime);
      initCTime = TimeOfDay(hour: cdate.hour, minute: cdate.minute);
    } else {
      initCTime = TimeOfDay(hour: now.hour, minute: now.minute);
    }
    final startTime = await showTimePicker(context: context, initialTime: initTime, helpText: 'meeting_detail_pick_start_time_hint'.tr);
    if (startTime != null) {
      final completeTime = await showTimePicker(context: context, initialTime: initCTime, helpText: 'meeting_detail_pick_complete_time_hint'.tr);
      if (completeTime != null) {
        if (completeTime.hour < startTime.hour) {
          Loading.toast('meeting_detail_time_smaller_error'.tr);
          return;
        }
        if (completeTime.hour == startTime.hour && completeTime.minute < startTime.minute) {
          Loading.toast('meeting_detail_time_smaller_error'.tr);
          return;
        }
        final startHour = startTime.hour > 9 ? '${startTime.hour}' : '0${startTime.hour}';
        final startMinute = startTime.minute > 9 ? '${startTime.minute}' : '0${startTime.minute}';
        final completeHour = completeTime.hour > 9 ? '${completeTime.hour}' : '0${completeTime.hour}';
        final completeMinute = completeTime.minute > 9 ? '${completeTime.minute}' : '0${completeTime.minute}';
        final meetingInfo = controller.state.meetingInfo.value?.newInstanceCopyValue();
        if (meetingInfo != null) {
          meetingInfo.startTime =  meetingInfo.startTime?.replaceRange(11, 16, '$startHour:$startMinute');
          meetingInfo.completedTime =  meetingInfo.completedTime?.replaceRange(11, 16, '$completeHour:$completeMinute');
          controller.state.meetingInfo.value = meetingInfo;
          OLogger.d('meetingInfo: ${meetingInfo.toJson()}');
        }
      }
    }
  }
  // 选择会议类型
  void clickPickMeetingType(BuildContext context) {
    O2UI.showBottomSheetWithCancel(context, controller.state.typeList.map((element) {
      return ListTile(
          onTap: () {
            Navigator.pop(context);
            final meetingInfo = controller.state.meetingInfo.value?.newInstanceCopyValue();
            if (meetingInfo != null) {
              meetingInfo.type =  element;
              controller.state.meetingInfo.value = meetingInfo;
              OLogger.d('meetingInfo: ${meetingInfo.toJson()}');
            }
          },
          title: Align(
            alignment: Alignment.center,
            child: Text(element,
                style: Theme.of(context).textTheme.bodyMedium),
          ),
        );
    }).toList());
  }
  // 选择会议方式
  void clickPickMeetingMode(BuildContext context) {
    final list = [MeetingMode.offline, MeetingMode.online];
    O2UI.showBottomSheetWithCancel(context, list.map((element) {
      return ListTile(
          onTap: () {
            Navigator.pop(context);
            final meetingInfo = controller.state.meetingInfo.value?.newInstanceCopyValue();
            if (meetingInfo != null) {
              meetingInfo.mode =  element.getKey();
              controller.state.meetingInfo.value = meetingInfo;
              OLogger.d('meetingInfo: ${meetingInfo.toJson()}');
            }
          },
          title: Align(
            alignment: Alignment.center,
            child: Text(element.getName(),
                style: Theme.of(context).textTheme.bodyMedium),
          ),
        );
    }).toList());
  }

  // 添加会议材料
  void clickAddAttachment(BuildContext context) {
     final id = controller.state.meetingInfo.value?.id;
    if (id == null || id.isEmpty) {
      O2UI.showConfirm(context, 'meeting_form_confirm_save_meeting_before_upload'.tr, okText: 'meeting_form_confirm_ok_text'.tr, okPressed: (() => controller.uploadMeetingAttachment()));
    } else {
      controller.uploadMeetingAttachment();
    }
  }
  
}
