import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:functional_widget_annotation/functional_widget_annotation.dart';
import 'package:marking_app/common/mixin/common.dart';
import 'package:marking_app/common/model/event_bus/job_home_refresh_bus.dart';
import 'package:marking_app/common/model/marking/marking_list_params.dart';
import 'package:marking_app/pages/common/event_bus_mixin.dart';
import 'package:marking_app/routes/RouterManager.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/my_text.dart';

import 'package:badges/badges.dart' as badges;

import '../../utils/my_future_builder.dart';

part 'job_home.g.dart';

class JobHome extends StatefulWidget {
  const JobHome({super.key});

  @override
  State<JobHome> createState() => _JobHomeState();
}

class _JobHomeState extends State<JobHome> with CommonMixin, EventBusMixin, AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;

  late Future<int> _future;
  List<EntranceModel> entrances = [
    EntranceModel(
      title: '作业批阅',
      image: '',
      navigationUrl: RouterManager.jobMainListPagePath,
    ),
    EntranceModel(
      title: '学生历史作业',
      image: '',
      navigationUrl: RouterManager.jobStudentGroupPath,
      page: 'history',
    ),
    EntranceModel(
      title: '知识点掌握',
      image: '',
      navigationUrl: RouterManager.jobKnowledgePointsPath,
    ),
    EntranceModel(
      title: '答题轨迹',
      image: '',
      navigationUrl: '',
    ),
    EntranceModel(
      title: '优先批阅设定',
      image: '',
      navigationUrl: RouterManager.jobStudentGroupPath,
      page: 'set',
    ),
    EntranceModel(
      title: '批阅设置',
      image: '',
      navigationUrl: '',
    ),
  ];

  @override
  void initState() {
    _future = getData();
    eventOn(callback: (JobHomeRefreshBus item) {
      _future = getData();
      toUpState(setState, () {}, mounted);
    });
    super.initState();
  }

  @override
  void dispose() {
    eventCancel();
    super.dispose();
  }

  Future<int> getData() async {
    try {
      var _client = await getClient();
      var _result = await _client.getJobsByPage(MarkingListParams(
        isFinish: false,
        page: 1,
        limit: 1,
        pageType: 0,
      ));
      return _result.data?.total ?? 0;
    } catch (e) {
      return 0;
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);

    return AnnotatedRegion(
      value: const SystemUiOverlayStyle(
        systemNavigationBarColor: Color(0xFF000000),
        systemNavigationBarDividerColor: null,
        statusBarColor: Colors.white,
        systemNavigationBarIconBrightness: Brightness.light,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
      ),
      child: Scaffold(
        appBar: AppBar(
          backgroundColor: Colors.white,
          centerTitle: true, // 标题居中
          title: quickText('我的作业管理'),
          systemOverlayStyle: SystemUiOverlayStyle.dark,
          elevation: 0,
        ),
        backgroundColor: Color.fromRGBO(244, 244, 244, 1),
        body: RefreshIndicator(
          onRefresh: () async {
            _future = getData();
            toUpState(setState, () {}, mounted);
          },
          child: MyFutureBuilder.buildFutureBuilderOfSingleInstance<int>(context, _future, (data) {
            if (data == null)
              return Center(
                child: Container(
                  child: TextButton(
                    onPressed: () {
                      _future = getData();
                      toUpState(setState, () {}, mounted);
                    },
                    child: quickText('没有获取到数据，点击重试'),
                  ),
                ),
              );

            return Container(
              child: Column(
                children: [
                  Container(
                    height: 200.h,
                    width: double.infinity,
                    decoration: BoxDecoration(
                      image: DecorationImage(
                        image: AssetImage('assets/images/job_home_top_bgm.png'),
                        fit: BoxFit.fill, // 完全填充
                      ),
                    ),
                  ),
                  $TermRow([
                    EntranceModel(
                      title: '答题轨迹',
                      image: '',
                      navigationUrl: '',
                    ),
                    EntranceModel(
                      title: '优先批阅设定',
                      image: '',
                      navigationUrl: RouterManager.jobStudentGroupPath,
                      page: 'set',
                    ),
                  ], data)
                  // Row(
                  //   children: [
                  //     Expanded(child: Container(
                  //       child: ,
                  //     )),
                  //     Expanded(child: Container()),
                  //   ],
                  // ),
                  // Expanded(
                  //   child:
                  // GridView(
                  //   padding: EdgeInsets.symmetric(vertical: 30.h, horizontal: 20.w),
                  //   gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  //     crossAxisCount: 2,
                  //     mainAxisSpacing: 24.r,
                  //     crossAxisSpacing: 24.r,
                  //     childAspectRatio: 556 / 200,
                  //   ),
                  //   children: entrances.map((e) {
                  //     bool isJob = e.title == '作业批阅';

                  //     return InkWell(
                  //         onTap: () => easyThrottle('GO_TO_JOB_HOME_NAVIGATION', () {
                  //               if (e.page != '') {
                  //                 RouterManager.router.navigateTo(context, '${e.navigationUrl}?page=${e.page}', transition: getTransition());
                  //               } else {
                  //                 RouterManager.router.navigateTo(context, e.navigationUrl, transition: getTransition());
                  //               }
                  //             }),
                  //         child: badges.Badge(
                  //           showBadge: isJob && data > 0,
                  //           ignorePointer: false,
                  //           badgeContent: quickText(data, color: Colors.white),
                  //           badgeAnimation: badges.BadgeAnimation.rotation(
                  //             animationDuration: Duration(seconds: 1),
                  //             colorChangeAnimationDuration: Duration(seconds: 1),
                  //             loopAnimation: false,
                  //             curve: Curves.fastOutSlowIn,
                  //             colorChangeAnimationCurve: Curves.easeInCubic,
                  //           ),
                  //           child: Container(
                  //             decoration: BoxDecoration(
                  //               borderRadius: BorderRadius.all(Radius.circular(6.r)),
                  //               border: Border.all(
                  //                 width: 0.5.w,
                  //                 color: Color.fromARGB(255, 219, 226, 250),
                  //               ),
                  //             ),
                  //             alignment: Alignment.center,
                  //             child: Row(
                  //               mainAxisAlignment: MainAxisAlignment.center,
                  //               children: [
                  //                 // Image(image: e.image),
                  //                 Icon(
                  //                   const IconData(0xe642, fontFamily: "AlibabaIcon"),
                  //                   size: 12.sp,
                  //                 ),
                  //                 quickText(e.title, size: 12.sp),
                  //               ],
                  //             ),
                  //           ),
                  //         ));
                  //   }).toList(),
                  // ),
                  // ),
                ],
              ),
            );
          }),
        ),
      ),
    );
  }
}

