import 'package:achievement_view/achievement_view.dart';
import 'package:easy_stepper/easy_stepper.dart';
import 'package:flutter/material.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_page_data_report.dart';
import 'package:marking_app/common/model/common/base_structure_result_report.dart';
import 'package:marking_app/common/model/report/marked_item.dart';
import 'package:marking_app/common/model/report/marked_item_params.dart';
import 'package:marking_app/common/model/user/user_info_report.dart';
import 'package:marking_app/utils/easy_refresh/MyEmptyWidget.dart';
import 'package:marking_app/utils/easy_refresh/mixin/refresh_data_handle_report.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/my_text.dart';
import 'package:marking_app/utils/request/rest_client_report.dart';

part 'report_home_services.g.dart';

// 用户身份和考试切换
class SwitchIdentityExamsController with CommonMixin, RefreshDataHandleReport<MarkedItem, MarkedItemParams> {
  ValueNotifier<int> positionIndex; //  职位下标
  ValueNotifier<int> examIndex; //  考试下标
  ValueNotifier<int> stepIndex; //  步骤下标
  ValueNotifier<int> examId; // 考试ID

  ValueNotifier<MarkedItemParams> examParams; //  考试请求参数
  ValueNotifier<List<MarkedItem>?> exams; //  考试数据

  // EasyRefreshController refreshController;
  List<Positions> positons;

  double? positionDy; // 考试Y轴位置

  SwitchIdentityExamsController({
    required this.positionIndex,
    required this.examIndex,
    required this.stepIndex,
    required this.examId,
    required this.examParams,
    required this.exams,
    // required this.refreshController,
    required this.positons,
  });

  void dispose() {
    positons = [];
    // refreshController.dispose();

    exams.dispose();
    examParams.dispose();
    positionIndex.dispose();
    examIndex.dispose();
    stepIndex.dispose();
  }

  static SwitchIdentityExamsController use(
      {required int position,
      required int exam,
      required int? initExamId,
      int step = 0,
      required List<Positions> positons}) {
    final positionuseState = useState(position);
    final examState = useState(exam);
    final stepState = useState(step);
    final initExamIdState = useState(initExamId ?? -1);

    final examParamsState =
        useState(MarkedItemParams(1, 10, roleId: positons.isNotEmpty ? positons[positionuseState.value].id : 0));
    final examsState = useState<List<MarkedItem>?>(null);

    // EasyRefreshController _easyRefresh = EasyRefreshController();
    SwitchIdentityExamsController example = SwitchIdentityExamsController(
      positionIndex: positionuseState,
      examIndex: examState,
      stepIndex: stepState,
      examId: initExamIdState,
      examParams: examParamsState,
      exams: examsState,
      // refreshController: _easyRefresh,
      positons: positons,
    );

    return example;
  }

  void setIndexData({required int indexExam, required int indexPosition}) {
    examIndex.value = indexExam;
    examId.value = exams.value?[indexExam].id ?? -1;
    positionIndex.value = indexPosition;
  }

  /// temPositionIndex 当前选中的步骤
  void nextStepButtonCall(int temPositionIndex, EasyRefreshController refreshController, state) {
    int oldPositionIndex = positionIndex.value; // 旧职位小标
    positionIndex.value = temPositionIndex;

    examParams.value.roleId = positons[positionIndex.value].id; // 用户身份职位更新
    // 职务没有改变，不用再发起请求直接跳转到考试
    state(() => stepIndex.value = 1);

    if (exams.value == null || oldPositionIndex != temPositionIndex) {
      // 需要发起请求
      examId.value = -1;
      examIndex.value = -1;
      exams.value?.clear();
      positionDy = null; // 清空确定位置
      setTimeOut(200, () => refreshController.callRefresh());
    }
  }

