import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:grouped_list/grouped_list.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/widgets/index.dart';
import 'index.dart';

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

  static Future<dynamic> pickMeetingRoom(
      String? startTime, String? endTime) async {
    return Get.toNamed(O2OARoutes.appMeetingRoomPicker, arguments: {
      'startTime': startTime,
      'endTime': endTime,
    });
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<MeetingRoomPickerController>(
      builder: (_) {
        return Scaffold(
          appBar: AppBar(title: Text("meeting_detail_room_label".tr)),
          body: SafeArea(
              child: Column(
            children: [
              timeChooseView(context),
              Expanded(
                flex: 1,
                child: roomListView(),
              )
            ],
          )),
        );
      },
    );
  }

  Widget roomListView() {
    return Obx(() {
      var list = controller.state.roomList.toList();
      return GroupedListView<MeetingRoom, String>(
        elements: list,
        groupBy: (element) => element.buildName ?? 'other',
        groupSeparatorBuilder: ((value) => Padding(
            padding: const EdgeInsets.only(left: 8, top: 10, bottom: 10),
            child: Text(value))),
        itemBuilder: (context, element) {
          final deviceList = element.device?.split('#') ?? [];
          var statusColor = AppColor.meetingRoomIdleColor;
          var statusText = 'meeting_room_status_idle'.tr;
          if (element.available == true) {
            if (element.idle != true) {
              statusColor = AppColor.meetingRoomBusyColor;
              statusText = 'meeting_room_status_busy'.tr;
            }
          } else {
            statusColor = AppColor.meetingRoomDisableColor;
            statusText = 'meeting_room_status_disable'.tr;
          }
          return Container(
              color: Theme.of(context).colorScheme.background,
              child: InkWell(
                  onTap: () => controller.chooseRoom(element),
                  child: Padding(
                      padding: const EdgeInsets.only(
                          left: 16, right: 16, top: 10, bottom: 10),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            mainAxisSize: MainAxisSize.max,
                            crossAxisAlignment: CrossAxisAlignment.center,
                            children: [
                              Text(element.name ?? '',
                                  style: const TextStyle(fontSize: 18)),
                              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 SizedBox(height: 8),
                          Row(children: [
                            Text('meeting_room_floor_label'
                                .trArgs(['${element.floor ?? 1}'])),
                            const SizedBox(width: 5),
                            Text('meeting_room_room_number_label'
                                .trArgs(['${element.roomNumber}'])),
                            const SizedBox(width: 5),
                            Text('meeting_room_capacity_label'
                                .trArgs(['${element.capacity ?? 0}'])),
                          ]),
                          const SizedBox(height: 8),
                          Text('meeting_room_device_label'.tr),
                          Row(
                            children: deviceList
                                .map((e) => Padding(
                                    padding: const EdgeInsets.all(8),
                                    child: AssetsImageView(
                                        toMeetingRoomDevice(e).getAssetName(),
                                        width: 16,
                                        height: 16)))
                                .toList(),
                          ),
                          ...applicantView(element),
                        ],
                      ))));
        },
      );
    });
  }

  List<Widget> applicantView(MeetingRoom room) {
    if (room.available == true &&
        room.idle != true &&
        (room.meetingList?.length ?? 0) > 0) {
      final meeting = room.meetingList![0];
      return [
        const SizedBox(height: 8),
        Text('meeting_detail_applicant'.trArgs([meeting.applicant?.o2NameCut() ?? ''])),
      ];
    } else {
      return [];
    }
  }

  Widget timeChooseView(BuildContext context) {
    return Container(
      color: Theme.of(context).colorScheme.background,
      height: 48,
      padding: const EdgeInsets.only(left: 10, right: 10),
      child: Obx(() {
        String time = '';
        if (controller.state.startTime.isNotEmpty &&
            controller.state.endTime.isNotEmpty) {
          time =
              '${controller.state.startTime.substring(11, 16)} 至 ${controller.state.endTime.substring(11, 16)}';
        }
        return Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          mainAxisSize: MainAxisSize.max,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            TextButton(
              child: Text(
                controller.state.startTime.isEmpty
                    ? ''
                    : controller.state.startTime.substring(0, 10),
                style: const TextStyle(decoration: TextDecoration.underline),
              ),
              onPressed: () => clickPickDay(context),
            ),
            TextButton(
              child: Text(time,
                  style: const TextStyle(decoration: TextDecoration.underline)),
              onPressed: () => clickPickTime(context),
            )
          ],
        );
      }),
    );
  }

  void clickPickDay(BuildContext context) async {
    final time = controller.state.startTime;
    final now = DateTime.now();
    DateTime initDate;
    if (time.isNotEmpty) {
      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 newDay = result.ymd();
      controller.state.startTime =
          controller.state.startTime.replaceRange(0, 10, newDay);
      controller.state.endTime =
          controller.state.endTime.replaceRange(0, 10, newDay);
      controller.loadRoomList();
    }
  }

  // 选择开始时间喝结束时间
  void clickPickTime(BuildContext context) async {
    final time = controller.state.startTime;
    final cTime = controller.state.endTime;
    final now = DateTime.now();
    TimeOfDay initTime;
    TimeOfDay initCTime;
    if (time.isNotEmpty) {
      final date = DateTime.parse(time);
      initTime = TimeOfDay(hour: date.hour, minute: date.minute);
    } else {
      initTime = TimeOfDay(hour: now.hour, minute: now.minute);
    }
    if (cTime.isNotEmpty) {
      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}';
        controller.state.startTime = controller.state.startTime
            .replaceRange(11, 16, '$startHour:$startMinute');
        controller.state.endTime = controller.state.endTime
            .replaceRange(11, 16, '$completeHour:$completeMinute');
        controller.loadRoomList();
      }
    }
  }
}
