/*
 * @Author: WuXiangNan
 * @Date: 2021-03-16 11:12:48
 * @LastEditTime : 2022-01-19 16:39:35
 * @LastEditors  : WuWei
 * @Description: 考勤日历
 */

import 'package:app_package/app_package.dart';
import 'package:attendance_package/src/models/enum.dart';
import 'package:attendance_package/src/models/response_model/calendar/calendar_model.dart';
import 'package:attendance_package/src/models/response_model/calendar/clock_infos_model.dart';
import 'package:attendance_package/src/service/impl/attendance_service_impl.dart';
import 'package:flutter/material.dart';
import 'package:flutter_calendar_carousel/classes/event.dart';
import 'package:flutter_calendar_carousel/classes/event_list.dart';
import 'package:flutter_calendar_carousel/flutter_calendar_carousel.dart';
import 'package:intl/intl.dart';
import 'package:wisdom_cli/wisdom_cli.dart';

class CalendarStore with ChangeNotifier {
  final BuildContext context;

  late Map args;
  CalendarStore(this.context) {
    args =
        ModalRoute.of(context)!.settings.arguments as Map<dynamic, dynamic>? ??
            {};
  }

  DateTime currentDate = DateTime.now();
  DateTime currentDate2 = DateTime.now();
  String currentMonth = DateFormat('yyyy-MM').format(DateTime.now());
  DateTime targetDateTime = DateTime.now();

  EventList<Event> attendanceEvent = EventList<Event>(events: {});

  List<CalendarModel>? calendarData;

  int clockTimes = 0;

  //当前员工的信息
  final authGlobalStore = GetIt.I.get<AuthGlobalStore>();
  //当前员工的信息
  EmployeesInfoModel? get userInfo => authGlobalStore.info;

  // 状态
  String? clockStatusText;

  CalendarModel? selectedDay;

  // 考勤日历
  Future<void> getCalendar(String? id, String date) async {
    WLoadingUtil.show();
    final res = await AttendanceServiceImpl().getCalendar({
      'groupIdentification': id,
      'yearMonth': date,
      'employeeId': userInfo!.id,
      // 固定班制
      // 'employeeId': '284394842658852864',
      // 排班制
      // 'employeeId': '136884611961634816',
      // 自由工时
      // 'employeeId': '136884045252444160',
      // 'companyId': '136523944394149888',
      'companyId': userInfo!.companyId,
    });
    calendarData = res.data;
    initEvent();
    WLoadingUtil.hide();
  }

  // 初始化日历事件
  void initEvent() {
    attendanceEvent = EventList<Event>(events: {});
    for (CalendarModel item in calendarData ?? []) {
      var day = DateTime(targetDateTime.year, targetDateTime.month, item.day!);
      Color? color;
      // 0：异常；1：正常；2：休息；
      switch (item.clockStatus) {
        case 0:
          color = Colors.orange;
          break;
        case 1:
          color = Color(0XFF27CEAC);
          break;
        case 2:
          color = Colors.white;
          break;
      }

      if (item.clockStatus != 2) {
        attendanceEvent.add(
          day,
          Event(
            date: day,
            title: 'Attendance',
            dot: Container(
              margin: EdgeInsets.symmetric(horizontal: 1.0),
              height: 5.0,
              width: 5.0,
              decoration: new BoxDecoration(
                  color: color,
                  borderRadius: BorderRadius.all(Radius.circular(1000)),
                  border: Border.all(color: color!, width: 2.0)),
            ),
          ),
        );
      }
      notifyListeners();
    }
  }

  // 上个月
  void preMount() {
    targetDateTime = DateTime(targetDateTime.year, targetDateTime.month - 1);
    currentMonth = DateFormat('yyyy-MM').format(targetDateTime);
    notifyListeners();
    getCalendar(args['groupId'], currentMonth);
  }

  // 下个月
  void nextMount() {
    targetDateTime = DateTime(targetDateTime.year, targetDateTime.month + 1);
    currentMonth = DateFormat('yyyy-MM').format(targetDateTime);
    notifyListeners();
    getCalendar(args['groupId'], currentMonth);
  }

  // 日历改变
  void calendarOnChange(DateTime date) {
    targetDateTime = date;
    currentMonth = DateFormat('yyyy-MM').format(targetDateTime);
    notifyListeners();
    getCalendar(args['groupId'], currentMonth);
  }

  // 日历：选中日期
  void calendarOnPressed(DateTime date, List<Event> events) {
    clockTimes = 0;
    currentDate2 = date;
    selectedDay =
        (calendarData?.length ?? 0) > 0 ? calendarData![date.day - 1] : null;

    computedWorkTime(selectedDay?.clockInfos);
    if (selectedDay != null)
      for (var i = 0; i < selectedDay!.clockInfos!.length; i++) {
        ClockInfosModel item = selectedDay!.clockInfos![i];
        if (item.clockResult != null &&
            ClockResult.values[item.clockResult!].toString() !=
                'ClockResult.CARD_MISS') clockTimes++;
      }

    bool isWeekend = false;
    if (date.weekday == 6 || date.weekday == 7) {
      isWeekend = true;
    }
    switch (selectedDay?.clockStatus) {
      case 0:
        clockStatusText = '异常';
        break;
      case 1:
        clockStatusText = '正常';
        break;
      case 2:
        if (isWeekend) {
          clockStatusText = '休息';
          break;
        }
        clockStatusText = '当日未排班';
        break;
    }
    notifyListeners();
  }

  // 计算有效出勤工时
  String computedWorkTime(List<ClockInfosModel>? clockInfos) {
    var timeTemp = 0;
    var date = DateFormat("yyyy-MM-dd ").format(currentDate2);

    for (int i = 1; clockInfos != null && i < clockInfos.length; i = i + 2) {
      if (clockInfos[i].clockResult != 4 &&
          clockInfos[i].clockResult != 2 &&
          clockInfos[i].date != null &&
          clockInfos[i - 1].date != null) {
        var str1 = date + clockInfos[i].date!;
        var str2 = date + clockInfos[i - 1].date!;
        timeTemp = timeTemp +
            (DateTime.parse(str1).millisecondsSinceEpoch -
                DateTime.parse(str2).millisecondsSinceEpoch);
      }
    }
    return _durationTransform(timeTemp);
  }

  //时间转换 将豪秒转换为小时分钟
  String _durationTransform(int milliseconds) {
    var d = Duration(milliseconds: milliseconds);
    List<String> parts = d.toString().split(':');
    return '${parts[0]}小时${parts[1]}分钟';
  }
}
