import 'dart:math';
import 'package:flutter/material.dart';

class SectorShape {
  Offset center; // 中心点
  double innerRadius; // 小圆半径
  double outRadius; // 大圆半径
  double startAngleRad; // 起始弧度
  double sweepAngleRad; // 扫描弧度

  SectorShape({
    required this.center,
    required this.innerRadius,
    required this.outRadius,
    required this.startAngleRad,
    required this.sweepAngleRad,
  });

  void draw(Canvas canvas, Paint paint, Rect? boundry) {
    Path path = formPath();
    if (boundry != null) {
      Path boundryPath = Path()..addRect(boundry);
      path = Path.combine(PathOperation.intersect, path, boundryPath);
    }
    canvas.drawPath(path, paint);
  }

  Path formPath() {
    double startRad = startAngleRad;
    double endRad = startAngleRad + sweepAngleRad;

    double r0 = innerRadius;
    double r1 = outRadius;
    Offset p0 = Offset(cos(startRad) * r0, sin(startRad) * r0);
    Offset p1 = Offset(cos(startRad) * r1, sin(startRad) * r1);
    Offset q0 = Offset(cos(endRad) * r0, sin(endRad) * r0);
    Offset q1 = Offset(cos(endRad) * r1, sin(endRad) * r1);

    bool large = sweepAngleRad.abs() > pi;
    bool clockwise = sweepAngleRad > 0;

    Path path = Path()
      ..moveTo(p0.dx, p0.dy)
      ..lineTo(p1.dx, p1.dy)
      ..arcToPoint(q1,
          radius: Radius.circular(r1), clockwise: clockwise, largeArc: large)
      ..lineTo(q0.dx, q0.dy)
      ..arcToPoint(p0,
          radius: Radius.circular(r0), clockwise: !clockwise, largeArc: large);
    // 闭合路径
    path.close();
    return path.shift(center);
  }

  // 计算外接矩形的方法
  Rect boundingBox() {
    double startRad = startAngleRad;
    double endRad = startAngleRad + sweepAngleRad;
    // print('startRad: $startRad, endRad: $endRad');
    bool crossZero =
        pi / 2 < max(startRad, endRad) && pi / 2 > min(startRad, endRad);
    // print('crossZero: $crossZero');
    double maxRadius = max(innerRadius, outRadius);
    List<Offset> points = [
      Offset(cos(startRad) * innerRadius, sin(startRad) * innerRadius),
      Offset(cos(startRad) * outRadius, sin(startRad) * outRadius),
      Offset(cos(endRad) * innerRadius, sin(endRad) * innerRadius),
      Offset(cos(endRad) * outRadius, sin(endRad) * outRadius),
      if (crossZero) Offset(0, maxRadius),
    ];

    double minX = double.infinity;
    double minY = double.infinity;
    double maxX = double.negativeInfinity;
    double maxY = double.negativeInfinity;

    for (var point in points) {
      Offset shiftedPoint = point + center;
      if (shiftedPoint.dx < minX) minX = shiftedPoint.dx;
      if (shiftedPoint.dy < minY) minY = shiftedPoint.dy;
      if (shiftedPoint.dx > maxX) maxX = shiftedPoint.dx;
      if (shiftedPoint.dy > maxY) maxY = shiftedPoint.dy;
    }

    return Rect.fromLTRB(minX, minY, maxX, maxY);
  }

  // 绘制外接矩形的方法
  void drawBoundingBox(Canvas canvas, Paint paint) {
    Rect rect = boundingBox();
    canvas.drawRect(rect, paint);
  }
}
