import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.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/common/upload_img_secret_key.dart';
import 'package:marking_app/common/model/enum/KeyboardType.dart';
import 'package:marking_app/common/model/event_bus/job_currenttab_finish_addtion.dart';
import 'package:marking_app/common/model/event_bus/job_submit_bus.dart';
import 'package:marking_app/common/model/event_bus/job_question_switch_bus.dart';
import 'package:marking_app/common/model/job/marking_text_question_job.dart';
import 'package:marking_app/common/model/job/marking_text_question_job_params.dart';
import 'package:marking_app/common/model/marking/do_marking_keyboard_model.dart';
import 'package:marking_app/components/PictureOverview.dart';
import 'package:marking_app/pages/common/event_bus_mixin.dart';
import 'package:marking_app/pages/homework_correction/components/jobPictureOverview.dart';
import 'package:marking_app/utils/index.dart';
import 'package:marking_app/utils/request/rest_client.dart';

class UseKeyboard
    with
        CommonMixin,
        EventBusMixin<JobQuestionSwitchBus>,
        EventBusMixinSub<JobSubmitBus>,
        EventBusMixinSubLast<JobCurrenttabFinishAddtion> {
  ValueNotifier<num?> tensVal; // 当前选中十位分值
  ValueNotifier<String?> smallScoreVal; // 当前选中个位分值
  num? score;

  ValueNotifier<List<int>> tensList; // 十位数分值 ==> 集合
  ValueNotifier<List<double>> singleDigitList; // 打开辅助键盘的个位数集合 ==》 个位数分值集合
  ValueNotifier<List<double>> combineList; // 关闭辅助键盘后的小键盘 ==》 混合十位和个位数分值集合
  DoMarkingKeyboardModel preferenceModel;

  UseKeyboard._({
    required this.tensVal,
    required this.smallScoreVal,
    required this.tensList,
    required this.singleDigitList,
    required this.combineList,
    required this.preferenceModel,
  });

  // 工厂构造函数
  factory UseKeyboard.use(DoMarkingKeyboardModel preferenceModel) {
    final tens = useState<List<int>>([]);
    final singleDigit = useState<List<double>>([]);
    final combine = useState<List<double>>([]);
    final _tensVal = useState<num?>(null);
    final _smallScoreVal = useState<String?>(null);

    return UseKeyboard._(
      tensVal: _tensVal,
      smallScoreVal: _smallScoreVal,
      tensList: tens,
      singleDigitList: singleDigit,
      combineList: combine,
      preferenceModel: preferenceModel,
    );
  }

  init({required SortKeyboard sort, required MarkingTextQuestionJob job, double? localScoreInterval}) {
    initKeyboardSuper(
        sort: sort,
        // totalScore: job.totalScore,
        // scoreInterval: job.scoreInterval,
        totalScore: 1,
        scoreInterval: 1,
        localScoreInterval: localScoreInterval);
  }

  /// 键盘计算数据
  /// @params totalScore 当前试题总分
  /// @params scoreInterval 当前试题系统默认指定步长
  /// @params localScoreInterval 本地设置分值步长
  /// @params sort 键盘排序方式
  void initKeyboardSuper({
    required double totalScore,
    required SortKeyboard sort,
    double scoreInterval = 1,
    double? localScoreInterval,
  }) {
    if (localScoreInterval != null && localScoreInterval != 0 && localScoreInterval != scoreInterval) {
      scoreInterval = localScoreInterval;
    }

    /// 没有子题
    // double totalScore = widget.hasSubtopic
    //     ? widget.data.subQuestionDetailList[widget.subtopicIndex].subQuestionScore
    //     : widget.totalScore;

    if (scoreInterval == 0) scoreInterval = 1;
    initKeyboard(totalScore, scoreInterval, sort);
  }

  /// 初始化键盘
  /// @params {double} totalScore 总分
  /// @params {double} scoreInterval 小分步长
  void initKeyboard(double totalScore, double scoreInterval, SortKeyboard sort) {
    /** ---  十位计算  --- */
    List<int> tens = [];
    int floorScore = totalScore.floor(); // 总分向下取整
    int singleDigit = floorScore; // 个位小数
    int numsLength = singleDigit;
    if (floorScore > 10) {
      singleDigit = 9;
      for (var i = 10; i < floorScore; i += 10) {
        tens.add(i);
      }
    }

    /** ---  混合集合  --- */
    numsLength = ((numsLength - (numsLength % scoreInterval)) / scoreInterval).floor();
    List<double> subNums = List.generate(numsLength + 1, (e) => e * scoreInterval); // +1 添加满分 小分键盘
    if (numsLength * scoreInterval < totalScore) subNums.add(totalScore); // 加一个总分

    /** ---  个位集合  --- */

    List<double> nums = (jsonDecode(jsonEncode(subNums)) as List<dynamic>).cast<double>(); // 辅助键盘的小分键盘
    if (sort != SortKeyboard.FULL_AND_AERO_TOP) {
      if (totalScore > 19) {
        nums = nums.reversed.toList();
      } else {
        nums = nums.reversed.where((e) => e <= 10).toList();
      }
      subNums = subNums.reversed.toList();
    }

    tensList.value = tens;
    singleDigitList.value = nums;
    combineList.value = subNums;

    // // 计算关闭辅助键盘后的小键盘
    // if (floorScore > 10) {
    //   int a = scoreInterval == 0.5 ? floorScore * 2 : floorScore;
    //   subNums = List.generate(a+1, (e) => e * scoreInterval); // 小分键盘
    // }
  }

  /// 批阅
  Future<num?> readOver({
    required GlobalKey<JobPictureOverviewState> scaffoldKeyPictureOverview,
    required BuildContext context,
    required num fraction,
    required MarkingTextQuestionJob job,
    bool isTens = false,
    bool automatic = true,
  }) async {
    EasyLoading.show(status: 'loading...');

    try {
      // double totalScore = job.totalScore;
      double totalScore = 1;
      bool fullMarks = totalScore == fraction;
      // 十位
      if (isTens) {
        bool cleanScore = tensVal.value == fraction;
        if (!cleanScore) {
          tensVal.value = fraction;
        } else {
          tensVal.value = null;
          smallScoreVal.value = null;
        }
        score = tensVal.value;
        return score;
      }

      num? oldTensVal = tensVal.value;
      String? oldSmallscoreVal = smallScoreVal.value;

      double theScore = fraction.toDouble();
      if (fullMarks) {
        // 满分
        tensVal.value = null;
        smallScoreVal.value = null;
      } else if (tensVal.value != null) {
        // 有十位数
        theScore = (tensVal.value! + fraction).toDouble();
      }

      if (theScore > totalScore) {
        return ToastUtils.showError('评分已大于总分，请重新评分');
      }

      if (preferenceModel.autoSubmitToNextQuestion) {
        bool submitFlag = await toSubmitMarking(
          scaffoldKeyPictureOverview,
          context,
          // TODO 数据控制  commentImageUrl
          MarkingTextQuestionJobParams(
            score: theScore,
            taskSubjectiveDetailId: 1,
            // taskSubjectiveDetailId: job.taskSubjectiveDetailId,
            // commentImageUrl: job.commentImageUrl,
          ),
        );
        if (!submitFlag) {
          // 提交失败 恢复旧数据
          tensVal.value = oldTensVal;
          smallScoreVal.value = oldSmallscoreVal;
          return oldTensVal ?? (oldSmallscoreVal != null ? num.parse(oldSmallscoreVal) : null);
        }

        // 提交成功需要跳转下一题
        Future.delayed(Duration.zero, () => eventFire(model: JobQuestionSwitchBus()));
      }

      smallScoreVal.value = fraction.toString();
      score = theScore;
      return score;
    } catch (e) {
      toPrint(val: e.toString());
    } finally {
      EasyLoading.dismiss();
    }
    return null;
  }

  Future<bool> toSubmitMarking(GlobalKey<JobPictureOverviewState> scaffoldKeyPictureOverview, BuildContext context,
      MarkingTextQuestionJobParams param,
      {bool loading = false}) async {
    if (loading) EasyLoading.show(status: 'loading...');
    try {
      RestClient client = await getClient();

      // final pictureOverviewState = Provider.of<PictureOverviewState>(context);

      // final secondView = Get.find<PictureOverviewState>();

      // 上传批注图片
      // FileResult? res = await pictureOverviewKey.currentState?.saveImage();
      FileResult? res = await scaffoldKeyPictureOverview.currentState?.saveImage();
      if (res != null && res.url != null) param.commentImageUrl = res.url;
      // TODO
      // BaseStructureResult result = await client.toSubmitMarking(param);
      // if (!result.success) {
      //   return ToastUtils.showError('提交失败，请重新打分');
      // }
      // eventFireSubLast(model: JobCurrenttabFinishAddtion()); // 当前试题提交后 增加当前tab已经批阅完成数量
      // // ToastUtils.showSuccess('得分：' + getDoubleRemoveZero(param.score), duration: Duration(milliseconds: 500));
      // Fluttertoast.showToast(
      //   msg: '得分${getDoubleRemoveZero(param.score)}',
      //   toastLength: Toast.LENGTH_SHORT,
      //   gravity: ToastGravity.BOTTOM,
      //   fontSize: 16.sp,
      // );
      // return result.success;
    } catch (e) {
      print(e);
    } finally {
      if (loading) EasyLoading.dismiss();
    }
    return false;
  }

  // initBus(BuildContext context) {
  //   eventOnSub(callback: (JobSubmitBus _model) async {
  //     if (score == null) return;
  //     bool success = await toSubmitMarking(
  //       scaffoldKeyPictureOverview,
  //       context,
  //       MarkingTextQuestionJobParams(
  //         score: score!.toDouble(),
  //         taskSubjectiveDetailId: _model.taskSubjectiveDetailId,
  //       ),
  //       loading: true,
  //     );
  //     if (success) {
  //       // 提交成功需要跳转下一题
  //       Future.delayed(Duration.zero, () => eventFire(model: JobQuestionSwitchBus()));
  //     }
  //   });
  // }

  disBus() {
    eventCancel();
    eventCancelSub();
    eventCancelSubLast();
  }
}
