import 'package:fis_i18n/i18n.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/utils/sizer/sizer.dart';
import 'package:flyinsono/pages/schedule/calendar/controller.dart';
import 'package:flyinsono/pages/schedule/calendar/models.dart';
import 'package:flyinsono/pages/schedule/calendar/calendar_page/month_calendar/month_calendar_item.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class MonthCalendar extends FStatefulWidget {
  const MonthCalendar({super.key});

  @override
  FState<MonthCalendar> createState() => _MonthCalendarState();
}

class _MonthCalendarState extends FState<MonthCalendar> {
  List<MonthViewDayModel> monthViewDaysList = []; // 当前控制器的日期列表
  CalendarController calendarController = Get.find<CalendarController>();
  int _maxScheduleLines = 3; // 最大的日程行数【需要动态计算】
  double _viewHeight = 0; // 维护一个视口高度，如果视口高度不变，那么日程的高度不需要计算
  int _calendarLines = 0; // 维护一个日历行数，如果日历行数不变，那么日程的高度不需要计算
  GlobalKey _gridAreaKey = GlobalKey(); // 日历的key，用于获取日历的高度
  @override
  void initState() {
    super.initState();

    /// 监控resize事件，动态计算最大日程行数
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _handleMaxScheduleLines();
    });

    /// 监听resize事件
    Sizer.ins.addListener(_onWindowResize);

    monthViewDaysList = calendarController.monthViewDaysList;
    calendarController.onDaysListChange.addListener(_onDaysListChange);
  }

  void _onWindowResize(e) {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _handleMaxScheduleLines();
    });
  }

  @override
  void dispose() {
    super.dispose();
    Sizer.ins.removeListener(_onWindowResize);

    calendarController.onDaysListChange.removeListener(_onDaysListChange);
  }

  void _onDaysListChange(_, e) {
    setState(() {
      monthViewDaysList = calendarController.monthViewDaysList;
    });
    _handleMaxScheduleLines();
  }

  @override
  FWidget build(BuildContext context) {
    return FColumn(
      key: _gridAreaKey,
      children: <FWidget>[
        _buildMonthCalendarWeekTitle(),
        FExpanded(child: _buildMonthCalendarDaysBody()),
      ],
    );
  }

  /// 构建「日、一、二、三、四、五、六」的标题
  FWidget _buildMonthCalendarWeekTitle() {
    return FSizedBox(
      height: 30,
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: <FWidget>[
          _buildEachTitle(i18nBook.calendar.singleSunday.t),
          _buildEachTitle(i18nBook.calendar.singleMonday.t),
          _buildEachTitle(i18nBook.calendar.singleTuesday.t),
          _buildEachTitle(i18nBook.calendar.singleWednesday.t),
          _buildEachTitle(i18nBook.calendar.singleThursday.t),
          _buildEachTitle(i18nBook.calendar.singleFriday.t),
          _buildEachTitle(i18nBook.calendar.singleSaturday.t),
        ],
      ),
    );
  }

  FWidget _buildEachTitle(String title) {
    const weekTextStyle = TextStyle(fontSize: 12, color: Colors.black);
    return FSizedBox(
      width: 25,
      child: FText(
        title,
        style: weekTextStyle,
        textAlign: TextAlign.center,
      ),
    );
  }

  /// 构建日历主体
  FWidget _buildMonthCalendarDaysBody() {
    // 将35天分成5个周
    final weeksInMonth = <List<MonthViewDayModel>>[];
    for (var i = 0; i < monthViewDaysList.length; i += 7) {
      weeksInMonth.add(monthViewDaysList.sublist(i, i + 7));
    }
    return FSizedBox(
      child: FColumn(
        mainAxisSize: MainAxisSize.max,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: weeksInMonth.map(_buildMonthCalendarDayRow).toList(),
      ),
    );
  }

  /// 构建每一行（周）
  FWidget _buildMonthCalendarDayRow(List<MonthViewDayModel> sevenDays) {
    return FExpanded(
      child: FRow(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: sevenDays.map(_buildEachDay).toList(),
      ),
    );
  }

  /// 构建每一天
  FWidget _buildEachDay(MonthViewDayModel day) {
    return FExpanded(
      child: FContainer(
        decoration: const BoxDecoration(
          border: Border(
            right: BorderSide(
              color: Colors.black12,
              width: 1,
            ),
            top: BorderSide(
              color: Colors.black12,
              width: 1,
            ),
          ),
        ),
        child: MonthDayItem(
          dayData: day,
          maxScheduleLines: _maxScheduleLines,
        ),
      ),
    );
  }

  /// 动态计算日历格内的最大日程行数
  void _handleMaxScheduleLines() {
    final gridAreaHeight = _getGridAreaHeight(_gridAreaKey);
    if (gridAreaHeight == _viewHeight &&
        calendarController.calendarLines == _calendarLines) return;
    _viewHeight = gridAreaHeight;
    _calendarLines = calendarController.calendarLines;
    final gridRows = calendarController.calendarLines;
    final gridHeight = gridAreaHeight;
    final gridItemHeight = gridHeight / gridRows;
    final scheduleAreaHeight = gridItemHeight - 30; // 30 是日期的高度
    final maxLines = (scheduleAreaHeight / 20).floor();
    setState(() {
      _maxScheduleLines = maxLines;
    });
  }

  /// 通过组件的 key 获取对应的组件的大小信息
  /// 获取日历格区域的高度
  double _getGridAreaHeight(GlobalKey key) {
    try {
      final RenderBox renderBox =
          key.currentContext?.findRenderObject() as RenderBox;
      return renderBox.size.height;
    } catch (e) {
      print('fail to count the size: $e');
      return 0;
    }
  }
}
