import 'package:achievement_view/achievement_view.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:functional_widget_annotation/functional_widget_annotation.dart';
import 'package:marking_app/common/model/enum/KeyboardType.dart';
import 'package:marking_app/common/model/job/marking_text_question_job.dart';
import 'package:marking_app/common/model/marking/do_marking_keyboard_model.dart';
import 'package:marking_app/pages/homework_correction/hooks/use_preference.dart';
import 'package:marking_app/pages/homework_correction/hooks/use_screen.dart';
import 'package:marking_app/utils/my_text.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:syncfusion_flutter_sliders/sliders.dart';

import '../hooks/use_settings.dart';

part 'setPreference.g.dart';

/// 偏好设置主页
class SetPreference extends HookWidget {
  final MarkingTextQuestionJob textQuestion;
  final UsePreference usePreference;
  final UseScreen useScreen;
  final UseSettings useSettings;
  final int taskId;
  const SetPreference(
      {required this.textQuestion,
      required this.usePreference,
      required this.useScreen,
      required this.useSettings,
      required this.taskId,
      super.key});

  @override
  Widget build(BuildContext context) {
    UseTemPreference _useTemPrefce = UseTemPreference.use();

    useEffect(() {
      _useTemPrefce.init(usePreference.preferenceState.value);
      return () {};
    }, []);

    DoMarkingKeyboardModel tempPreference = _useTemPrefce.preferenceTemState.value; // 保存的偏好设置
    ScreenDirection orientation = tempPreference.screenDirection; // 当前方向
    bool isHorizontal = tempPreference.screenDirection == ScreenDirection.HORIZONTAL_SCREEN; // 是否是横向

    return Container(
      height: double.infinity,
      width: double.infinity,
      color: const Color.fromARGB(255, 233, 232, 232),
      child: Stack(
        children: [
          Container(
            color: const Color.fromRGBO(249, 250, 254, 1),
            alignment: Alignment.center,
            child: quickText(
              "学而有道",
              size: 170.sp,
              color: Color.fromRGBO(255, 255, 255, 0.65),
            ),
          ),
          Column(
            children: [
              $HeadBox(
                useTemPrefce: _useTemPrefce,
                useSettings: useSettings,
                usePreference: usePreference,
              ),
              Expanded(
                child: Container(
                  width: double.infinity,
                  // color: const Color.fromARGB(255, 233, 232, 232),
                  padding: EdgeInsets.only(top: 12.h, left: 10.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      $KeyboardBox(orientation: orientation, useTemPrefce: _useTemPrefce),
                      $AutoNextQuestBox(useTemPrefce: _useTemPrefce),
                      // $ScoreIntervalSetBox(
                      //   taskId: taskId,
                      //   questionNum: textQuestion.questionNum,
                      //   defaultNum: textQuestion.scoreInterval,
                      //   useTemPrefce: _useTemPrefce,
                      // ),
                      $SetScoringRulesBox(
                        tempPreference: tempPreference,
                        isHorizontal: isHorizontal,
                        call: (SortKeyboard e) {
                          _useTemPrefce.preferenceTemState.value.sort = e;
                          _useTemPrefce.preferenceTemState.value =
                              DoMarkingKeyboardModel.fromJson(_useTemPrefce.preferenceTemState.value.toJson());
                        },
                      ),
                    ],
                  ),
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}

// 获取键盘区域
@swidget
Widget $keyboardBox(
  BuildContext context, {
  required ScreenDirection orientation,
  required UseTemPreference useTemPrefce,
}) {
  bool isHorizontal = orientation == ScreenDirection.HORIZONTAL_SCREEN; // 是否是横向
  DoMarkingKeyboardModel tempPreference = useTemPrefce.preferenceTemState.value;
  KeyboardType keyboard = tempPreference.keyboard;
  int keyboardIndex = keyboard.index;

  List<TheDoMarkingKeyboardModel> keyboardTypes =
      KeyboardType.values.where((e) => e != KeyboardType.INPUT_TYPE).map((e) {
    bool isCurrent = keyboard == e; // 当前使用的键盘是不是当前这个键盘
    bool isInput = e == KeyboardType.INPUT_TYPE;

    DoMarkingKeyboardModel item = DoMarkingKeyboardModel(
      keyboard: e,
      open: isInput ? tempPreference.open : true, // 只有输入型键盘可以开启关闭
      guidePageDisplay: isInput ? tempPreference.guidePageDisplay : false, // 只有输入型键盘有引导页
    );

    if (isCurrent) {
      item.sort = tempPreference.sort;
      item.autoSubmitToNextQuestion = tempPreference.autoSubmitToNextQuestion;
    }
    return TheDoMarkingKeyboardModel(item, isCurrent);
  }).toList();

  selectKeyboardPreferences(TheDoMarkingKeyboardModel e, bool isInputAndHor) {
    if (keyboard == e.model.keyboard || isInputAndHor) return;
    tempPreference.keyboard = e.model.keyboard;
    DoMarkingKeyboardModel model = e.model;
    if (model.keyboard != KeyboardType.INPUT_TYPE) {
      // 不重置，若后面需要重置再打开
      // scoreInterval = model.getScoreStepSize(widget.markingUserId, widget.questionNum, widget.defaultScoreInterval);
      tempPreference.sort = model.sort;
    }
    useTemPrefce.preferenceTemState.value = DoMarkingKeyboardModel.fromJson(tempPreference.toJson());
  }

  return SizedBox(
    width: double.infinity,
    child: Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        quickText(
          '键盘选择',
          color: const Color.fromRGBO(45, 56, 76, 1),
          size: 14.sp,
          fontWeight: FontWeight.w500,
        ),
        Wrap(
          children: keyboardTypes.map((e) {
            TheDoMarkingKeyboardModel item = e;
            bool isInputAndHor = !isHorizontal && item.model.keyboard == KeyboardType.INPUT_TYPE; // 横屏和输入键盘
            return Padding(
              padding: EdgeInsets.only(right: 36.w, left: isHorizontal ? 0 : 5.w),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    width: 8.w,
                    margin: EdgeInsets.only(right: isHorizontal ? 3.w : 8.w),
                    child: Checkbox(
                      tristate: isInputAndHor, // 三态复选框，默认 false，当设置为 true 时，设置 value = null，复选框中间会变成破折号(-)
                      activeColor: Theme.of(context).primaryColor,
                      checkColor: Colors.white,
                      value: isInputAndHor ? null : keyboard == e.model.keyboard,
                      onChanged: (value) => selectKeyboardPreferences(e, isInputAndHor),
                    ),
                  ),
                  InkWell(
                    onTap: () => selectKeyboardPreferences(e, isInputAndHor),
                    child: quickText(
                      item.title,
                      color: const Color.fromRGBO(80, 87, 103, 1),
                      size: 14.sp,
                    ),
                  ),
                ],
              ),
            );
          }).toList(),
        ),
        SizedBox(height: 30.h),
      ],
    ),
  );
}

// 自动跳转下一题
@swidget
Widget $autoNextQuestBox(BuildContext context, {required UseTemPreference useTemPrefce}) {
  DoMarkingKeyboardModel preferenceTem = useTemPrefce.preferenceTemState.value;

  return Column(
    mainAxisSize: MainAxisSize.min,
    crossAxisAlignment: CrossAxisAlignment.start,
    children: [
      quickText(preferenceTem.keyboard == KeyboardType.INPUT_TYPE ? '自动跳转下一题' : '自动提交',
          size: 14.sp, color: const Color.fromRGBO(45, 56, 76, 1), fontWeight: FontWeight.bold),
      Transform.scale(
        scale: 0.7,
        alignment: Alignment.centerLeft,
        child: CupertinoSwitch(
          value: preferenceTem.autoSubmitToNextQuestion,
          activeColor: Theme.of(context).primaryColor,
          trackColor: const Color.fromRGBO(148, 163, 182, 1),
          onChanged: (value) {
            preferenceTem.autoSubmitToNextQuestion = value;
            useTemPrefce.preferenceTemState.value = DoMarkingKeyboardModel.fromJson(preferenceTem.toJson());
          },
        ),
      ),
    ],
  );
}

// 给分规则区域
@swidget
Widget $setScoringRulesBox(BuildContext context,
    {required bool isHorizontal,
    required DoMarkingKeyboardModel tempPreference,
    required Function(SortKeyboard) call}) {
  if (tempPreference.keyboard == KeyboardType.INPUT_TYPE) {
    return Container();
  }

  SortKeyboard? sortType = tempPreference.sort;
  return Container(
    margin: EdgeInsets.only(top: 30.h),
    child: Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        quickText(
          '设置常用给分',
          size: 14.sp,
          color: const Color.fromRGBO(45, 56, 76, 1),
          fontWeight: FontWeight.bold,
        ),
        Wrap(
          children: SortKeyboard.values.map((e) {
            String title;
            switch (e) {
              case SortKeyboard.INVERTED_ORDER:
                title = '按倒序排列';
                break;
              case SortKeyboard.FULL_AND_AERO_TOP:
                title = '顺序排列满分零分置顶';
                break;
              case SortKeyboard.FULL_AND_AERO_TOP_INVERTED_ORDER:
                title = '按倒序排列满分零分置顶';
                break;
            }
            return Padding(
              padding: EdgeInsets.only(right: 30.w),
              child: Row(
                mainAxisSize: MainAxisSize.min,
                children: [
                  Container(
                    width: 8.w,
                    margin: EdgeInsets.only(right: isHorizontal ? 3.w : 8.w, left: isHorizontal ? 0 : 5.w),
                    child: Checkbox(
                      activeColor: Theme.of(context).primaryColor,
                      checkColor: Colors.white,
                      value: e == sortType,
                      onChanged: (value) => call(e),
                    ),
                  ),
                  InkWell(
                    onTap: () => call(e),
                    child: quickText(
                      title,
                      color: const Color.fromRGBO(80, 87, 103, 1),
                      size: 14.sp,
                    ),
                  ),
                ],
              ),
            );
          }).toList(),
        ),
      ],
    ),
  );
}

