/*
 * @Author: WuXiangNan
 * @Date: 2021-02-18 10:21:01
 * @LastEditTime : 2023-05-10 10:59:11
 * @LastEditors  : WuWei
 * @Description: 
 */

import 'package:attendance_package/src/assets.gen.dart';
import 'package:attendance_package/src/models/enum.dart';
import 'package:attendance_package/src/models/response_model/clock_status/current_clock_status_vos_model.dart';
import 'package:flutter/material.dart';
import 'package:wisdom_cli/wisdom_cli.dart';
import '../../public/location.dart';
import '../../view_models/attendance_store.dart';
import 'package:intl/intl.dart';

import 'clock.dart';

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

class Sign extends StatelessWidget {
  const Sign({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => AttendanceStore(context),
      lazy: false,
      child: _PageView(),
    );
  }
}

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

  @override
  __PageViewState createState() => __PageViewState();
}

class __PageViewState extends State<_PageView> {
  AttendanceStore get attendanceStore =>
      Provider.of<AttendanceStore>(context, listen: false);
  LocationStore get store => Provider.of<LocationStore>(context, listen: false);

  @override
  void initState() {
    super.initState();
  }


  @override
  void dispose() {
    attendanceStore.destory();
    store.destory();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final colorScheme = WTheme.of(context).colorScheme;
    final attendance = Provider.of<AttendanceStore>(context);

    return Scaffold(
      appBar: WAppBar(
        brightness: Brightness.light,
        title: WisText('${attendance.args['appBarTitle']}',
            size: 19.pt, weight: FontWeight.w600, color: colorScheme.mainTitle),
        iconTheme: IconThemeData(
          color: colorScheme.mainTitle,
          size: 19.pt,
        ),
        backgroundColor: Colors.white,
        actions: [
          Wisdom(
            margin: EdgeInsets.only(right: 15.pt),
            onTap: () {
              if (attendance.groupIdentification != null)
                Navigator.pushNamed(
                  context,
                  'attendance/calendar/index',
                  arguments: {"groupId": attendance.groupIdentification},
                );
              else {
                WToastUtil.show('未属于任何一个考勤组，暂无考勤统计信息',
                    location: WToastLoction.center);
              }
            },
            child: Icon(
              Icons.calendar_today_outlined,
              size: 21.pt,
              color: colorScheme.mainTitle,
            ),
          )
        ],
      ),
      body: Wisdom(
        margin: EdgeInsets.only(bottom: 10.pt),
        child: Wisdom.column(
          children: [
            WisCard(
              margin: EdgeInsets.fromLTRB(15.pt, 15.pt, 15.pt, 0),
              child: Wisdom.row(
                padding: EdgeInsets.fromLTRB(15.pt, 20.pt, 15.pt, 20.pt),
                color: Colors.white,
                children: [
                  // WisImage.asset(
                  //   AssetList.$rtx_png,
                  //   width: 42.pt,
                  //   height: 42.pt,
                  //   fit: BoxFit.fill,
                  //   borderRadius: BorderRadius.circular(100.pt),
                  // ),
                  Image(
                    image: AssetList.$rtx_png_image,
                    height: 42.pt,
                    width: 42.pt,
                    fit: BoxFit.fill,
                  ),
                  Wisdom.column(
                    children: [
                      Wisdom.row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        margin: EdgeInsets.only(left: 15.pt, bottom: 5.pt),
                        children: [
                          WisText(
                            attendance.userInfo!.name!,
                            bold: true,
                            size: 16.pt,
                          ),
                          Wisdom(
                            child: WisText(
                              '查看打卡规则',
                              color: colorScheme.primary,
                            ),
                            onTap: () {
                              if (attendance.groupIdentification != null)
                                Navigator.pushNamed(
                                  context,
                                  'attendance/rule/index',
                                  arguments: {
                                    "groupId": attendance.groupIdentification
                                  },
                                );
                              else {
                                WToastUtil.show('未属于任何一个考勤组，暂无打卡规则',
                                    location: WToastLoction.center);
                              }
                            },
                          ),
                        ],
                      ),
                      Wisdom.row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        width: 287.pt,
                        margin: EdgeInsets.only(left: 15.pt),
                        children: [
                          WisText(
                            attendance.userInfo!.phone!,
                            color: colorScheme.minor,
                            size: 14.pt,
                          ),
                          WisText(
                            DateFormat("yyyy-MM-dd").format(DateTime.now()),
                            color: colorScheme.minor,
                            size: 14.pt,
                          )
                        ],
                      ),
                    ],
                  ).asExpanded()
                ],
              ),
            ),
            // 打卡时间线
            buildTimeLine(),
          ],
        ),
      ),
      // bottomNavigationBar: WisButton(
      //     child: Text(
      //       '地勤管理',
      //       style: TextStyle(fontSize: 16.pt),
      //     ),
      //     color: colorScheme.primary,
      //     buttonShape: WisButtonShape.square,
      //     constraints: BoxConstraints(minHeight: 44.pt),
      //     onPressed: () {
      //       WToastUtil.show('功能正在开发中...', location: WToastLoction.center);
      //     }
      //     //  Navigator.pushNamed(context, 'attendance/track/index'),
      //     ),
    );
  }

  Widget buildTimeLine() {
    final colorScheme = WTheme.of(context).colorScheme;
    final attendance = Provider.of<AttendanceStore>(context);

    List<CurrentClockStatusVosModel>? timeLine = attendance.clockTimeLineList;
    return WisScrollView(
      key: attendance.scorllViewKey,
      onInit: () => attendance.onInit()!.then((value) => value),
      onRefresh: () => attendance.onInit()!.then((value) => value),
      controller: attendance.scrollController,
      slivers: [
        if (attendance.clockStatusData == null)
          SliverFillRemaining(
            child: buildLoading(),
          ),
        WisSliverList.childBuilder(
          childCount: timeLine?.length ?? 0,
          padding: EdgeInsets.symmetric(horizontal: 10.pt),
          builder: (_, i) {
            var clockResults =
                ClockResult.values[timeLine![i].clockResult ?? 0].toString();
            var clockType =
                ClockType.values[timeLine[i].clockType ?? 0].toString();

            return Wisdom.stack(
              clipBehavior: Clip.none,
              margin: EdgeInsets.all(30.pt),
              children: [
                Wisdom.column(
                  margin: EdgeInsets.only(left: 30.pt),
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    WisText(
                      clockType == 'ClockType.AFTERWORK'
                          ? '下班打卡 ${attendance.timeFormat(timeLine[i].shouldClockTime) ?? ''}'
                          : '上班打卡 ${attendance.timeFormat(timeLine[i].shouldClockTime) ?? ''}',
                      color: (timeLine[i].current == true)
                          ? colorScheme.primary
                          : colorScheme.minor,
                      size: 15.pt,
                    ),
                    if (timeLine[i].clockResult != null)
                      Wisdom.row(
                        children: [
                          // 外勤迟到、早退等特殊情况或者非外勤
                          if ((timeLine[i].clockWay == '3' &&
                                  timeLine[i].clockResult != 0) ||
                              timeLine[i].clockWay != '3')
                            WTag(
                              child: Text(
                                  clockResultList[timeLine[i].clockResult!]),
                              color: clockResults == 'ClockResult.NORMAL'
                                  ? Color(0xFF2FB22B)
                                  : Colors.orange,
                            ),
                          // 外勤打卡记录
                          if (timeLine[i].clockWay == '3')
                            WTag(
                              child: Text('外勤'),
                              color: Colors.orange,
                            ),
                          if (clockResults != 'ClockResult.CARD_MISS')
                            Wisdom.row(
                              children: [
                                WisText(' 打卡时间 '),
                                WisText(
                                  attendance
                                          .timeFormat(timeLine[i].clockTime) ??
                                      '',
                                  color: Color(0XFF0F67F8),
                                ),
                                SizedBox(
                                  width: 20.pt,
                                ),
                                // 非外勤打卡情况下显示地点
                                // if (timeLine[i].locateName != null)
                                //   Wisdom.row(
                                //     maxWidth: 100.pt,
                                //     crossAxisAlignment:
                                //         CrossAxisAlignment.start,
                                //     children: [
                                //       Icon(
                                //         Icons.location_on,
                                //         color: colorScheme.disabled,
                                //       ),
                                //       WisText(
                                //         timeLine[i].locateName!,
                                //         color: colorScheme.minor,
                                //         maxLines: 1,
                                //         overflow: TextOverflow.ellipsis,
                                //       ).asExpanded()
                                //     ],
                                //   )
                              ],
                            )
                          else
                            WisText(
                              '无打卡记录',
                              color: Color(0XFF0F67F8),
                            ),
                        ],
                      ),
                    if (timeLine[i].current == true &&
                        i == timeLine.length - 1 &&
                        timeLine[i].clockTime != null)
                      Wisdom.row(
                        onTap: () => attendance.clockIn(),
                        children: [
                          WisText(
                            '更新打卡',
                            color: Color(0XFF0F67F8),
                          ),
                          Icon(
                            Icons.keyboard_arrow_right,
                            color: Color(0XFF0F67F8),
                          )
                        ],
                      )
                  ],
                ),
                if (i != timeLine.length - 1)
                  Positioned(
                    left: 0.pt,
                    top: 5.pt,
                    bottom: -65.pt,
                    child: Container(
                      width: 1,
                      color: colorScheme.divider,
                    ),
                  ),
                Positioned(
                  left: -5.pt,
                  top: 5.pt,
                  child: Wisdom(
                    height: 10.pt,
                    width: 10.pt,
                    color: (timeLine[i].current != true)
                        ? Color(0xFFDEE3E9)
                        : colorScheme.primary,
                    borderRadius: BorderRadius.circular(10.pt),
                  ),
                ),
                if ((timeLine[i].current == true &&
                    timeLine[i].clockTime == null &&
                    attendance.shiftType != 'ShiftType.FREE_TIME'))
                  Wisdom(
                    margin: EdgeInsets.only(top: 50.pt),
                    child: ClockPageModel(),
                  ),
              ],
            );
          },
        ),
        if (timeLine?.length == 0)
          SliverFillRemaining(
            child: ClockPageModel(),
          )
        // 自由班次且打卡次数大于零，或未排班
        else if ((attendance.shiftType == 'ShiftType.FREE_TIME' &&
                (timeLine?.length ?? 0) > 0) ||
            (attendance.clockStatusData?.workDay == false))
          // 打卡
          ClockPageModel().asSliver(),
      ],
    ).asExpanded();
  }

  Widget buildLoading() {
    return Container(
      height: 20,
      width: 20,
      alignment: Alignment.center,
      child: SizedBox(
        height: 20,
        width: 20,
        child: CircularProgressIndicator(
          valueColor: AlwaysStoppedAnimation(
            Theme.of(context).indicatorColor,
          ),
          strokeWidth: 2,
        ),
      ),
    );
  }
}