class EntranceModel extends Object {
  String title;
  String image;
  String navigationUrl;
  String? page;
  EntranceModel({required this.title, required this.image, required this.navigationUrl, this.page = ''});
}

@swidget
Widget $termRow(BuildContext context, List<EntranceModel> items, int data) {
  var leng = items.length;
  Widget childWidget;
  switch (leng) {
    case 1:
      var e = items[0];
      bool isJob = e.title == '作业批阅';
      childWidget = InkWell(
          onTap: () => easyThrottle('GO_TO_JOB_HOME_NAVIGATION', () {
                if (e.page != '') {
                  RouterManager.router.navigateTo(context, '${e.navigationUrl}?page=${e.page}', transition: getTransition());
                } else {
                  RouterManager.router.navigateTo(context, e.navigationUrl, transition: getTransition());
                }
              }),
          child: badges.Badge(
            showBadge: isJob && data > 0,
            ignorePointer: false,
            badgeContent: quickText(data, color: Colors.white),
            badgeAnimation: badges.BadgeAnimation.rotation(
              animationDuration: Duration(seconds: 1),
              colorChangeAnimationDuration: Duration(seconds: 1),
              loopAnimation: false,
              curve: Curves.fastOutSlowIn,
              colorChangeAnimationCurve: Curves.easeInCubic,
            ),
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(6.r)),
                border: Border.all(
                  width: 0.5.w,
                  color: Color.fromARGB(255, 219, 226, 250),
                ),
              ),
              alignment: Alignment.center,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // Image(image: e.image),
                  Icon(
                    const IconData(0xe642, fontFamily: "AlibabaIcon"),
                    size: 12.sp,
                  ),
                  quickText(e.title, size: 12.sp),
                ],
              ),
            ),
          ));
      break;
    case 2:
      childWidget = Row(
        children: items.map((e) {
          var e = items[0];
          bool isJob = e.title == '作业批阅';
          return InkWell(
              onTap: () => easyThrottle('GO_TO_JOB_HOME_NAVIGATION', () {
                    if (e.page != '') {
                      RouterManager.router.navigateTo(context, '${e.navigationUrl}?page=${e.page}', transition: getTransition());
                    } else {
                      RouterManager.router.navigateTo(context, e.navigationUrl, transition: getTransition());
                    }
                  }),
              child: badges.Badge(
                showBadge: isJob && data > 0,
                ignorePointer: false,
                badgeContent: quickText(data, color: Colors.white),
                badgeAnimation: badges.BadgeAnimation.rotation(
                  animationDuration: Duration(seconds: 1),
                  colorChangeAnimationDuration: Duration(seconds: 1),
                  loopAnimation: false,
                  curve: Curves.fastOutSlowIn,
                  colorChangeAnimationCurve: Curves.easeInCubic,
                ),
                child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.all(Radius.circular(6.r)),
                    border: Border.all(
                      width: 0.5.w,
                      color: Color.fromARGB(255, 219, 226, 250),
                    ),
                  ),
                  alignment: Alignment.center,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      // Image(image: e.image),
                      Icon(
                        const IconData(0xe642, fontFamily: "AlibabaIcon"),
                        size: 12.sp,
                      ),
                      quickText(e.title, size: 12.sp),
                    ],
                  ),
                ),
              ));
        }).toList(),
      );

      break;
    case 3:
      var e = items[0];
      bool isJob = e.title == '作业批阅';
      childWidget = InkWell(
          onTap: () => easyThrottle('GO_TO_JOB_HOME_NAVIGATION', () {
                if (e.page != '') {
                  RouterManager.router.navigateTo(context, '${e.navigationUrl}?page=${e.page}', transition: getTransition());
                } else {
                  RouterManager.router.navigateTo(context, e.navigationUrl, transition: getTransition());
                }
              }),
          child: badges.Badge(
            showBadge: isJob && data > 0,
            ignorePointer: false,
            badgeContent: quickText(data, color: Colors.white),
            badgeAnimation: badges.BadgeAnimation.rotation(
              animationDuration: Duration(seconds: 1),
              colorChangeAnimationDuration: Duration(seconds: 1),
              loopAnimation: false,
              curve: Curves.fastOutSlowIn,
              colorChangeAnimationCurve: Curves.easeInCubic,
            ),
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(6.r)),
                border: Border.all(
                  width: 0.5.w,
                  color: Color.fromARGB(255, 219, 226, 250),
                ),
              ),
              alignment: Alignment.center,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  // Image(image: e.image),
                  Icon(
                    const IconData(0xe642, fontFamily: "AlibabaIcon"),
                    size: 12.sp,
                  ),
                  quickText(e.title, size: 12.sp),
                ],
              ),
            ),
          ));
      break;
    default:
      childWidget = Container();
  }

  return Container(child: childWidget);
}
