// 逻辑文件
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:making_school_asignment_app/common/config/request_config.dart';
import 'package:making_school_asignment_app/common/job/marking_models/do_test_questions_image_info.dart';
import 'package:making_school_asignment_app/common/job/marking_models/original_manuscript_handwriting_params.dart';
import 'package:making_school_asignment_app/common/mixins/request_tool_mixin.dart';
import 'package:making_school_asignment_app/common/utils/toast_utils.dart';
import 'package:making_school_asignment_app/page/home_page/children/homework_review/components/job_handwriting.dart';
import 'package:making_school_asignment_app/page/home_page/children/homework_review/components/original_manuscript_handwriting/configuration_files/states.dart';

class HandwritingLogic extends GetxController with RequestToolMixin {
  Rx<JobHandwriting?> resultData = Rx<JobHandwriting?>(null); // 笔迹数据
  Rx<HandwritingInfo?> handwritingInfo = Rx<HandwritingInfo?>(null); // 笔迹数据
  Rx<List<List<GestureHandwritingRecording>>> packagedHandwritingDatas = Rx<List<List<GestureHandwritingRecording>>>([]);
  Rx<List<GestureHandwritingRecording>> packagedHandwritingDataAll = Rx<List<GestureHandwritingRecording>>([]); // 总数据
  Rx<OriginalManuscriptHandwritingParams?> params = Rx<OriginalManuscriptHandwritingParams?>(null); // 参数
  Rx<TestQuestionsImageInfo?> imagInfoModel = Rx<TestQuestionsImageInfo?>(null); // 图片加载后的数据

  late ToolbarControl toolbar;

  final Function backCall;
  HandwritingLogic(this.backCall);

  @override
  void onInit() {
    toolbar = ToolbarControl(
      showManuscript: Rx<bool>(false), // 查看原卷
      initialization: Rx<bool>(false), // 初始化完成
      executionData: Rx<List<GestureHandwritingRecording>>([]), // 执行数据
    );
    ever(params, (callback) => getData());
    ever(imagInfoModel, (callback) {
      // 图像数据初始化后 计算笔迹数据
      toolbar.initialization.value = false;
      handwritingInfo.value = getHandwritingDetail(resultData.value);
      getCalculatedSize();
    });
    super.onInit();
  }

  Future<void> getData() async {
    if (params.value == null) return;
    var dio = getClientDio();
    try {
      ToastUtils.showLoading();
      toolbar.initialization.value = false;
      imagInfoModel.value = null;
      // 设置时长

      dio.options.receiveTimeout = const Duration(seconds: 20);
      var res = await getClient().getOriginalManuscriptHandwriting(params.value!);
      resultData.value = res;
    } catch (e) {
      ToastUtils.showError('获取笔迹数据报错，请重试');
      backCall();
    } finally {
      dio.options.receiveTimeout = const Duration(milliseconds: RequestConfig.receiveTimeout); // 还原接收数据时长
      ToastUtils.dismiss();
    }
  }

  // 计算尺寸
  Future<void> getCalculatedSize() async {
    if (imagInfoModel.value == null || handwritingInfo.value == null) return;
    Map<int, List<Lattices>> mapData = handwritingInfo.value!.strokeMap;
    double scaleRatio = imagInfoModel.value!.scaleRatio;
    if (mapData.isNotEmpty) {
      List<int> keys = mapData.keys.toList();
      print('重新计算：${scaleRatio}');
      List<List<GestureHandwritingRecording>> _packagedHandwritingDatas = [];
      List<GestureHandwritingRecording> _packagedHandwritingDataAll = [];
      for (var i = 0; i < keys.length; i++) {
        List<GestureHandwritingRecording> newTrajectoryData = mapData[keys[i]]!.map((e) {
          // double theX = e.x;
          // double theY = e.y;
          // if (!e.initialization) {
          //   // 未初始化基准
          //   e.toInitialization(scaleRatio);
          //   theX = e.x;
          //   theY = e.y;
          // }
          return GestureHandwritingRecording(
            stroke: e.stroke,
            data: Offset(e.x * scaleRatio, e.y * scaleRatio),
            // data: Offset(theX, theY),
            usageTime: e.time.toInt(),
            intervalTime: e.intervalTime,
          );
        }).toList();

        newTrajectoryData.sort((a, b) => a.usageTime.compareTo(b.usageTime));
        _packagedHandwritingDatas.add(newTrajectoryData);
        _packagedHandwritingDataAll.addAll(newTrajectoryData);
      }
      packagedHandwritingDatas.value = _packagedHandwritingDatas; // 分组数据
      packagedHandwritingDataAll.value = _packagedHandwritingDataAll; // 不分组数据
      toolbar.showManuscript.value = true; // 默认原稿展示
      toolbar.initialization.value = true; // 数据初始化完成

      // Future.delayed(Duration.zero, () => eventFire(model: JobHandwritingGetReadyBus())); // 通知外部可以播放笔迹
    }
  }

