import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/base/base_controller.dart';
import '../../../data/bean/image_viewer_item.dart';
import '../../../router/app_page_arguments.dart';
import '../../../utils/atmob_log.dart';

/// 图片预览控制器
@injectable
class ImageViewerController extends BaseController {
  final String _tag = "ImageViewerController";

  /// 要预览的图片列表
  RxList<ImageViewerItem> imageViewerItemList = <ImageViewerItem>[].obs;

  /// 当前的查看的图片的索引
  Rx<int> currentIndex = 0.obs;

  /// 是否显示标题栏
  RxBool isShowTitleBar = true.obs;

  late PageController pageController;

  @override
  void onInit() {
    super.onInit();
    _initArgs();
  }

  @override
  void onClose() {
    // 销毁每个PhotoViewController
    pageController.dispose();
    super.onClose();
  }

  /// 初始化参数
  void _initArgs() {
    final arguments = Get.arguments as Map<String, dynamic>?;

    // 图片预览列表
    if (arguments?[AppPageArguments.imageViewerItemList] == null) {
      AtmobLog.i(_tag, '没有传递 imageViewerItemList 参数');
    } else {
      final List<ImageViewerItem>? argumentList =
          arguments?[AppPageArguments.imageViewerItemList]
              as List<ImageViewerItem>?;
      if (argumentList != null) {
        imageViewerItemList.assignAll(argumentList);
        AtmobLog.i(_tag, "imageViewerItemList: $imageViewerItemList");
      }
    }

    // 当前索引
    if (arguments?[AppPageArguments.index] == null) {
      AtmobLog.i(_tag, '没有传递 index 参数');
    } else {
      final int? argumentIndex = arguments?[AppPageArguments.index] as int?;
      if (argumentIndex != null) {
        currentIndex.value = argumentIndex;
        AtmobLog.i(_tag, "index: $currentIndex");
      }
    }

    // 创建PageController，并设置当前页的索引
    pageController = PageController(initialPage: currentIndex.value);
  }

  /// 返回
  void clickBack() {
    Get.back();
  }

  /// 更新当前索引
  void updateCurrentIndex(int newIndex) {
    currentIndex.value = newIndex;
  }

  /// 切换标题栏的显示和隐藏
  void toggleShowTitleBar() {
    isShowTitleBar.value = !isShowTitleBar.value;
  }

  /// 获取对应类型的图片ImageProvider
  ImageProvider getImageProvider(ImageViewerItem item) {
    switch (item.type) {
      case ImageType.asset:
        return AssetImage(item.path);
      case ImageType.network:
        return CachedNetworkImageProvider(item.path);
      case ImageType.file:
        return FileImage(File(item.path));
    }
  }
}