  Future<void> getExamData(
      {required BuildContext context,
      required state,
      required EasyRefreshController refreshController,
      bool isRefresh = true}) async {
    MarkedItemParams params = examParams.value;
    if (isRefresh) {
      // 更新数据
      examParams.value.roleId = positons[positionIndex.value].id;
    } else {
      // 数据页自加
      params.page += 1;
    }

    RestClientReport clientReport = await getClientReport();
    BasePageDataReport<MarkedItem>? results = await toRefreshData(
      refreshController,
      api: clientReport.getexamsbyuser,
      params: examParams.value,
      isReFresh: isRefresh,
      context: context,
    );
    if (results != null) {
      if (isRefresh) exams.value?.clear();

      if (exams.value == null) {
        exams.value = results.items;
      } else {
        exams.value!.addAll(results.items);
      }
      int theExamId = examId.value;
      if (theExamId != -1) {
        MarkedItem? item = exams.value?.firstWhere((element) => element.id == theExamId,
            orElse: () => MarkedItem(-1, -1, '', -1, '', '', '', -1, ''));
        if (item != null && item.id != -1) {
          examId.value = item.id;
          examIndex.value = exams.value!.indexOf(item);
        } else {
          examId.value = -1;
          examIndex.value = -1;
        }
      }
      state(() => {});
    }
  }

  Future<int?> openSwitch(
      {required BuildContext context, required int currentExamId, required int currentPositionIndex}) async {
    var size = MediaQuery.of(context).size; //获取屏幕宽高和Widget大小
    ScrollController _scroller = ScrollController();
    EasyRefreshController _easyRefresh = EasyRefreshController();
    Future<bool?> future = showModalBottomSheet<bool>(
      backgroundColor: Colors.transparent,
      //颜色空白
      isDismissible: true,
      //能否点击消失
      isScrollControlled: true,
      //能否拖动消失
      context: context,
      //接受cotext
      builder: (context) {
        // int temPositionIndex = positionIndex.value;
        // int temExamIndex = examIndex.value;

        int temPositionIndex = currentPositionIndex;
        int temExamIndex = examIndex.value;

        return StatefulBuilder(builder: (context, state) {
          MarkedItem? currentExam =
              (exams.value?.isEmpty ?? true) || temExamIndex == -1 ? null : exams.value![temExamIndex];
          if (currentExam == null && temExamIndex == -1 && exams.value != null) {
            temExamIndex = exams.value!.indexWhere((element) => element.id == currentExamId);
            if (temExamIndex != -1) {
              currentExam = exams.value![temExamIndex];
            }
          }
          final Positions currentPosition = positons[temPositionIndex];
          bool roleBody = stepIndex.value == 0;

          return Stack(
            alignment: const FractionalOffset(0.96, 0.02),
            children: [
              Container(
                width: size.width,
                height: size.height * 0.8, //使用屏幕宽高比设置大小
                padding: EdgeInsets.only(top: 12.h, left: 20.w, right: 20.w, bottom: 21.h),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    //圆角
                    topLeft: Radius.circular(20), //左上角的圆角
                    topRight: Radius.circular(20), //右上角的圆角
                  ),
                ),
                child: Column(
                  children: [
                    $EasyStepper(stepIndex.value, Theme.of(context).primaryColor.withOpacity(0.3), (int stepVal) {
                      int oldStep = stepIndex.value;
                      if (oldStep == stepVal) return;

                      stepIndex.value = stepVal;
                      if (stepVal == 1) {
                        // 角色 =》 考试
                        nextStepButtonCall(temPositionIndex, _easyRefresh, state);
                      } else {
                        // 考试 =》 角色
                        state(() => {});
                      }
                    }),
                    Expanded(
                      child: $ChooseBox(
                        roleBody,
                        roleBody
                            ?
                            // 角色body
                            ScrollConfiguration(
                                behavior: EUMNoScrollBehavior(),
                                child: positons.isEmpty
                                    ? Center(child: MyEmptyWidget(padding: EdgeInsets.only(top: 80.h)))
                                    : ListView(
                                        children: positons.map((e) {
                                          bool isCurrent = currentPosition.id == e.id;
                                          return InkWell(
                                            onTap: () {
                                              state(() => temPositionIndex = positons.indexOf(e));
                                            },
                                            child: $ItemContainer(isCurrent, e.name, context),
                                          );
                                        }).toList(),
                                      ),
                              )
                            :
                            // 考试body
                            $ExamsContainer(
                                refreshController: _easyRefresh,
                                widgets: (exams.value == null || exams.value!.isEmpty)
                                    ? [Center(child: MyEmptyWidget(padding: EdgeInsets.only(top: 80.h)))]
                                    : exams.value!.map((e) {
                                        bool isCurrent =
                                            currentExam == null ? e.id == currentExamId : currentExam.id == e.id;
                                        return GestureDetector(
                                          onTapUp: (TapUpDetails details) {
                                            Offset position = details.localPosition;
                                            positionDy = position.dy;
                                            state(() => temExamIndex = exams.value!.indexOf(e));
                                          },
                                          child: $ItemContainer(isCurrent, e.name, context),
                                        );
                                      }).toList(),
                                toGetDatacall: (bool isRefresh) => getExamData(
                                    context: context,
                                    state: state,
                                    refreshController: _easyRefresh,
                                    isRefresh: isRefresh),
                              ),
                      ),
                    ),
                    if (roleBody) // 下一步按钮
                      $NextStepButton(temPositionIndex, temExamIndex, context,
                          () => nextStepButtonCall(temPositionIndex, _easyRefresh, state))
                    else // 确认按钮
                      $ConfirmButton(temPositionIndex, temExamIndex, context, () async {
                        if (temExamIndex == -1) {
                          return AchievementView(
                            elevation: 0.5,
                            duration: Duration(seconds: 1),
                            title: "提示",
                            subTitle: "请选择想要查看的考试",
                            color: Theme.of(context).primaryColor,
                          ).show(context);
                        }
                        try {
                          ToastUtils.showLoading();
                          setIndexData(indexExam: temExamIndex, indexPosition: temPositionIndex);
                          RestClientReport clientReport = await getClientReport();
                          BaseStructureResultReport<bool> baseRest =
                              await clientReport.switchposition(currentPosition.id);
                          if (!baseRest.success || baseRest.data == null || baseRest.data == false) {
                            return ToastUtils.showError(baseRest.message ?? '身份切换错误，请重试');
                          }
                          Navigator.of(context).pop(true);
                        } catch (e) {
                          toPrint(val: '请求报错....，$e');
                        } finally {
                          ToastUtils.dismiss();
                        }
                      }),
                  ],
                ),
              ),
              InkWell(
                onTap: () {
                  Navigator.of(context).pop(false);
                },
                child: Icon(Icons.close, size: 30.sp, color: Color.fromRGBO(148, 163, 182, 1)),
              )
            ],
          );
        });
      },
    );
