import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:video_player/video_player.dart';

import '../../../common/utils/index.dart';
import 'index.dart';

class VideoPlayerPageController extends GetxController {
  VideoPlayerPageController();

  final state = VideoPlayerState();

  // 视频控制器
  VideoPlayerController? videoPlayerController;
  bool isSliding = false;

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final context = Get.context;
    if (context != null) {
      state.isLandscape = MediaQuery.of(context).orientation == Orientation.landscape;
    }
    _initVideo();
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    if (state.isLandscape) {
      OLogger.i("关闭前还原竖屏");
      _setPortrait();
    }
    
    videoPlayerController?.dispose();
    videoPlayerController = null;
    state.isInit = false;
    super.onClose();
  }


  _initVideo() {
    final map = Get.arguments;
    if (map != null) {
      state.title = map["title"] ?? "";
      OLogger.d("设置标题 title: ${state.title} ");
      final String url = map["url"] ?? "";
      final String filePath = map["filePath"] ?? "";
      if (url.isNotEmpty) {
        OLogger.d('在线视频，url $url');
        videoPlayerController = VideoPlayerController.networkUrl(Uri.parse(url),
            httpHeaders: <String, String>{
              O2ApiManager.instance.tokenName:
                  O2ApiManager.instance.o2User?.token ?? ''
            });
        _initVideoController();
      } else if (filePath.isNotEmpty) {
        OLogger.d('本地视频，filePath $filePath');
        videoPlayerController = VideoPlayerController.file(File(filePath));
        _initVideoController();
      }
    }
  }

  _initVideoController() async {
    await videoPlayerController?.initialize();
    state.isInit = true;
    state.duration = videoPlayerController?.value.duration ?? Duration.zero;
    videoPlayerController?.addListener(() {
      if (isSliding) {
        return;
      }
      final position = videoPlayerController?.value.position;
      final duration = videoPlayerController?.value.duration;
      state.duration = duration ?? Duration.zero;
      state.position = position ?? Duration.zero;
      state.progress =
          state.position.inMilliseconds / state.duration.inMilliseconds;
      OLogger.d('${state.duration} ${state.position} ${state.progress}');
      if (state.isPlaying && position == duration) {
        // 播放完成
        state.isPlaying = false;
      }
    });
    OLogger.d("init video controller  完成！！！！");
  }

  /// 点击旋转 横屏或竖屏
  clickRotation() {
    if (state.isLandscape) {
      _setPortrait();
    } else {
      _setLandscape();
    }
  }

    // 设置横屏
  _setLandscape() {
    SystemChrome.setPreferredOrientations([DeviceOrientation.landscapeRight]);
    if(Platform.isAndroid){
      ///关闭状态栏，与底部虚拟操作按钮
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual, overlays: []);
    }
    state.isLandscape = true;
  }

  // 设置竖屏
 _setPortrait() {
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    if(Platform.isAndroid){
      ///显示状态栏，与底部虚拟操作按钮
      SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
          overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom]);
    }
    state.isLandscape = false;
  }

  /// 点击视频 暂停或播放
  clickVideo() {
    if (state.isPlaying) {
      videoPlayerController?.pause();
    } else {
      videoPlayerController?.play();
    }
    state.isPlaying = !state.isPlaying;
  }

  /// 滑动视频进度 开始
  slideChangeProgressStart(double value) {
    isSliding = true;
    slideChangeProgress(value);
  }
  /// 滑动视频进度 结束
  slideChangeProgressEnd(double value) {
    slideChangeProgress(value);
    videoPlayerController?.seekTo(state.position);// 拖动完成设置视频进度
    isSliding = false;
  }
  /// 滑动视频进度 拖动中
  slideChangeProgress(double value) {
    final duration = videoPlayerController?.value.duration;
    state.duration = duration ?? Duration.zero;
    int position = (value * state.duration.inMilliseconds).toInt();
    state.position = Duration(milliseconds: position);
    state.progress = state.position.inMilliseconds / state.duration.inMilliseconds;
    OLogger.d('${state.duration} ${state.position} ${state.progress}');
    if (state.isPlaying && state.position == state.duration) {
      // 播放完成
      state.isPlaying = false;
    }
  }

}
