// import 'package:fis_lib_report/converts/event_type.dart';
import 'package:fis_common/event/event_type.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_measure/view/player/controller_old.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/rpc.dart';
import 'package:flyinsono/views/wechat_mini_program/wx_images_list/controller.dart';
import 'package:flyinsono/views/wechat_mini_program/wx_public_widgets/wx_screen_direction_lock.dart';
import 'package:get/get.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_measure/view/player/enums.dart';
import 'package:fis_measure/view/player/events.dart';
import 'package:fis_vid/data_host/data_host.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';

import 'index.dart';

class WxImagePreviewController extends GetxController {
  WxImagePreviewController();

  final state = WxImagePreviewState();

  late final VidPlayerControllerNoSharing _playerController;

  VidPlayerControllerNoSharing get playerController => _playerController;

  final FEventHandler<double> onProcessChange = FEventHandler<double>();

  WxImagePreviewArgs _args =
      WxImagePreviewArgs(fileToken: '', type: WxImagesType.SingleFramePng);

  String get pngFileToken => _args.fileToken;

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    _init();
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  void _init() async {
    state.isLoading = true;
    final arguments = Get.arguments;
    if (!(arguments is WxImagePreviewArgs)) return;
    _args = arguments;
    if (_args.isPng) {
      state.isPng = true;
    } else {
      state.isPng = false;
      _initVidData();
    }
  }

  // 初始化播放器数据
  void _initVidData() async {
    final String openId = Store.user.token;
    AppletAPIDownloadFileResult result =
        await rpc.appletAPI.downloadFileAsync(DownloadFileRequest(
      openId: openId,
      fileToken: _args.fileToken,
    ));
    if (result.fileString == null) {
      return;
    }
    const mimeType =
        "video/vid"; // 根据您的视频文件类型进行设置 (如 'video/webm', 'video/ogg' 等)
    final String dataURI = 'data:$mimeType;base64,${result.fileString}';
    // 多帧
    // final mockURL =
    //     'http://cdn-bj.fis.plus/816A061FF8E348D6BBDB106DFAC464FD.vid';
    // 单帧
    // final mockURL =
    //     'http://cdn-bj.fis.plus/3005AE58DFBE4B4B8062E8E2A1404BB9.vid';
    final dataHost = VidDataHost(dataURI);
    final playerController = VidPlayerControllerNoSharing(dataHost: dataHost);
    _playerController = playerController;
    state.isControllerInitialized = true;
    loadVidDataHost(_playerController);
    _playerController.eventHandler.addListener(onControllerEvent);
  }

  void loadVidDataHost(VidPlayerControllerNoSharing playerController) async {
    int retryCount = 0;
    while (retryCount < 3) {
      try {
        bool success = await playerController.load();
        if (!success) {
          throw "loadVidDataHost failed";
        }
        state.isLoading = false;
        state.totalFramesCount = playerController.totalFramesCount;
        if (playerController.currentFrame != null) {
          state.aspectRatio = playerController.currentFrame!.width /
              playerController.currentFrame!.height;
          print("state.aspectRatio:${state.aspectRatio}");
        }
        if (playerController.totalFramesCount <= 1) {
          state.isSingleFrame = true;
          WidgetsBinding.instance.addPostFrameCallback((_) {
            playerController.gotoFrame(0);
          });
        }
        playerController.play();
        return;
      } catch (e) {
        retryCount++;
        if (retryCount == 3) {
          PromptBox.toast(i18nBook.common.NetImageError.t);
        }
      }
    }
  }

  void onControllerEvent(Object sender, VidPlayerEvent e) {
    if (e is VidPlayerStatusChangeEvent) {
      if (e.status == VidPlayStatus.pause) {
        state.isPlaying = false;
        print("暂停播放");
      }
      if (e.status == VidPlayStatus.play) {
        state.isPlaying = true;
        print("开始播放");
      }
    } else if (e is VidPlayerFrameIndexChangeEvent) {
      if (e.index == 0 && playerController.currentFrame != null) {
        state.aspectRatio = playerController.currentFrame!.width /
            playerController.currentFrame!.height;
        print("state.aspectRatio:${state.aspectRatio}");
      }
      state.processValue = e.index + 1;
      onProcessChange.emit(this, state.processValue.toDouble());
    }
  }

  void onScreenDirectionChange(ScreenDirection newDirection) {
    print("newDirection:$newDirection");
    if (Get.context == null) {
      return;
    }
    // 跳回到第一帧
    if (playerController.currentFrameIndex != 0) {
      playerController.gotoFrame(0);
      if (state.isSingleFrame) {
        playerController.pause();
      } else {
        playerController.play();
      }
    }
    if (state.isSingleFrame) {
      WidgetsBinding.instance.addPostFrameCallback((_) {
        playerController.gotoFrame(0);
      });
    }
  }

  void clickPlayButton() {
    if (state.isPlaying) {
      playerController.pause();
    } else {
      playerController.play();
    }
  }
}

class WxImagePreviewArgs {
  String fileToken;
  WxImagesType type;
  WxImagePreviewArgs({required this.fileToken, required this.type});
  bool get isPng => type == WxImagesType.SingleFramePng;
}