// .then((value) => stepIndex.value = 0)
    bool? flag = await future.whenComplete(() {
      _scroller.dispose();
      _easyRefresh.dispose();
    }); // 参数初始化
    stepIndex.value = 0;

    if (flag != null && flag) return examId.value;
    if (flag == null) {
      if (positionIndex.value != 0) positionIndex.value = 0;
    }
    return null;
  }
}

@swidget
Widget $examsContainer(
    {required EasyRefreshController refreshController,
    required List<Widget> widgets,
    required Function(bool isRefresh) toGetDatacall}) {
  return EasyRefresh(
    firstRefresh: false,
    taskIndependence: true,
    enableControlFinishLoad: true,
    enableControlFinishRefresh: true,
    controller: refreshController,
    header: MaterialHeader(),
    footer: MaterialFooter(),
    onRefresh: () async => toGetDatacall(true),
    onLoad: () async => toGetDatacall(false),
    child: ListView(children: widgets),
  );
}

@swidget
Widget $itemContainer(bool isCurrent, String name, BuildContext context) {
  return Container(
    height: 44.h,
    decoration: BoxDecoration(
      color: isCurrent ? Color.fromRGBO(235, 239, 255, 1) : Color.fromRGBO(248, 249, 255, 1),
      borderRadius: BorderRadius.all(Radius.circular(6.sp)),
      border: isCurrent ? Border.all(color: Theme.of(context).primaryColor) : null,
    ),
    alignment: Alignment.centerLeft,
    padding: EdgeInsets.symmetric(vertical: 3.h, horizontal: 17.w),
    margin: EdgeInsets.only(bottom: 12.h),
    child: Row(
      children: [
        Expanded(
          child: quickText(name,
              size: 16.sp, color: isCurrent ? Theme.of(context).primaryColor : Color.fromRGBO(45, 56, 76, 1)),
        ),
        if (isCurrent) Icon(Icons.check_circle, color: Theme.of(context).primaryColor, size: 20.sp)
      ],
    ),
  );
}