  // 数据笔画处理计算
  HandwritingInfo? getHandwritingDetail(JobHandwriting? theData) {
    if (theData == null) return null;
    // 笔画分组
    // var lattices = Map<int, List<Lattices>>.fromIterable(
    //   theData.lattices,
    //   key: (key) => key.stroke,
    //   value: (value) {
    //     // return theData.lattices.where((item) => item.stroke == value.stroke).toList()..sort((a, b) => a.time.compareTo(b.time));
    //     return theData.lattices.where((item) => item.stroke == value.stroke).toList();
    //   },
    // );
    var lattices = <int, List<Lattices>>{};
    var theLattices = theData.lattices;
    for (var i = 0; i < theLattices.length; i++) {
      Lattices item = theLattices[i];
      if (!lattices.containsKey(item.stroke)) lattices[item.stroke] = [];
      lattices[item.stroke]!.add(item); // 添加笔画数据
    }

    List<int> latticeKeys = lattices.keys.toList(); // 笔画集合
    int timeConsuming = 0;
    if (latticeKeys.isNotEmpty) {
      // 计算总时长
      List<Lattices>? firstAction = lattices[latticeKeys[0]];
      List<Lattices>? lastAction = lattices[latticeKeys[latticeKeys.length - 1]];
      int firstTime = 0;
      int lastTime = 0;

      if (firstAction?.isNotEmpty ?? false) {
        // 第一个笔画集合
        firstTime = firstAction![0].time;
      }
      if (lastAction?.isNotEmpty ?? false) {
        // 最后一笔画集合
        lastTime = lastAction![0].time;
      }
      timeConsuming = lastTime - firstTime;
    }
    var pauseCount = 0; // 停顿次数
    List<PauseIntervalTime> pauseInterval = [];
    for (var i = 0; i < latticeKeys.length; i++) {
      var currentLattices = lattices[latticeKeys[i]]!; // 当前循环笔画集合
      var prevLattices = i == 0 ? null : lattices[latticeKeys[i - 1]]!; // 下一个笔画集合
      for (var j = 0; j < currentLattices.length; j++) {
        var intervalTime = 0;
        var lattice = currentLattices[j];

        if (j != 0) {
          var prevItem = currentLattices[j - 1];
          var adjacentSpacingTime = lattice.time - prevItem.time;
          intervalTime = adjacentSpacingTime + prevItem.intervalTime;
          if (adjacentSpacingTime > 5000) {
            // 大于5秒算一次停顿
            pauseCount++;
            pauseInterval.add(PauseIntervalTime(startTime: prevItem.intervalTime, endTime: intervalTime));
          }
        } else {
          if (i != 0 && prevLattices != null) {
            var prevLatticeLastItem = prevLattices[prevLattices.length - 1];
            var adjacentSpacingTime = lattice.time - prevLatticeLastItem.time;
            intervalTime = adjacentSpacingTime + prevLatticeLastItem.intervalTime;
            if (adjacentSpacingTime > 5000) {
              // 大于5秒算一次停顿
              pauseCount++;
              pauseInterval.add(PauseIntervalTime(startTime: prevLatticeLastItem.intervalTime, endTime: intervalTime));
            }
          }
        }
        lattice.intervalTime = intervalTime;
      }
    }
    return HandwritingInfo(pauseCount, timeConsuming, lattices, pauseInterval);
  }
}
