import 'dart:async';

import 'package:fis_common/event/event_type.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_measure/index.dart';
import 'package:fis_measure/utils/prompt_box.dart';
import 'package:fis_measure/view/player/enums.dart';
import 'package:fis_measure/view/player/events.dart';
import 'package:fis_ui/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/pages/remedical/image_pool/controller.dart';
import 'package:flyinsono/pages/remedical/image_pool/controllers/player_controller.dart';
import 'package:fis_vid/data_host/data_host.dart';
import 'package:get/get.dart';

class CanvasPlayerView extends FStatefulWidget implements FWidget {
  const CanvasPlayerView(
    this.vidURL,
    this.playerStateController,
    this.onStateChanged,
    this.index, {
    Key? key,
  }) : super(key: key);
  final String vidURL;
  final int index;
  final FEventHandler<VidPlayStatus> onStateChanged;

  /// 外部播放状态控制器
  final PlayerStateController playerStateController;
  @override
  _CanvasPlayerViewState createState() => _CanvasPlayerViewState();
}

class _CanvasPlayerViewState extends FState<CanvasPlayerView> {
  late final VidPlayerController _playerController;
  final controller = Get.find<ImagePoolController>();
  VidDataHost? _vidDataHost;
  VidDataHost get dataHost => _vidDataHost!;
  bool _ifInit = false;
  bool _isLoading = false;
  Timer? _timer;

  void loadVidDataHost(String url) {
    final playerController = VidPlayerController(url);
    controller.state.canPlayImages[widget.index]!.vidPlayerController =
        playerController;
    _playerController = playerController;
  }

  ///点击播放
  void clickPlay() {
    if (_ifInit) {
      _playerController.play();
    } else {
      _playerController.load().then((value) {
        if (_playerController.status != VidPlayStatus.ready) {
          PromptBox.toast(i18nBook.common.NetImageError.t);
          print(
              '_playerController play error:' + _playerController.status.name);
          logger.e(
              '_playerController play error:' + _playerController.status.name);
          return;
        }
        Future.delayed(const Duration(milliseconds: 100), () {
          _playerController.play();
        });
        setState(() {
          _ifInit = true;
        });
      });
    }
  }

  void clickPause() {
    _playerController.pause();
  }

  void onClickPlay(Object sender, dynamic e) {
    clickPlay();
  }

  @override
  void initState() {
    super.initState();
    loadVidDataHost(widget.vidURL);
    _playerController.eventHandler.removeListener(onControllerEvent);
    _playerController.eventHandler.addListener(onControllerEvent);
    _playerController.frameLoadStateChanged
        .addListener(_onFrameLoadStateChanged);
    widget.playerStateController.trigglePlay.removeListener(onClickPlay);
    widget.playerStateController.trigglePlay.addListener(onClickPlay);
  }

  void onControllerEvent(Object sender, VidPlayerEvent e) {
    if (e is VidPlayerStatusChangeEvent) {
      widget.onStateChanged.emit(this, e.status);
    }
    if (e is VidPlayerFrameIndexChangeEvent) {
      // onFrameChanged(e);
    }
  }

  @override
  FWidget build(BuildContext context) {
    FWidget child;
    final loadingWidget = FContainer(
      height: 40,
      width: 40,
      child: FCircularProgressIndicator(),
    );
    if (!_ifInit) {
      child = loadingWidget;
    } else {
      FWidget player = QuickFWidget(VidPlayer(_playerController));
      child = FStack(
        alignment: AlignmentDirectional.center,
        children: [
          player,
          if (_isLoading) ...[
            FPositioned(
              width: 40,
              height: 40,
              child: loadingWidget,
            ),
          ],
        ],
      );
    }

    return FCenter(
      child: child,
    );
  }

  @override
  void dispose() {
    _playerController.pause();
    _playerController.dispose();
    //dataHost.release();
    widget.playerStateController.trigglePlay.removeListener(onClickPlay);
    _playerController.frameLoadStateChanged
        .removeListener(_onFrameLoadStateChanged);
    _playerController.eventHandler.removeListener(onControllerEvent);
    super.dispose();
  }

  void _onFrameLoadStateChanged(Object sender, bool e) {
    _handleChange(e);
  }

  void _handleChange(bool value) {
    if (value) {
      _timer?.cancel();
      _timer = Timer(Duration(milliseconds: 100), () {
        setState(() {
          _isLoading = value;
        });
      });
    } else {
      if (_timer != null && (_timer?.isActive ?? false)) {
        _timer?.cancel();
        if (_isLoading != false) {
          setState(() {
            _isLoading = false;
          });
        }
      }
    }
  }
}