@swidget
Widget $chooseBox(bool isRole, Widget bodyWidget) {
  return Column(
    children: [
      // Row(
      //   children: [
      //     Image.asset(
      //       isRole ? 'assets/images/role_selection.png' : 'assets/images/exam_selection.png',
      //       width: 29.w,
      //       height: 29.h,
      //     ),
      //     quickText(isRole ? '选择角色' : '选择考试', size: 18.sp, color: Color.fromRGBO(45, 56, 76, 1)),
      //   ],
      // ),
      SizedBox(height: 16.h),
      Expanded(child: bodyWidget),
    ],
  );
}

@swidget
Widget $confirmButton(temPositionIndex, temExamIndex, context, ontapCall) {
  return GestureDetector(
    onTap: () => easyThrottle('confirmRoleExamCall', () => ontapCall()),
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(height: 20.h),
        Container(
          width: double.infinity,
          height: 46.h,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(92.sp)),
            boxShadow: [
              BoxShadow(
                color: Color.fromRGBO(46, 91, 255, 0.50).withOpacity(0.2), // 阴影的颜色
                offset: Offset(4.w, 6.h), // 阴影与容器的距离
                blurRadius: 6.0, // 高斯的标准偏差与盒子的形状卷积。
                spreadRadius: 5, // 在应用模糊之前，框应该膨胀的量。
              ),
            ],
            gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [Color.fromRGBO(54, 86, 255, 0.99), Color.fromRGBO(93, 128, 255, 1)],
            ),
          ),
          alignment: Alignment.center,
          child: quickText('确 认', color: Colors.white, size: 18.sp, fontWeight: FontWeight.w400),
        )
      ],
    ),
  );
}

@swidget
Widget $nextStepButton(temPositionIndex, temExamIndex, context, ontapCall) {
  return GestureDetector(
    onTap: () => easyThrottle('nextRoleToExamCall', () => ontapCall()),
    child: Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(height: 20.h),
        Container(
          width: double.infinity,
          height: 46.h,
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(92.sp)),
            boxShadow: [
              BoxShadow(
                color: Color.fromRGBO(46, 91, 255, 0.50).withOpacity(0.2), // 阴影的颜色

                offset: Offset(4.w, 6.h), // 阴影与容器的距离
                blurRadius: 6.0, // 高斯的标准偏差与盒子的形状卷积。
                spreadRadius: 5, // 在应用模糊之前，框应该膨胀的量。
              ),
            ],
            gradient: LinearGradient(
              begin: Alignment.centerLeft,
              end: Alignment.centerRight,
              colors: [Color.fromRGBO(54, 86, 255, 0.99), Color.fromRGBO(93, 128, 255, 1)],
            ),
          ),
          alignment: Alignment.center,
          child: quickText('下一步', color: Colors.white, size: 18.sp, fontWeight: FontWeight.w400),
        )
      ],
    ),
  );
}

@swidget
Widget $easyStepper(int activeStep, Color finishedStepBackgroundColor, OnStepReached oncall) {
  return EasyStepper(
    alignment: Alignment.centerLeft,
    disableScroll: true,
    activeStep: activeStep,
    lineLength: 170,
    stepShape: StepShape.rRectangle,
    stepBorderRadius: 15,
    borderThickness: 2,
    internalPadding: 10,
    stepRadius: 28,
    // finishedStepBorderColor: Colors.deepOrange,
    // finishedStepTextColor: Colors.deepOrange,
    finishedStepBackgroundColor: finishedStepBackgroundColor,
    // activeStepIconColor: Colors.deepOrange,
    showLoadingAnimation: true,
    steps: [
      EasyStep(
        customStep: ClipRRect(
          borderRadius: BorderRadius.circular(15).r,
          child: Opacity(
            opacity: activeStep == 0 ? 1 : 0.3,
            child: Image.asset('assets/images/role_selection.png'),
          ),
        ),
        customTitle: const Text(
          '选择角色',
          textAlign: TextAlign.center,
        ),
      ),
      EasyStep(
        customStep: ClipRRect(
          borderRadius: BorderRadius.circular(15).r,
          child: Opacity(
            opacity: activeStep == 1 ? 1 : 0.3,
            child: Image.asset('assets/images/exam_selection.png', width: 80.w, height: 80.h),
          ),
        ),
        customTitle: const Text(
          '选择考试',
          textAlign: TextAlign.center,
        ),
      ),
    ],
    onStepReached: oncall,
  );
}
