import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_hooks/flutter_hooks.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:functional_widget_annotation/functional_widget_annotation.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:marking_app/common/model/job/gesture_recording.dart';
import 'package:marking_app/pages/common/event_bus_mixin.dart';
import 'package:marking_app/pages/homework_correction/eventBus/do_papers_job_custom_paint_size_bus.dart';
import 'package:marking_app/pages/homework_correction/hooks/use_cached_img_refresh.dart';
import 'package:marking_app/pages/homework_correction/providers/drawing_provider.dart';
import 'package:marking_app/utils/my_text.dart';

part 'theExamPaperDrawing.g.dart';

class TheExamPaperDrawing extends ConsumerWidget {
  final double boxHeight;
  final double boxWidth;
  final bool openEraser;
  final String imageUrl;
  final String? commentImageUrl;
  final bool showAnnotations;
  TheExamPaperDrawing(
      {required this.imageUrl,
      required this.commentImageUrl,
      required this.showAnnotations,
      required this.boxHeight,
      required this.boxWidth,
      required this.openEraser,
      super.key});

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    var points = ref.watch(jobHomeWorkProvider);
    if (showAnnotations && points.isNotEmpty) {
      return CustomPaint(
        foregroundPainter: DrawingPainter(points: points, isErasing: openEraser),
        child: RepaintBoundary(
          child: Container(
            color: Colors.transparent,
            alignment: Alignment.center,
            constraints: BoxConstraints(minWidth: boxWidth),
            child: $TheCachedNetworkImage(
              (context, imageProvider) => Image(image: imageProvider, fit: BoxFit.fitWidth),
              imageUrl: commentImageUrl!,
            ),
          ),
        ),
      );
    }
    return CustomPaint(
      painter: DrawingPainter(points: points, isErasing: openEraser),
      // child: CustomPaintChildSize(boxWidth: boxWidth),
      child: Container(
        color: Colors.transparent,
        constraints: BoxConstraints(minWidth: boxWidth),
        child: CustomPaintChildSize(boxWidth: boxWidth),
      ),
    );
  }
}

class CustomPaintChildSize extends StatefulWidget {
  final double boxWidth;
  const CustomPaintChildSize({required this.boxWidth, super.key});

  @override
  State<CustomPaintChildSize> createState() => _CustomPaintChildSizeState();
}

class _CustomPaintChildSizeState extends State<CustomPaintChildSize> with EventBusMixin<DoPapersJobCustomPaintSizeBus> {
  double? theHeight;

  @override
  void initState() {
    super.initState();
    eventOn(callback: (DoPapersJobCustomPaintSizeBus val) {
      theHeight = val.theHeight;
      setState(() {});
    });
  }

  @override
  void dispose() {
    super.dispose();
    eventCancel();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.transparent,
      height: theHeight,
      width: widget.boxWidth,
    );
  }
}

class DrawingPainter extends CustomPainter {
  final List<GestureRecording> points;
  final bool isErasing;
  final bool openErasing;

  DrawingPainter({required this.points, required this.isErasing})
      : openErasing = points.isNotEmpty && isErasing,
        super();

  Paint paintBrush = Paint()
    ..color = Colors.red
    ..strokeCap = StrokeCap.round
    ..strokeWidth = 0.6.sp;

  // Paint eraser = Paint()
  //   ..blendMode = BlendMode.clear
  //   ..color = Colors.transparent
  //   ..style = PaintingStyle.stroke
  //   ..strokeCap = StrokeCap.round
  //   ..strokeWidth = 100;

  // final emptyPaint = Paint();
  // final emptyPaintWithWidth = Paint()..strokeWidth = 60.0;

  @override
  void paint(Canvas canvas, Size size) {
    /**
    if (points.isNotEmpty) {
      // canvas.saveLayer(destRect, emptyPaintWithWidth);    // 只绘制图片大小区域
      canvas.saveLayer(Rect.largest, emptyPaintWithWidth); // 整个视图区域

      canvas.drawColor(Colors.transparent, BlendMode.clear);
    } */

    if (points.length > 1) {
      for (int i = 0; i < points.length - 1; i++) {
        GestureRecording item = points[i];
        GestureRecording nextItem = points[i + 1];
        Offset? offsetData = item.data;
        Offset? nextOffsetData = nextItem.data;
        if (offsetData != null && nextOffsetData != null) {
          // canvas.drawLine(
          //     offsetData, nextOffsetData, !item.eraser ? paintBrush : eraser);

          canvas.drawLine(offsetData, nextOffsetData, paintBrush);
        }
      }
    }
    // canvas.drawPoints(PointMode.polygon, offsetPoints, paintBrush);
    // 恢复画布状态.
    // if (points.isNotEmpty) canvas.restore();
  }

  // @override
  // bool shouldRepaint(DrawingPainter oldDelegate) {
  //   List<GestureRecording> thePoints = oldDelegate.points;
  //   // var flag = oldDelegate.points != points || oldDelegate.isErasing != isErasing;
  //   return  thePoints != points;
  // }

  @override
  bool shouldRepaint(DrawingPainter oldDelegate) => true;
}

@hwidget
Widget $theCachedNetworkImage(ImageWidgetBuilder imageBuilder, {required String imageUrl}) {
  UseCachedImgRefresh _useImgRefsh = UseCachedImgRefresh.use();

  return CachedNetworkImage(
    key: _useImgRefsh.imageKey.value,
    fit: BoxFit.fitWidth,
    width: double.infinity,
    imageUrl: imageUrl,
    imageBuilder: imageBuilder,
    placeholder: (context, url) => Center(child: SpinKitWave(color: Theme.of(context).primaryColor, size: 50.r)),
    errorWidget: (context, url, error) {
      return GestureDetector(
        onTap: () => (_useImgRefsh.imageKey.value = UniqueKey()),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Image.asset('assets/images/test_paper_loading_failed.png'),
            quickText('加载失败，点击重试', color: Color.fromRGBO(148, 163, 182, 1), size: 12.sp),
          ],
        ),
      );
    },
  );
}
