import 'package:fis_common/env/env.dart';
import 'package:fis_common/event/event_type.dart';
import 'package:fis_common/index.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/view/player/enums.dart';
import 'package:fis_theme/theme.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/pages/remedical/image_pool/widgets/image_describe_view.dart';
import 'package:flyinsono/pages/remedical/report/report_edit/widgets/quick_preview_plugin.dart';
import 'package:flyinsono/pages/remedical/image_pool/controller.dart';
import 'package:flyinsono/pages/remedical/image_pool/controllers/player_controller.dart';
import 'package:flyinsono/pages/remedical/image_pool/entitys/Image_info.dart';
import 'package:flyinsono/pages/remedical/image_pool/entitys/image_state.dart';
import 'package:get/get.dart';

import 'canvas_player_view.dart';

///单个图像播放
class ImagePlayContentView extends FStatefulWidget
    implements FInteractiveContainer {
  ///单个图像信息
  final ExamImageInfo imageInfo;
  final List<DiagnosisOrganEnum>? diagnosisOrgans;

  /// ai 部位
  final DiagnosisConclusionEnum? diagnosisConclusion;
  final void Function()? onTap;
  int get index => imageInfo.index;

  final PlayerStateController playerStateController = PlayerStateController();

  final onStateChanged = FEventHandler<VidPlayStatus>();
  final showIconStatus = [
    VidPlayStatus.loadFail,
    VidPlayStatus.stop,
    VidPlayStatus.pause
  ];
  @override
  final String pageName;
  ImagePlayContentView(
    this.imageInfo, {
    this.pageName = 'ImagePlayContentView',
    this.onTap,
    this.diagnosisConclusion,
    this.diagnosisOrgans,
  });

  @override
  FState<FStatefulWidget> createState() {
    return _FImagePlayContentView();
  }
}

class _FImagePlayContentView extends FState<ImagePlayContentView> {
  final controller = Get.find<ImagePoolController>();
  ExamImageInfo get imageInfo => widget.imageInfo;

  bool _isSelected = false;
  late bool _isMeasureImage = imageInfo.imageType == ExamImageType.MeasureImage;

  @override
  void initState() {
    _isSelected = controller.state.selectedImages
        .any((e) => e.remedicalMeasuredInfoCode == imageInfo.remedicalCode);
    controller.onSelectAllImageChange.addListener(_onSelectAllImageChange);
    super.initState();
  }

  @override
  void dispose() {
    controller.onSelectAllImageChange.removeListener(_onSelectAllImageChange);
    super.dispose();
  }

  @override
  FWidget build(BuildContext context) {
    return _buildImageView();
  }

  @override
  void didUpdateWidget(ImagePlayContentView old) {
    // if (old.imageInfo.index != widget.index) {
    //   _isSelected =
    //       controller.state.selectedImages.contains(imageInfo.remedicalCode);
    // }
    var isSelected = controller.state.selectedImages
        .any((e) => e.remedicalMeasuredInfoCode == imageInfo.remedicalCode);
    if (isSelected != _isSelected) {
      if (mounted) {
        setState(() {
          _isSelected = isSelected;
        });
      }
    }
    super.didUpdateWidget(old);
  }

  FWidget _buildImageView() {
    var imageContent = FContainer(
      color: Colors.black,
      alignment: Alignment.center,
      margin: EdgeInsets.all(5),
      child: _buildChildImage(widget.playerStateController),
    );
    return FStack(
      alignment: Alignment.center,
      children: [
        if (_isMeasureImage) ...[
          FMouseRegion(
            cursor: SystemMouseCursors.click,
            child: FGestureDetector(
              onTap: () {
                setState(() {
                  _isSelected = !_isSelected;
                });
                widget.onTap?.call();
              },
              businessParent: widget,
              name: '',
              child: imageContent,
            ),
          ),
        ] else ...[
          imageContent,
        ],
        if (_isMeasureImage) ...[
          FPositioned(
            right: 5,
            top: 5,
            child: QuickFWidget(
              Checkbox(
                value: _isSelected,
                onChanged: (v) {
                  setState(() {
                    _isSelected = !_isSelected;
                  });
                  widget.onTap?.call();
                },
                checkColor: FTheme.ins.colorScheme.primary,
                fillColor: MaterialStateProperty.all(Colors.white),
              ),
            ),
          ),
        ],
        if (_isMeasureImage) ...[
          FPositioned(
            right: 35,
            top: 7,
            child: FQuickPreviewPlugin(
              imageUrl: imageInfo.url,
              vidUrl: imageInfo.url,
              child: FIcon(
                Icons.zoom_in,
                color: Colors.white,
                size: 32,
              ),
            ),
          ),
        ],
        FPositioned(
          left: 10,
          top: 5,
          child: FText(
            (widget.index + 1).toString(),
            style: TextStyle(
              color: Colors.white,
            ),
          ),
        ),
        ImageDescribeView(
          diagnosisConclusion: widget.diagnosisConclusion,
          diagnosisOrgans: widget.diagnosisOrgans,
          application: imageInfo.application,
          applicationCategory: imageInfo.applicationCategory,
        ),
        if (!imageInfo.isImage) ...[
          FObx(() {
            final isNeedShowIcon =
                controller.state.isShowPlayIconMap[widget.index];
            if (isNeedShowIcon == null || isNeedShowIcon) {
              return buildPlayCircleIcon(widget.playerStateController);
            }
            return FSizedBox();
          }),
        ],
      ],
    );
  }