// 分值间隔设置
@swidget
Widget $scoreIntervalSetBox(
  BuildContext context, {
  required UseTemPreference useTemPrefce,
  required int taskId,
  required String questionNum,
  required double defaultNum,
  double interval = 1,
  double min = 0.5,
  double? questTotalScore,
}) {
  DoMarkingKeyboardModel preferenceTem = useTemPrefce.preferenceTemState.value;

  double scoreInterval = preferenceTem.getScoreStepSize(taskId, questionNum, defaultNum);

  // preferenceTem
  KeyboardType keyboard = preferenceTem.keyboard;
  if (keyboard == KeyboardType.INPUT_TYPE) {
    return Container();
  }

  bool isHorizontal = preferenceTem.screenDirection == ScreenDirection.HORIZONTAL_SCREEN; // 是否是横向

  return Container(
    margin: EdgeInsets.only(top: 30.h),
    child: Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        InkWell(
          onTap: () {
            AchievementView(
              elevation: 0.5,
              duration: Duration(seconds: 1),
              title: "分值间隔",
              subTitle: "设定当前题目的分数按钮的间隔分值",
              color: Theme.of(context).primaryColor,
            ).show(context);
          },
          child: Stack(
            alignment: const FractionalOffset(1, 0),
            children: [
              quickText(
                '分值间隔设置    ',
                size: 14.sp,
                color: const Color.fromRGBO(45, 56, 76, 1),
                fontWeight: FontWeight.bold,
              ),
              Tooltip(
                message: '这是一个提示',
                child: Icon(Icons.help, color: Colors.black, size: 18.sp),
              ),
            ],
          ),
        ),
        SfSlider(
          onChanged: (value) {
            int flVal = value.floor();
            double differenceVal = value - flVal;
            if (differenceVal != 0) {
              value = differenceVal > 0.5 ? value.ceil().toDouble() : flVal + 0.5;
            }
            if (questTotalScore != null && value > questTotalScore) {
              value = questTotalScore;
              AchievementView(
                      elevation: 0.5,
                      duration: Duration(seconds: 1),
                      icon: Icon(
                        Icons.warning_amber,
                        color: Colors.yellow,
                        size: 40.sp,
                      ),
                      title: "提示",
                      subTitle: "设定分值间隔不得大于当前分试题总分",
                      textStyleTitle: TextStyle(color: Colors.yellow),
                      color: Theme.of(context).primaryColor)
                  .show(context);
            }
            // toUpState(setState, () => scoreInterval = value, mounted);
          },
          showTicks: true,
          showLabels: true,
          enableTooltip: true,
          //值
          value: scoreInterval,
          //滑块划过的颜色
          activeColor: Theme.of(context).primaryColor,
          //滑块未划过的颜色
          inactiveColor: Colors.grey[400],
          min: min,
          max: questTotalScore ?? 5,
          interval: interval,
        ),
      ],
    ),
  );
}

