import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_hooks/flutter_hooks.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;

  @override
  void initState() {
    getData();
    eventOn(callback: (JobHomeRefreshBus item) => getData());
    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,
      ));
      var data = _result.data?.total ?? 0;
      eventFire(model: QuantityToBeReviewedData(data));
      return data;
    } catch (e) {
      return 0;
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    var spaceWidth = SizedBox(height: ScreenUtil().screenWidth / 19);
    return AnnotatedRegion(
      value: const SystemUiOverlayStyle(
        systemNavigationBarColor: Color(0xFF000000),
        systemNavigationBarDividerColor: null,
        statusBarColor: Colors.white,
        systemNavigationBarIconBrightness: Brightness.light,
        statusBarIconBrightness: Brightness.dark,
        statusBarBrightness: Brightness.light,
      ),
      child: RefreshIndicator(
        onRefresh: () async => eventFire(model: JobHomeRefreshBus()),
        child: ListView(
          children: [
            Container(
              constraints: BoxConstraints(
                minHeight: 200.h,
                maxWidth: double.infinity,
              ),
              // decoration: BoxDecoration(
              //   image: DecorationImage(
              //     image: AssetImage('assets/images/job_home_top_bgm.png'),
              //     fit: BoxFit.fitWidth, // 完全填充
              //   ),
              // ),
              child: Image.asset('assets/images/job_home_top_bgm.png', fit: BoxFit.fitWidth),
            ),
            SizedBox(height: 30.h),
            SlidingData([
              EntranceModel(title: '作业批阅', image: 'assets/images/job_home_marking.png', navigationUrl: RouterManager.jobMainListPagePath),
              EntranceModel(
                title: '学生历史作业',
                image: 'assets/images/job_home_history.png',
                navigationUrl: '${RouterManager.jobStudentGroupPath}?page=history',
              ),
              EntranceModel(title: '知识点点掌握', image: 'assets/images/job_home_knowledge.png', navigationUrl: RouterManager.jobKnowledgePointsPath)
            ]),
            spaceWidth,
            $TermRow([
              EntranceModel(title: '答题轨迹', image: 'assets/images/job_home_answer_record.png', navigationUrl: RouterManager.answerTrajectoryPath),
              EntranceModel(
                title: '优先批阅设定',
                image: 'assets/images/job_home_youxian.png',
                navigationUrl: '${RouterManager.jobStudentGroupPath}?page=set',
              )
            ], 0),
            // spaceWidth,
            // $TermRow([EntranceModel(title: '批阅设置', image: 'assets/images/job_home_marking_set.png', navigationUrl: '')], 0),
          ],
        ),
      ),
    );
  }
}

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

class QuantityToBeReviewedData extends Object {
  int num;
  QuantityToBeReviewedData(this.num);
}

@swidget
Widget $termRow(BuildContext context, List<EntranceModel> items, int data) {
  var leng = items.length;
  Widget childWidget;
  switch (leng) {
    case 1:
      childWidget = Row(children: [Expanded(child: $TermItem(items[0], data))]);
      break;
    case 2:
      childWidget = Row(children: [
        Expanded(flex: 9, child: $TermItem(items[0], data)),
        Expanded(flex: 1, child: SizedBox()),
        Expanded(flex: 9, child: $TermItem(items[1], data)),
      ]);
      break;
    case 3:
      double _theHeight = ScreenUtil().screenWidth / 19 + 54.h * 2;
      childWidget = Row(
        children: [
          Expanded(child: $TermItem(items[0], data, theHeight: _theHeight)),
          SizedBox(width: ScreenUtil().screenWidth / 19),
          Expanded(
            child: SizedBox(
              height: _theHeight,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  $TermItem(items[1], data),
                  $TermItem(items[2], data),
                ],
              ),
            ),
          ),
        ],
      );
      break;
    default:
      childWidget = Container();
  }

  return Container(padding: EdgeInsets.symmetric(horizontal: 14.w), child: childWidget);
}

@swidget
Widget $termItem(BuildContext context, EntranceModel e, int data, {double? theHeight}) {
  bool isJob = e.title == '作业批阅';

  return Material(
    color: Colors.white,
    elevation: 3.r,
    shadowColor: const Color.fromRGBO(231, 231, 231, 1),
    borderRadius: BorderRadius.all(Radius.circular(8.r)),
    child: InkWell(
        onTap: () => easyThrottle('GO_TO_JOB_HOME_NAVIGATION', () {
              RouterManager.router.navigateTo(context, e.navigationUrl, transition: getTransition());
            }),

        // splashColor: splashColor,
        borderRadius: BorderRadius.all(Radius.circular(8.r)),
        child: badges.Badge(
          showBadge: isJob && data > 0,
          ignorePointer: false,
          badgeContent: quickText(data, color: Colors.white, size: 10.sp),
          badgeAnimation: badges.BadgeAnimation.rotation(
            animationDuration: Duration(seconds: 1),
            colorChangeAnimationDuration: Duration(seconds: 1),
            loopAnimation: false,
            curve: Curves.fastOutSlowIn,
            colorChangeAnimationCurve: Curves.easeInCubic,
          ),
          badgeStyle: badges.BadgeStyle(
            badgeColor: Color.fromRGBO(255, 105, 105, 1),
            shape: badges.BadgeShape.square,
            borderRadius: BorderRadius.only(topLeft: Radius.circular(10.r), topRight: Radius.circular(8.5.r), bottomRight: Radius.circular(8.5.r)),
            // borderSide: BorderSide(color: Colors.white, width: 2),
            elevation: 1,
            padding: EdgeInsets.symmetric(horizontal: isPad() ? 11.w : 16.w, vertical: 2.h),
          ),
          position: badges.BadgePosition.topEnd(top: 10.r, end: 10.r),
          child: Container(
            height: theHeight,
            padding: EdgeInsets.symmetric(vertical: 12.h),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.all(Radius.circular(8.r)),
              // boxShadow: [
              //   BoxShadow(
              //     color: const Color.fromRGBO(231, 231, 231, 1),
              //     offset: Offset(4.w, 6.h), //阴影y轴偏移量
              //     blurRadius: 8, //阴影模糊程度
              //     spreadRadius: 0.2, //阴影扩散程度
              //   )
              // ],
              // border: Border.all(width: 0.5.w, color: Color.fromARGB(255, 219, 226, 250)),
            ),
            alignment: Alignment.center,
            child: isJob
                ? Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(e.image, height: 32.r, width: 32.r, fit: BoxFit.cover),
                      SizedBox(height: 6.r),
                      quickText(e.title, size: 12.sp, color: Color.fromRGBO(79, 79, 79, 1), fontWeight: FontWeight.w500),
                    ],
                  )
                : Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(e.image, height: 32.r, width: 32.r, fit: BoxFit.cover),
                      SizedBox(width: 6.r),
                      quickText(e.title, size: 12.sp, color: Color.fromRGBO(79, 79, 79, 1), fontWeight: FontWeight.w500),
                    ],
                  ),
          ),
        )),
  );
}

class SlidingData extends HookWidget with EventBusMixin {
  final List<EntranceModel> items;
  SlidingData(this.items);

  @override
  Widget build(BuildContext context) {
    var dataNumber = useState<QuantityToBeReviewedData?>(null);

    useEffect(() {
      eventOn(callback: (QuantityToBeReviewedData data) => (dataNumber.value = data));
      return () {
        eventCancel();
      };
    }, []);

    return $TermRow(items, dataNumber.value?.num ?? 0);
  }
}
