/*
 * @Author: WuXiangNan
 * @Date: 2021-02-25 16:23:31
 * @LastEditTime : 2023-05-15 17:29:06
 * @LastEditors  : WuWei
 * @Description: 
 */

import 'package:attendance_package/src/models/enum.dart';
import 'package:attendance_package/src/models/response_model/calendar/clock_infos_model.dart';
import 'package:attendance_package/src/view_models/attendance_calendar.dart';
import 'package:flutter/material.dart';

import 'package:flutter_calendar_carousel/flutter_calendar_carousel.dart'
    show CalendarCarousel;
import 'package:flutter_calendar_carousel/classes/event.dart';
import 'package:intl/intl.dart' show DateFormat;
import 'package:wisdom_cli/wisdom_cli.dart';
import '../../assets.gen.dart';

class CalendarPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => CalendarStore(context),
      child: MyHomePage(),
      lazy: false,
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  CalendarCarousel? calendarCarouselNoHeader;

  CalendarStore get calendarStore =>
      Provider.of<CalendarStore>(context, listen: false);

  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) async {
      if (calendarStore.args['groupId'] != null)
        calendarStore.getCalendar(calendarStore.args['groupId'],
            DateFormat('yyyy-MM').format(DateTime.now()));
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    initCalendar();
    final store = Provider.of<CalendarStore>(context);
    final colorScheme = WTheme.of(context).colorScheme;
    return Scaffold(
      appBar: WAppBar(
        brightness: Brightness.light,
        title: WisText('考勤统计',
            size: 19.pt, weight: FontWeight.w600, color: colorScheme.mainTitle),
        iconTheme: IconThemeData(
          color: colorScheme.mainTitle,
          size: 19.pt,
        ),
        backgroundColor: Colors.white,
      ),
      body: Wisdom(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Wisdom.row(
              color: Colors.white,
              padding: EdgeInsets.symmetric(vertical: 15.pt),
              mainAxisAlignment: MainAxisAlignment.spaceAround,
              children: [
                Wisdom(
                  child: Image(
                    image: AssetList.$xz_png_image,
                    width: 13.pt,
                    height: 12.pt,
                  ),
                  onTap: () => store.preMount(),
                ),
                WisText(
                  store.currentMonth,
                  size: 15.pt,
                ),
                Wisdom(
                  child: Image(
                    image: AssetList.$xy_png_image,
                    width: 13.pt,
                    height: 12.pt,
                  ),
                  onTap: () => store.nextMount(),
                ),
              ],
            ),
            Divider(
              height: 0.5,
              color: Color(0xFFE6E6E6),
            ),
            Container(
              color: Colors.white,
              child: calendarCarouselNoHeader,
            ),
            if (store.clockStatusText == '休息')
              Wisdom.column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                margin: EdgeInsets.only(top: 10.pt),
                width: MediaQuery.of(context).size.width,
                padding: EdgeInsets.symmetric(vertical: 15.pt),
                color: Colors.white,
                height: 178.pt,
                children: [
                  Image(
                    image: AssetList.$drxx_png_image,
                    width: 199.pt,
                    height: 131.pt,
                  ),
                  WisText(
                    '当日休息',
                    size: 14.pt,
                    color: Color(0xFF666666),
                  ),
                ],
              ).asExpanded()
            else
              buildCalendarInfo(),
          ],
        ),
      ),
    );
  }

  void initCalendar() {
    final colorScheme = WTheme.of(context).colorScheme;
    final store = Provider.of<CalendarStore>(context);
    calendarCarouselNoHeader = CalendarCarousel<Event>(
      todayBorderColor: Colors.white,
      onDayPressed: (DateTime date, List<Event> events) {
        store.calendarOnPressed(date, events);
      },
      // locale: 'zh',
      customWeekDayBuilder: (weekday, weekdayName) {
        @override
        Widget build(BuildContext context) {
          switch (weekday) {
            case 1:
              weekdayName = '一';
              break;
            case 2:
              weekdayName = '二';
              break;
            case 3:
              weekdayName = '三';
              break;
            case 4:
              weekdayName = '四';
              break;
            case 5:
              weekdayName = '五';
              break;
            case 6:
              weekdayName = '六';
              break;
            case 0:
              weekdayName = '日';
              break;
          }
          return Wisdom(
            padding: EdgeInsets.all(15.pt),
            child: WisText(
              weekdayName,
              color: Color(0xFF666666),
            ),
          );
        }

        return build(context);
      },
      daysTextStyle: TextStyle(
        fontSize: 14.pt,
        fontWeight: FontWeight.bold,
        color: Colors.black,
      ),
      weekendTextStyle: TextStyle(
        fontSize: 14.pt,
        fontWeight: FontWeight.bold,
        color: Color(0xFF666666),
      ),
      // 圆形边框
      daysHaveCircularBorder: true,
      showOnlyCurrentMonthDate: false,
      weekFormat: false,
      // markedDatesMap: _markedDateMap,
      markedDatesMap: store.attendanceEvent,
      height: 400.0,
      selectedDateTime: store.currentDate2,
      targetDateTime: store.targetDateTime,
      customGridViewPhysics: NeverScrollableScrollPhysics(),
      markedDateCustomTextStyle: TextStyle(
        fontSize: 18,
        color: Color(0XFF0F67F8),
      ),
      showHeader: false,
      showWeekDays: true,
      todayTextStyle: TextStyle(
          color: colorScheme.primary,
          fontWeight: FontWeight.bold,
          fontSize: 14.pt),
      todayButtonColor: Colors.white,
      selectedDayTextStyle: TextStyle(
        color: Colors.white,
        fontSize: 15.pt,
        // fontFamily: 'HiraginoSansGB-W3',
      ),
      selectedDayButtonColor: colorScheme.primary,
      selectedDayBorderColor: colorScheme.primary,
      minSelectedDate: store.currentDate.subtract(Duration(days: 360)),
      maxSelectedDate: store.currentDate.add(Duration(days: 360)),
      prevDaysTextStyle: TextStyle(
        fontSize: 14.pt,
        color: Colors.grey,
      ),
      nextDaysTextStyle: TextStyle(
        fontSize: 14.pt,
        color: Colors.grey,
      ),
      inactiveDaysTextStyle: TextStyle(
        color: Colors.tealAccent,
        fontSize: 16,
      ),
      onCalendarChanged: (DateTime date) {
        store.calendarOnChange(date);
      },
    );
  }

  Widget buildCalendarInfo() {
    final colorScheme = WTheme.of(context).colorScheme;
    final store = Provider.of<CalendarStore>(context);
    List<ClockInfosModel> clockInfos = store.selectedDay?.clockInfos ?? [];
    return ListView(
      children: <Widget>[
        Wisdom.column(
          margin: EdgeInsets.only(top: 10.pt),
          width: MediaQuery.of(context).size.width,
          padding: EdgeInsets.symmetric(vertical: 20.pt),
          color: Colors.white,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Wisdom(
              margin: EdgeInsets.only(left: 15.pt),
              child: WisText(
                store.selectedDay?.shiftInfo != null
                    ? '班次：${store.selectedDay?.shiftInfo}'
                    : '班次：当日暂无排班',
                color: colorScheme.grey,
                size: 14.pt,
              ),
            ),
            if (store.selectedDay?.shiftInfo != null)
              Wisdom.column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Wisdom(
                    margin: EdgeInsets.only(left: 15.pt, bottom: 10.pt),
                    child: WisText(
                      '今日打卡${store.clockTimes}次，共工作${store.computedWorkTime(store.selectedDay!.clockInfos)}',
                      color: colorScheme.grey,
                      size: 14.pt,
                    ),
                  ),
                  Divider(
                    color: Color(0xFFE6E6E6),
                  ),
                ],
              ),
            for (var i = 0; i < clockInfos.length; i++)
              Wisdom.stack(
                clipBehavior: Clip.none,
                margin: EdgeInsets.fromLTRB(20.pt, 15.pt, 15.pt, 0.pt),
                children: [
                  Wisdom.column(
                    margin: EdgeInsets.only(left: 20.pt),
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    children: [
                      Wisdom.row(
                        children: [
                          WisText(
                            clockInfos[i].clockType == 0
                                ? '上班打卡：${clockInfos[i].date ?? '未打卡'}'
                                : '下班打卡：${clockInfos[i].date ?? '未打卡'}',
                            color: colorScheme.mainTitle,
                            size: 15.pt,
                          ),
                          Wisdom(
                            margin: EdgeInsets.only(left: 10.pt),
                            child: WTag(
                              color: clockInfos[i].clockResult == 0
                                  ? Color(0xFF25B41C)
                                  : Colors.orange,
                              child: Text(
                                clockResultList[clockInfos[i].clockResult!] ??
                                    '',
                              ),
                            ),
                          ),
                        ],
                      )
                    ],
                  ),
                  if (i != clockInfos.length - 1)
                    Positioned(
                      left: 0.pt,
                      top: 5.pt,
                      bottom: -20.pt,
                      child: Container(
                        width: 1,
                        color: colorScheme.divider,
                      ),
                    ),
                  Positioned(
                      left: -5.pt,
                      top: 5.pt,
                      child: Wisdom(
                          height: 10.pt,
                          width: 10.pt,
                          color: Color(0xFFDEE3E9),
                          borderRadius: BorderRadius.circular(10.pt))),
                ],
              ),
          ],
        ),
      ],
    ).asExpanded();
  }
}
