import 'dart:convert';
import 'dart:ui';

import 'package:fis_measure/interfaces/date_types/point.dart';
import 'package:fis_measure/process/primitives/detection.dart';
import 'package:fis_measure/utils/js_utils.dart'
    if (dart.library.io) 'package:fis_measure/utils/js_utils4native.dart'
    if (dart.library.html) 'package:fis_measure/utils/js_utils.dart';
import 'package:fis_measure/utils/prompt_box.dart';

import 'calculator.dart';

class CarotidDetectionCal extends Calculator<CarotidDetection, double> {
  CarotidDetectionCal(CarotidDetection ref, this.type) : super(ref);
  String type = '';
  @override
  void calculate() {
    if (ref.feature == null) return;
    //图片尺寸
    final imageSize = ref.application.carotid2DSize;
    //画布尺寸
    final canavsSize = ref.application.displaySize;
    //图像缩放比
    final imageScale = ref.application.displayScaleRatio;
    //标准画布尺寸
    final stdCanavsSize =
        Size(canavsSize.width / imageScale, canavsSize.height / imageScale);
    //Vid图像左上顶点的像素坐标
    final imageLeftTopPoint = DPoint(
        (stdCanavsSize.width - imageSize.width) / 2,
        (stdCanavsSize.height - imageSize.height) / 2);

    String measureItemType = 'PlaqueDectectionMeasureItem';
    if (type == 'Plaque Detection') {
      measureItemType = 'PlaqueDectectionMeasureItem';
    } else if (type == 'Intima Detection') {
      measureItemType = 'IntimaDetectionMeasureItem';
    }
    final params = "{'MeasureItemType':'$measureItemType'}";

    String description = "\n Waiting $type";
    updateStringValue(description);
    List<Offset> getPointsFromStrList(List pointsStr) {
      final points = <Offset>[];
      for (var point in pointsStr) {
        final xyStr = point.split(',');
        points.add(Offset((double.parse(xyStr[0]) + imageLeftTopPoint.x),
            (double.parse(xyStr[1]) + imageLeftTopPoint.y)));
      }
      return points;
    }

    /// [Carotid] ✅在此处通知 Shell 计算,获取 description,直接绘制结果
    try {
      callShellMethod('getMeasureResult', [params]).callMethod(
        'then',
        [
          (result) {
            if (result == 'error') {
              // description = "$type.detect Failed";
              PromptBox.toast("$type.detect Failed");
              // updateStringValue(description);
              // ref.application.updateRenderReady.emit(this, null);
              return;
            }
            final feature = ref.feature!;
            final res = jsonDecode(result);
            // print('getMeasureResult res: $res');
            if (res.length > 0) {
              if (type == 'Plaque Detection') {
                description =
                    "\n Area: ${res[0]['PlaqueArea'].toStringAsFixed(2)}mm²";
                feature.offsetsList
                    .add(getPointsFromStrList(res[0]['PlaqueEdgePoints']));
              } else {
                description = "";
                if (res['UpperIntimaResult']['ErrorCode'].toString() ==
                    "1000") {
                  description +=
                      "\n Ant.Max: ${res['UpperIntimaResult']['MaxThickness'].toStringAsFixed(2)}mm\n Ant.Min: ${res['UpperIntimaResult']['MinThickness'].toStringAsFixed(2)}mm\n Ant.Avg: ${res['UpperIntimaResult']['AverageThickness'].toStringAsFixed(2)}mm\n Ant.SD: ${res['UpperIntimaResult']['SdThickness'].toStringAsFixed(2)}mm";
                  feature.offsetsList.add(getPointsFromStrList(
                      res['UpperIntimaResult']['PointLower']));
                  feature.offsetsList.add(getPointsFromStrList(
                      res['UpperIntimaResult']['PointUpper']));
                } else {
                  description += "\n Ant.detect Failed";
                }
                if (res['LowerIntimaResult']['ErrorCode'].toString() ==
                    "1000") {
                  description +=
                      "\n Post.Max: ${res['LowerIntimaResult']['MaxThickness'].toStringAsFixed(2)}mm\n Post.Min: ${res['LowerIntimaResult']['MinThickness'].toStringAsFixed(2)}mm\n Post.Avg: ${res['LowerIntimaResult']['AverageThickness'].toStringAsFixed(2)}mm\n Post.SD: ${res['LowerIntimaResult']['SdThickness'].toStringAsFixed(2)}mm";
                  feature.offsetsList.add(getPointsFromStrList(
                      res['LowerIntimaResult']['PointLower']));
                  feature.offsetsList.add(getPointsFromStrList(
                      res['LowerIntimaResult']['PointUpper']));
                } else {
                  description += "\n Post.detect Failed";
                }
              }
            } else {
              description = "$type.detect Failed";
              PromptBox.toast("$type.detect Failed");
            }
            updateStringValue(description);

            /// [Carotid] ✅在此处通知canvas 重绘结果
            ref.application.updateRenderReady.emit(this, null);
          },
        ],
      );
    } catch (e) {
      updateStringValue("$type.detect Failed");
      PromptBox.toast("$type.detect Failed");

      //
    }
  }
}