import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_easyrefresh/easy_refresh.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/common/base_structure_result.dart';
import 'package:marking_app/common/model/job/job_knowledge_detail_student.dart';
import 'package:marking_app/common/model/job/job_knowledge_points.dart';
import 'package:marking_app/common/model/job/job_knowledge_points_detail.dart';
import 'package:marking_app/common/model/job/job_student_history.dart';
import 'package:marking_app/components/ReturnToHomepage.dart';
import 'package:marking_app/pages/homework_correction/widget/personal_detail_topbar.dart';
import 'package:marking_app/routes/RouterManager.dart';
import 'package:marking_app/utils/easy_refresh/MyEmptyWidget.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/my_text.dart';
import 'package:marking_app/utils/request/rest_client.dart';
import 'package:percent_indicator/percent_indicator.dart';
import 'package:photo_view/photo_view.dart';
import 'package:syncfusion_flutter_datepicker/datepicker.dart';

class JobKnowledgePointsDetail extends StatefulWidget {
  final String knowledgeName;
  final int knowledgeId;

  const JobKnowledgePointsDetail(
      {Key? key, required this.knowledgeName, required this.knowledgeId})
      : super(key: key);

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

class _JobKnowledgePointsDetailState extends State<JobKnowledgePointsDetail>
    with CommonMixin, TickerProviderStateMixin {
  @override
  List<KnowledgePointsDetail> dataList = [];
  List<JobKnowledgeDetailStudent> studentList = [];
  late final EasyRefreshController refreshController;
  String paperImg = '';

  int studentId = 0;

  @override
  void initState() {
    super.initState();
    refreshController = EasyRefreshController();
    EasyLoading.show(status: 'loading...');
    getList();
  }

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

  void getList() async {
    RestClient _client = await getClient();
    BaseStructureResult<List<KnowledgePointsDetail>> res =
        await _client.getKnowledgeReportDetail(widget.knowledgeId);
    if (res.success) {
      setState(() {
        dataList = res.data!;
      });
    }

    EasyLoading.dismiss();
  }

  showStudent(questionid, title) async {
    await getStudents(questionid);

    showModalBottomSheet(
      context: context,
      elevation: 10,
      backgroundColor: Colors.white,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(20.r),
          topRight: Radius.circular(20.r),
        ),
      ),
      builder: (BuildContext context) {
        return Padding(
          padding: EdgeInsets.symmetric(horizontal: 2.w),
          child: Column(
            children: [
              Container(
                margin: EdgeInsets.only(top: 14.h),
                child: quickText(
                  title,
                  size: 18.sp,
                  fontWeight: FontWeight.bold,
                  color: Color.fromRGBO(60, 60, 60, 1),
                ),
              ),
              Expanded(
                child: ListView(
                  padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 4.w),
                  children: [
                    Wrap(
                      spacing: 6.r, // 主轴(水平)方向间距
                      runSpacing: 4.r, // 纵轴（垂直）方向间距
                      alignment: WrapAlignment.spaceAround, //沿主轴方向居中
                      children: studentList.map((e) {
                        return Container(
                          padding: EdgeInsets.symmetric(
                              vertical: 4.r, horizontal: 8.r),
                          decoration: BoxDecoration(
                            color: e.isAnswer
                                ? Color(0xFF4CC793)
                                : Color(0xFFE2E2E2),
                            borderRadius: BorderRadius.circular(4.r),
                          ),
                          child: quickText(e.studentName,
                              color:
                                  e.isAnswer ? Colors.white : Color(0xFF505E6E),
                              size: 10.sp),
                        );
                      }).toList(),
                    ),
                  ],
                ),
              )
            ],
          ),
        );
      },
    );
    EasyLoading.dismiss();
  }

  showImg(int sectionId, String questionNo) async {
    await getImg(sectionId, questionNo);
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          insetPadding: EdgeInsets.symmetric(vertical: 55.r,horizontal: 45.r),
          contentPadding: EdgeInsets.all(0),
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(15.r))),
          content: Container(
            width: MediaQuery.of(context).size.width,
            // height: MediaQuery.of(context).size.height,
            child: Image.network(paperImg),
          ),
        );
      },
    );
    EasyLoading.dismiss();
  }

  getStudents(questionid) async {
    RestClient _client = await getClient();
    BaseStructureResult<List<JobKnowledgeDetailStudent>> res =
        await _client.getKnowledgeStudent(questionid);
    if (res.success) {
      studentList = res.data!;
    } else {
      studentList = [];
    }
  }

  getImg(int sectionId, String questionNo) async {
    RestClient _client = await getClient();
    BaseStructureResult<String> res =
        await _client.getKnowledgeImg(sectionId, questionNo);
    if (res.success) {
      paperImg = res.data!;
    } else {
      paperImg = '';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color.fromRGBO(245, 245, 245, 1),
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text(widget.knowledgeName,
            style: TextStyle(fontSize: 14.sp, color: Color(0xFF333333))),
        centerTitle: true,
        leading: IconButton(
          icon: Icon(Icons.arrow_back_ios, color: Colors.black),
          onPressed: () => Navigator.of(context).pop(),
        ),
        actions: [
          ReturnToHomepage(),
        ],
        elevation: 0,
      ),
      body: Padding(
        padding: EdgeInsets.symmetric(vertical: 10.r),
        child: EasyRefresh(
          firstRefresh: false,
          taskIndependence: true,
          controller: refreshController,
          header: MaterialHeader(),
          footer: TaurusFooter(),
          onRefresh: () async {
            getList();
          },
          onLoad: () async {
            // getList();
          },
          child: dataList.length > 0
              ? ListView.builder(
                  itemCount: dataList.length,
                  itemBuilder: (context, index) {
                    KnowledgePointsDetail item = dataList[index];
                    return InkWell(
                      onTap: () {
                        /*  RouterManager.router.navigateTo(
                      context,
                      RouterManager.quickCheckPersonalPath +
                          '?jobId=${item.jobName}&studentId=$studentId',
                      transition: getTransition(),
                    );*/
                      },
                      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: [
                                Text(
                                  item.publishTime.substring(0, 10),
                                  style: TextStyle(
                                      fontSize: 14.sp,
                                      color: Color(0xFF505050)),
                                ),
                                SizedBox(
                                  width: 10.r,
                                ),
                                Expanded(
                                    child: Text(
                                  item.jobName,
                                  style: TextStyle(
                                      fontSize: 14.sp,
                                      color: Color(0xFF505050)),
                                )),
                                InkWell(
                                  onTap: () {
                                    EasyLoading.show(status: 'loading...');
                                    showImg(item.sectionId, item.questionNo);
                                  },
                                  child: Container(
                                    width: 49.r,
                                    height: 22.r,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(20.r)),
                                      border: Border.all(
                                          width: 1.r, color: Color(0xFF8B8B8B)),
                                    ),
                                    child: Center(
                                      child: Text(
                                        '${item.questionNo}题',
                                        style: TextStyle(
                                            fontSize: 10.sp,
                                            color: Color(0xFF8B8B8B)),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                            SizedBox(
                              height: 10.r,
                            ),
                            Container(
                              margin: EdgeInsets.only(top: 8.h),
                              padding: EdgeInsets.zero,
                              child: Row(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  InkWell(
                                    onTap: () {
                                      EasyLoading.show(status: 'loading...');
                                      showStudent(
                                          item.questionId, item.jobName);
                                    },
                                    child: Container(
                                        margin: EdgeInsets.only(right: 6.r),
                                        width: 56.r,
                                        height: 20.r,
                                        decoration: BoxDecoration(
                                          color: Color(0xFFD4FFED),
                                          borderRadius:
                                              BorderRadius.circular(20.r),
                                        ),
                                        child: Center(
                                            child: quickText('正确率 >',
                                                color: Color(0xFF4CC793),
                                                size: 10.sp))),
                                  ),
                                  Expanded(
                                    flex: 1,
                                    child: Container(
                                      child: Row(
                                        children: [
                                          Expanded(
                                            child: Container(
                                              decoration: BoxDecoration(
                                                borderRadius:
                                                    BorderRadius.circular(10.r),
                                              ),
                                              child: LinearPercentIndicator(
                                                padding: EdgeInsets.zero,
                                                animation: true,
                                                lineHeight: 8.h,
                                                animationDuration: 2500,
                                                percent: item.correctRate / 100,
                                                progressColor:
                                                    Color(0xFF90E0BE),
                                                backgroundColor:
                                                    Color(0xFFE8E8E8),
                                                barRadius:
                                                    Radius.circular(10.r),
                                              ),
                                            ),
                                          ),
                                          SizedBox(width: 4.w),
                                          quickText(
                                              '${doubleToStringAsFixed(item.correctRate / 100 * 100)}%',
                                              size: 10.sp,
                                              color: Color(0xFF606060))
                                        ],
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            /* progressBar(context,
                            title: '正确率 >',
                            color: Color(0xFF90E0BE),
                            percent: item.correctRate / 100,
                            padingEdg: EdgeInsets.zero,
                            marginEdg: EdgeInsets.only(top: 8.h),
                        studentCall:showStudent(item.questionId,item.jobName),
                        ),*/
                          ],
                        ),
                      ),
                    );
                  })
              : MyEmptyWidget(),
        ),
      ),
    );
  }
}

@swidget
Widget progressBar(
  BuildContext context, {
  double? fontSize,
  double? lineHeight,
  required String title,
  required Color color,
  required double percent,
  required EdgeInsets padingEdg,
  required EdgeInsets marginEdg,
  required Future<dynamic> studentCall,
}) {
  var percentStr = '${doubleToStringAsFixed(percent * 100)}%';
  fontSize ??= 10.sp;
  lineHeight ??= 8.h;
  return Container(
    margin: marginEdg,
    padding: padingEdg,
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        InkWell(
          onTap: () {
            studentCall;
          },
          child: Container(
              margin: EdgeInsets.only(right: 6.r),
              width: 56.r,
              height: 20.r,
              decoration: BoxDecoration(
                color: Color(0xFFD4FFED),
                borderRadius: BorderRadius.circular(20.r),
              ),
              child: Center(
                  child: quickText(title,
                      color: Color(0xFF4CC793), size: fontSize))),
        ),
        Expanded(
          flex: 1,
          child: Container(
            child: Row(
              children: [
                Expanded(
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(10.r),
                      /* boxShadow: [
                          BoxShadow(
                            color: color,
                            spreadRadius: 0.6,
                            blurRadius: 3,
                            offset: Offset(0, 0),
                          ),
                        ],*/
                    ),
                    child: LinearPercentIndicator(
                      padding: EdgeInsets.zero,
                      animation: true,
                      lineHeight: lineHeight,
                      animationDuration: 2500,
                      percent: percent,
                      /* center: Text(
                          percentStr,
                          style: TextStyle(color: Colors.white, fontSize: 4.5.sp),
                        ),*/
                      // linearStrokeCap: LinearStrokeCap.butt,
                      progressColor: color,
                      backgroundColor: Color(0xFFE8E8E8),
                      barRadius: Radius.circular(10.r),
                      // linearGradient: LinearGradient(
                      //   tileMode: TileMode.mirror,
                      //   stops: [0.0, 1.0],
                      //   colors: [color.withOpacity(0.1), color],
                      // ),
                    ),
                  ),
                ),
                SizedBox(width: 4.w),
                quickText(percentStr, size: fontSize, color: Color(0xFF606060))
              ],
            ),
          ),
        ),
      ],
    ),
  );
}