// 顶部区域
@swidget
Widget $headBox(
  BuildContext context, {
  required UseTemPreference useTemPrefce,
  required UsePreference usePreference,
  required UseSettings useSettings,
}) {
  return Container(
    height: 46.h,
    color: const Color.fromRGBO(255, 255, 255, 1),
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        SizedBox(width: 4.w),
        InkWell(
          onTap: () => useSettings.switchPreference(false),
          child: Padding(
            padding: EdgeInsets.symmetric(horizontal: 4.w),
            child: Icon(Icons.arrow_back_ios, size: 24.sp),
          ),
        ),
        SizedBox(width: 4.w),
        quickText('作业批改操作设置', size: 17.sp),
        Expanded(
          child: Container(
            padding: EdgeInsets.only(right: 12.w),
            alignment: Alignment.centerRight,
            child: InkWell(
              onTap: () async {
                await usePreference.savePreference(tempModel: useTemPrefce.preferenceTemState.value);
                useSettings.switchPreference(false);
              },
              child: quickText('保存', size: 18.sp, color: Theme.of(context).primaryColor),
            ),
          ),
        )
      ],
    ),
  );
}

class TheDoMarkingKeyboardModel {
  final DoMarkingKeyboardModel model;
  bool current;
  late String title;

  TheDoMarkingKeyboardModel(this.model, this.current) {
    switch (model.keyboard) {
      case KeyboardType.INPUT_TYPE:
        title = '输入型键盘';
        break;
      case KeyboardType.RIGHT_SELECTION:
        title = '右侧选择型键盘';
        break;
      case KeyboardType.BOTTOM_SELECTION:
        title = '底部选择型键盘';
        break;
    }
  }
}
