import 'package:fis_common/event/event_type.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/utils/prompt_box.dart';
import 'package:fis_measure/view/loadding/loadding.dart';
import 'package:fis_measure/view/player/controller_old.dart';
import 'package:fis_measure/view/player/enums.dart';
import 'package:fis_measure/view/player/events.dart';
import 'package:fis_measure/view/player/player.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:fis_vid/data_host/data_host.dart';
import 'package:flyinsono/pages/others/title_bar_buttons.dart';
import 'package:flyinsono/pages/remedical/report/report_edit/widgets/free_slider.dart';

class ConsultationImagePage extends FStatefulWidget
    implements FInteractiveContainer {
  final ConsultationFileDTO imageInfo;
  ConsultationImagePage(this.imageInfo);

  @override
  String get pageName => 'ConsultationImagePage';

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

class _ConsultationImagePageState extends FState<ConsultationImagePage> {
  static const double _playIconSize = 30;
  final FEventHandler<bool> onPause = FEventHandler<bool>();
  final FEventHandler<double> onProcessChange = FEventHandler<double>();
  late final String _sourceUrl;
  late final String _coverImageUrl;
  late final RemedicalFileDataTypeEnum _fileDataType;
  late final VidPlayerControllerNoSharing _playerController;
  VidPlayStatus _status = VidPlayStatus.init;
  bool _isInitialized = false;
  int _processValue = 0;
  int _totalFramesCount = 0;

  ///是否为图像
  bool get _isImage => [
        RemedicalFileDataTypeEnum.Image,
        RemedicalFileDataTypeEnum.VinnoVidSingle,
        RemedicalFileDataTypeEnum.ThirdVidSingle,
      ].contains(_fileDataType);

  ///是否显示播放Icon
  bool get _isNeedShowPlayIcon => [
        VidPlayStatus.pause,
        VidPlayStatus.stop,
      ].contains(_playerController.status);

  @override
  void initState() {
    super.initState();
    _initParameters();
    _loadVidDataHost(_sourceUrl);
    _processValue = 0;
    _clickPlay();
  }

  @override
  FWidget build(BuildContext context) {
    return FContainer(
      color: Colors.black,
      child: FSafeArea(
        child: FStack(
          children: [
            _buildMainVideoContentView(),
            if (!_isInitialized) ...[
              _buildLoading(),
            ],
            _buildCloseIconButton(),
            if (!_isImage && _isNeedShowPlayIcon) ...[
              _buildPlayCircleIcon(),
            ],
            if (!_isImage) ...[
              ///视频显示进度条
              _buildProcessBar(),
            ],
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    _playerController.eventHandler.removeListener(_onStatusChanged);
  }

  ///视频画面
  FWidget _buildVideoView() {
    return FInkWell(
      mouseCursor: SystemMouseCursors.basic,
      onTap: _videoClick,
      child: QuickFWidget(
        VidPlayer(_playerController),
      ),
    );
  }

  ///播放Icon
  FWidget _buildPlayCircleIcon() {
    return FPositioned(
      right: 0,
      bottom: 0,
      left: 0,
      top: 0,
      child: FContainer(
        alignment: Alignment.center,
        child: FMouseRegion(
          cursor: SystemMouseCursors.click,
          child: FGestureDetector(
            name: "consultationPlay",
            businessParent: widget,
            onTap: _clickPlay,
            child: FIcon(
              Icons.play_circle_outline,
              size: 50,
              color: Colors.white,
            ),
          ),
        ),
      ),
    );
  }

  ///关闭Icon按钮
  FWidget _buildCloseIconButton() {
    return FPositioned(
      right: 0,
      top: kIsMobile ? 10 : 0,
      child: HoverIconButton(
        Colors.white,
        () {
          router.back();
        },
        FIcon(Icons.close),
        Colors.transparent,
        hoverColor: Colors.red,
        hoverIconColor: Colors.white,
        businessParent: this.widget,
        name: "close",
      ),
    );
  }

  ///视频播放
  FWidget _buildMainVideoContentView() {
    FWidget imageContent;
    if (_isImage) {
      imageContent = FImage.network(
        _coverImageUrl,
        fit: BoxFit.fitHeight,
      );
    } else {
      imageContent = _buildVideoView();
    }
    return FPositioned(
      right: 0,
      bottom: 0,
      left: 0,
      top: 0,
      child: FContainer(
        color: Colors.black,
        child: imageContent,
      ),
    );
  }

  ///进度条栏
  FWidget _buildProcessBar() {
    if (_totalFramesCount < 1) {
      return FSizedBox();
    }
    return FPositioned(
      bottom: 20,
      right: 10,
      left: 10,
      child: FRow(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          FIconButton(
            onPressed: _videoClick,
            businessParent: widget,
            icon: FIcon(
              _status == VidPlayStatus.pause
                  ? Icons.play_circle_outline
                  : Icons.pause,
              size: _playIconSize,
              color: Colors.white,
            ),
            iconSize: _playIconSize,
            name: '',
          ),
          FExpanded(
            child: FContainer(
              height: _playIconSize,
              alignment: Alignment.center,
              child: QuickFWidget(
                FFreeSlider(
                  onProcessChange: onProcessChange,
                  min: 0,
                  max: _totalFramesCount.toDouble(),
                  step: 1,
                  value: _processValue.toDouble(),
                  onChanged: (value) {
                    _playerController.gotoFrame(value.toInt() - 1);
                  },
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

//----------------------UI逻辑处理-----------------------

  ///点击播放
  void _clickPlay() async {
    if (_isInitialized) {
      setState(() {
        _totalFramesCount = _playerController.totalFramesCount;
      });
      _playerController.play();
    } else {
      int retryCount = 0;
      while (retryCount < 3) {
        try {
          bool success = await _playerController.load();
          if (!success) {
            throw "loadVidDataHost failed";
          }
          if (_playerController.status != VidPlayStatus.ready) {
            PromptBox.toast(i18nBook.common.NetImageError.t);
            logger.e('_playerController play error:' +
                _playerController.status.name);
            return;
          }
          Future.delayed(const Duration(milliseconds: 100), () {
            setState(() {
              _totalFramesCount = _playerController.totalFramesCount;
            });
            _playerController.play();
          });
          _isInitialized = true;
          return;
        } catch (e) {
          retryCount++;
          if (retryCount == 3) {
            PromptBox.toast(i18nBook.common.NetImageError.t);
            if (_playerController.status != VidPlayStatus.ready) {
              logger.e('_playerController play error:' +
                  _playerController.status.name);
              return;
            }
          } else if (!mounted) {
            return; // 如果组件已经被销毁，则停止重试
          }
        }
      }
    }
  }

  void _loadVidDataHost(String url) {
    final dataHost = VidDataHost(url);
    _playerController = VidPlayerControllerNoSharing(dataHost: dataHost);
    _playerController.eventHandler.addListener(_onStatusChanged);
  }

  ///初始化入参
  void _initParameters() {
    var imageInfo = widget.imageInfo;
    _sourceUrl = imageInfo.sourceUrl ?? '';
    _coverImageUrl = imageInfo.coverImageUrl ?? '';
    _fileDataType = imageInfo.fileDataType;
  }

  ///状态改变
  void _onStatusChanged(Object sender, VidPlayerEvent e) {
    if (e is VidPlayerStatusChangeEvent) {
      setState(() {
        _status = e.status;
      });
    } else if (e is VidPlayerFrameIndexChangeEvent) {
      _processValue = e.index + 1;
      onProcessChange.emit(this, _processValue.toDouble());
    }
  }

  ///点击视频逻辑处理
  void _videoClick() {
    if (_isNeedShowPlayIcon) {
      _clickPlay();
      onPause.emit(this, false);
    } else if (_playerController.playing) {
      _playerController.pause();
      onPause.emit(this, true);
      setState(() {
        _status = VidPlayStatus.pause;
      });
    }
  }

  FWidget _buildLoading() {
    return FAlign(
      child: FCircularProgressIndicator(),
    );
  }
}
