// 使用缩放图片hooks
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:marking_app/common/model/marking/marking_zoom.dart';
import 'package:marking_app/utils/fast_data.dart';

class UseZoomImageHistory {
  String theQuestionNumber;

  ValueNotifier<double> initScale;
  ValueNotifier<Offset> initPosition;

  double? scale;
  Offset? position;

  UseZoomImageHistory._({required this.theQuestionNumber, required this.initScale, required this.initPosition});

  // 工厂构造函数
  factory UseZoomImageHistory.use(String questionNumber) {
    return UseZoomImageHistory._(
      theQuestionNumber: questionNumber,
      initScale: useState(1),
      initPosition: useState(Offset(0, 0)),
    );
  }

  void onPositionUpdate(Offset offset) {
    print('位置：$offset ；scale: ${initScale.value}');
    if (offset.dx == 0 && offset.dy == 0) return;

    double dx = offset.dx;
    double dy = 0;
    position = Offset(dx, dy);
    initPosition.value = position!;
    MarkingZoom theSetVal = MarkingZoom(dx: dx, dy: 0, questionNumber: theQuestionNumber, scale: initScale.value);
    print('onPositionUpdate :${theSetVal.toJson()}');
    FastData.getInstance().setMarkingPapersImageZoom(theSetVal);
  }

  void onScaleUpdate(double theScale, double zoom) {
    print('缩放比例：$theScale; 缩放级别：$zoom');
    scale = zoom;
    initScale.value = zoom;
    MarkingZoom theSetVal = MarkingZoom(
      dx: position?.dx ?? initPosition.value.dx,
      // dy: position?.dy ?? initPosition.value.dy,
      dy: 0,
      questionNumber: theQuestionNumber,
      scale: zoom,
    );
    print('onScaleUpdate :${theSetVal.toJson()}');
    FastData.getInstance().setMarkingPapersImageZoom(theSetVal);
  }

  // 初始化历史信息
  void initInfo([String? questionNumber]) async {
    MarkingZoom? zoomInfo = await FastData.getInstance().getMarkingPapersImageZoom();
    if (zoomInfo != null) {
      if (zoomInfo.questionNumber == (questionNumber ?? theQuestionNumber)) {
        // 有对应的试题

        if (questionNumber != null) {
          theQuestionNumber = questionNumber; // 赋值questionNumber
        }

        initScale.value = zoomInfo.scale;
        initPosition.value = Offset(zoomInfo.dx, zoomInfo.dy);
        print('执行了位置初始化............${initScale.value}  --  ${initPosition.value}');
        scale = zoomInfo.scale;
        position = initPosition.value;
        return;
      }
      FastData.getInstance().cleanMarkingPapersImageZoom(); // 不是对应的试题就清空历史题型数据
    }
  }
}