  ///播放Icon
  FWidget buildPlayCircleIcon(PlayerStateController playerStateController) {
    return FContainer(
      alignment: Alignment.center,
      child: FMouseRegion(
        cursor: SystemMouseCursors.click,
        child: FGestureDetector(
          name: "userPlayImages${widget.index}",
          businessParent: widget,
          onTap: () {
            controller.state.userPlayImages.add(widget.index);
            controller.state.canPlayImages[widget.index] =
                ImageState(isAutoPlay: true);
          },
          child: FIcon(
            Icons.play_circle_outline,
            size: 50,
            color: Colors.white,
          ),
        ),
      ),
    );
  }

  FWidget _buildChildImage(PlayerStateController playerStateController) {
    FWidget child = FObx(() {
      final allHeight = MediaQuery.of(Get.context!).size.height;
      var height = (allHeight / controller.state.column) - 62;
      if (FPlatform.isMacOS || FPlatform.isWindows) {
        height -= 30;
        if (controller.state.column <= 2) {
          height -= 20;
        }
      } else if (controller.state.column == 1) {
        height -= 2;
      }
      var imageStatus = controller.state.canPlayImages[widget.index];
      if (imageStatus != null && !imageStatus.isPlayEnd) {
        _addSelectedChangeListener(widget.index, playerStateController);
        if (imageStatus.isAutoPlay) {
          Future.delayed(
            Duration(milliseconds: 400),
            () {
              controller.state.isShowPlayIconMap[widget.index] = false;
              playerStateController.trigglePlay.emit(this, '');
            },
          );
        }

        return CanvasPlayerView(
          imageInfo.vidUrl,
          playerStateController,
          widget.onStateChanged,
          widget.index,
        );
      } else if (imageInfo.imageType == ExamImageType.AiImage) {
        return FImage.network(
          imageInfo.url,
          height: height,
          fit: BoxFit.fitWidth,
        );
      } else {
        widget.onStateChanged
            .removeListener((sender, e) => onImageStateChanged(sender, e));
        return FImage.network(
          imageInfo.url,
          height: height,
          fit: BoxFit.fitWidth,
        );
      }
    });

    return child;
  }

  void _addSelectedChangeListener(
      int index, PlayerStateController playerStateController) {
    var imageStatus = controller.state.canPlayImages[index];
    if (imageStatus == null) {
      return;
    }
    widget.onStateChanged
        .removeListener((sender, e) => onImageStateChanged(sender, e));
    widget.onStateChanged
        .addListener((sender, e) => onImageStateChanged(sender, e));
  }

  void onImageStateChanged(Object object, VidPlayStatus e) {
    var imageStatus = controller.state.canPlayImages[widget.index];
    if (imageStatus == null) {
      return;
    }
    imageStatus.status = e;
    imageStatus.isAutoPlay = false;
    controller.state.isShowPlayIconMap[widget.index] = false;
    if (e == VidPlayStatus.loadFail) {
      imageStatus.reloadTimes++;
      if (imageStatus.reloadTimes < 3) {
        Future.delayed(
          Duration(milliseconds: 200),
          () {
            widget.playerStateController.trigglePlay.emit(this, '');
          },
        );
      }
    } else if (e == VidPlayStatus.pause) {
      if (imageStatus.isPlayEnd) {
        controller.state.isShowPlayIconMap[widget.index] = true;
        return;
      }
      controller.state.isShowPlayIconMap[widget.index] = true;
      imageStatus.isPlayEnd = true;
      controller.onImageStateChange(widget.index);
    }
  }

  void _onSelectAllImageChange(Object sender, bool e) {
    setState(() {
      _isSelected = e;
    });
  }
}
