import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:making_school_asignment_app/common/job/knowledge_points_grasp.dart';
import 'package:making_school_asignment_app/common/utils/anti_shake_throttling.dart';
import 'package:making_school_asignment_app/common/utils/utils.dart';
import 'package:making_school_asignment_app/page/global_widget/MyEmptyWidget.dart';
import 'package:making_school_asignment_app/page/global_widget/ReturnToHomepage.dart';
import 'package:making_school_asignment_app/page/home_page/children/student_work_detail/widget/job_condition_filter.dart';
import 'package:making_school_asignment_app/page/home_page/widget/progress_bar.dart';
import 'package:making_school_asignment_app/routes/app_pages.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';

import 'knowledge_points_grasp_logic.dart';

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

  @override
  State<KnowledgePointsGraspPage> createState() => _KnowledgePointsGraspPageState();
}

class _KnowledgePointsGraspPageState extends State<KnowledgePointsGraspPage> {
  final logic = Get.find<KnowledgePointsGraspLogic>();
  final state = Get.find<KnowledgePointsGraspLogic>().state;

  @override
  Widget build(BuildContext context) {
    return OrientationBuilder(builder: (BuildContext context, Orientation orientation) {
      return Scaffold(
        backgroundColor: const Color.fromRGBO(245, 245, 245, 1),
        appBar: AppBar(
          backgroundColor: Colors.white,
          title: Text('知识点掌握', style: TextStyle(fontSize: 14.sp, color: const Color(0xFF333333))),
          centerTitle: true,
          leading: IconButton(
            icon: const Icon(Icons.arrow_back_ios, color: Colors.black),
            onPressed: () => Get.back(),
          ),
          actions: const [
            ReturnToHomepage(),
          ],
          elevation: 0,
        ),
        body: Column(
          children: [
            Container(
              margin: EdgeInsets.all(15.r),
              // height: 30.r,
              child: Row(
                children: [
                  Expanded(
                    child: Container(
                      padding: EdgeInsets.only(left: 10.r, right: 10.r),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(6.r),
                        border: Border.all(width: 1.r, color: const Color(0xFFDDDDDD)),
                        color: Colors.white,
                      ),
                      child: TextField(
                        controller: logic.textController,
                        textInputAction: TextInputAction.next,
                        style: TextStyle(
                          color: const Color.fromRGBO(80, 87, 103, 1),
                          fontSize: 10.sp,
                        ),
                        decoration: InputDecoration(
                          hintText: "请输入知识点名称",
                          hintStyle: TextStyle(fontSize: 10.sp, color: const Color.fromRGBO(153, 153, 153, 1)),
                          labelStyle: TextStyle(fontSize: 10.sp, color: const Color.fromRGBO(148, 163, 182, 1)),
                          border: InputBorder.none,
                        ),
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 10.r,
                  ),
                  InkWell(
                    onTap: () => easyThrottle('zshi_shi_dian_cx', () {
                      Utils.hideKeyboard();
                      logic.refreshController.callRefresh();
                    }),
                    child: Container(
                      width: 50.r,
                      height: 30.r,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(4.r), color: Theme.of(context).primaryColor),
                      child: Center(
                        child: Text(
                          '查询',
                          style: TextStyle(fontSize: 12.sp, color: Colors.white),
                        ),
                      ),
                    ),
                  )
                ],
              ),
            ),
            Obx(() {
              return JobConditionFilter(
                jobType: 1,
                controller: logic.tabController,
                customTimeStr: state.customTimeStr.value,
                customTime: logic.tabController.index != 2 || ((state.dateEnd == '') && (state.dateStart == ''))
                    ? null
                    : PickerDateRange(
                        state.dateStart == '' ? null : DateTime.parse(state.dateStart),
                        state.dateEnd == '' ? null : DateTime.parse(state.dateEnd),
                      ),
                onTimeFilter: (String? startTime, String? endTime) {
                  EasyLoading.show(status: 'loading...');
                  if (startTime == null && endTime == null) {
                    if (logic.tabController.index == 2) {
                      logic.tabController.animateTo(0);
                    }
                    state.dateStart = Utils.getWeekStartDate().toString().substring(0, 10);
                    state.dateEnd = Utils.getWeekEndDate().toString().substring(0, 10);
                    state.customTimeStr.value = '自定义';
                  } else {
                    state.dateStart = startTime ?? '';
                    state.dateEnd = endTime ?? '';
                  }
                  state.page = 1;
                  logic.getList();
                  // _refreshController2.callRefresh();
                },
                refreshTime: (value) {
                  if (value != null && value.startDate != null) {
                    state.customTimeStr.value = value.startDate?.toString().substring(0, 10) ?? '';
                    if (value.endDate != null) {
                      if (!Utils.isPad() && value.startDate!.year == value.endDate!.year) {
                        state.customTimeStr.value =
                            '${value.startDate.toString().substring(5, 10)}~${value.endDate.toString().substring(5, 10)}';
                      } else {
                        state.customTimeStr.value =
                            '${state.customTimeStr.value}~${value.endDate?.toString().substring(0, 10)}';
                      }
                    }
                  }
                },
              );
            }),
            Expanded(
              child: Padding(
                padding: EdgeInsets.symmetric(vertical: 10.r),
                child: Obx(() {
                  return EasyRefresh(
                    firstRefresh: false,
                    taskIndependence: true,
                    controller: logic.refreshController,
                    header: MaterialHeader(),
                    footer: TaurusFooter(),
                    onRefresh: () async {
                      state.page = 1;
                      logic.getList();
                    },
                    onLoad: () async {
                      if (state.page < state.totalPages) {
                        state.page += 1;
                        logic.getList();
                      }
                    },
                    child: state.dataList.isNotEmpty
                        ? ListView.builder(
                            itemCount: state.dataList.value.length,
                            itemBuilder: (context, index) {
                              KnowledgePointsGrasp item = state.dataList[index];
                              return InkWell(
                                onTap: () {
                                  Get.toNamed(Routes.knowledgePointsGraspDetailPage, arguments: {
                                    'dateStart': state.dateStart,
                                    'dateEnd': state.dateEnd,
                                    'knowledgeId': item.knowledgeId,
                                    'knowledgeName': item.knowledgeName,
                                    'subject': state.subject
                                  });
                                },
                                child: Container(
                                  margin: EdgeInsets.symmetric(vertical: 5.r, horizontal: 14.r),
                                  padding: EdgeInsets.symmetric(vertical: 14.r, horizontal: 10.r),
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.all(Radius.circular(10.r)), color: Colors.white),
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.start,
                                        crossAxisAlignment: CrossAxisAlignment.end,
                                        children: [
                                          Expanded(
                                              child: Text(
                                            item.knowledgeName,
                                            style: TextStyle(fontSize: 14.sp, color: const Color(0xFF505050)),
                                          )),
                                          Container(
                                            width: 49.r,
                                            height: 22.r,
                                            decoration: BoxDecoration(
                                              borderRadius: BorderRadius.all(Radius.circular(20.r)),
                                              border: Border.all(width: 1.r, color: Theme.of(context).primaryColor),
                                            ),
                                            child: Row(
                                              mainAxisAlignment: MainAxisAlignment.center,
                                              crossAxisAlignment: CrossAxisAlignment.center,
                                              children: [
                                                Text(
                                                  '${item.count}次',
                                                  style:
                                                      TextStyle(fontSize: 10.sp, color: Theme.of(context).primaryColor),
                                                ),
                                                SizedBox(width: 1.w),
                                                Padding(
                                                  padding: EdgeInsets.only(top: 2.h),
                                                  child: Icon(Icons.chevron_right,
                                                      size: 12.r, color: Theme.of(context).primaryColor),
                                                ),
                                                // Image.asset(
                                                //   'assets/images/job_data_right_icon.png',
                                                //   width: 10.r,
                                                //   height: 10.r,
                                                // ),
                                              ],
                                            ),
                                          ),
                                        ],
                                      ),
                                      SizedBox(
                                        height: 10.r,
                                      ),
                                      ProgressBar(
                                          title: '正确率：',
                                          color: const Color(0xFFB2DA93),
                                          percent: item.correctRate / 100,
                                          padingEdg: EdgeInsets.zero,
                                          marginEdg: EdgeInsets.only(top: 8.h)),
                                    ],
                                  ),
                                ),
                              );
                            })
                        : const MyEmptyWidget(),
                  );
                }),
              ),
            ),
          ],
        ),
      );
    });
  }

  @override
  void dispose() {
    Get.delete<KnowledgePointsGraspLogic>();
    super.dispose();
  }
}
