import 'dart:io';
import 'dart:typed_data';
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:hello_wallpaper/applovin_max/applovin_manage.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:hello_wallpaper/common/components/dialog/bottomsheet_dialog.dart';
import 'package:hello_wallpaper/common/components/easy_loading.dart';
import 'package:hello_wallpaper/common/storage/favorite_data.dart';
import 'package:hello_wallpaper/common/utils/device_info_util.dart';
import 'package:hello_wallpaper/common/utils/download_util.dart';
import 'package:hello_wallpaper/common/utils/local_path_util.dart';
import 'package:hello_wallpaper/common/utils/obj_util.dart';
import 'package:hello_wallpaper/common/utils/permission_util.dart';
import 'package:hello_wallpaper/common/utils/wallpaper_manage.dart';
import 'package:hello_wallpaper/models/wallpaper_model.dart';
import 'package:hello_wallpaper/modules/favorite/favorite_controller.dart';

class WallpaperDetController extends GetxController {
  late final List<GlobalKey> globalKey;
  late final List<WallpaperData> wallpaperList;
  late final PageController pageController;
  var blurs = <bool>[].obs;
  var position = 0;
  var filePath = '';

  @override
  void onInit() {
    super.onInit();
    Map<String, dynamic> arguments = Get.arguments ?? {};
    position = arguments['position'] ?? 0;
    wallpaperList = arguments['wallpaperList'] ?? <WallpaperData>[];
    globalKey = List.generate(wallpaperList.length, (index) => GlobalKey());
    blurs.value = List.generate(wallpaperList.length, (index) => false);
    pageController = PageController(initialPage: position);
  }

  @override
  void onClose() {
    pageController.dispose();
    super.onClose();
  }

  /// 图片切换
  void onPageChanged(int index) {
    position = index;
    filePath = '';
  }

  /// 设置滤镜
  void onTapBlur() {
    blurs[position] = !blurs[position];
  }

  /// 下载
  void onTapDownload() {
    if (blurs[position]) {
      // 若是模糊状态，直接捕获保存
      _captureScreenshot();
      return;
    }
    if (Get.isSnackbarOpen) {
      return;
    }
    DownloadUtil.downloadFile('${wallpaperList[position].original}', (savePath) async {
      filePath = savePath;
      bool canSave = true;
      if (Platform.isAndroid) {
        // 在Android 10及以上版本，由于引入了分区存储（Scoped Storage）机制，如果应用只是需要访问媒体文件，而不是整个外部存储
        // ImageGallerySaver使用MediaStore API来添加图片到相册，无需请求存储权限
        // Android 10以下版本，需要申请存储权限
        int sdkVersion = await DeviceInfoUtil.getAndroidSystemVersion();
        if (sdkVersion < 29) {
          canSave = await PermissionUtil.checkPermission([Permission.storage]);
        }
      }
      if (canSave) {
        final result = await ImageGallerySaver.saveFile(savePath);
        if (result['isSuccess']) {
          toast('Saved to album');
        } else {
          toast('Unable to save to album');
        }
      }
    });
  }

  /// 收藏
  void onTapFavorite() {
    WallpaperData wallpaperData = wallpaperList[position];
    // 未收藏过的才保存
    if (FavoriteData().getWallpaperData().firstWhereOrNull((element) => element.original == wallpaperData.original) == null) {
      FavoriteData().setWallpaperData(wallpaperData);
      // 刷新收藏列表
      if (Get.isRegistered<FavoriteController>()) {
        FavoriteController.to.getData();
      }
    }
    toast('Wallpaper has been collected');
  }

  /// 设置壁纸
  void onTapSetWallpaper() async {
    await ApplovinManage().showAdIfReady(ApplovinManage().adUnitId2);
    BottomSheetDialog.show((location) async {
      if (blurs[position]) {
        await _captureScreenshot();
      } else {
        if (ObjUtil.isNotEmptyStr(filePath)) {
          WallpaperManage.setWallpaper(filePath, location);
        } else {
          DownloadUtil.downloadFile('${wallpaperList[position].original}', (savePath) async {
            filePath = savePath;
            WallpaperManage.setWallpaper(filePath, location);
          });
        }
      }
    });
  }

  Future<void> _captureScreenshot() async {
    loading();
    try {
      if (globalKey[position].currentContext != null) {
        if (globalKey[position].currentContext!.findRenderObject() != null) {
          RenderObject boundary = globalKey[position].currentContext!.findRenderObject()!;
          RenderRepaintBoundary repaintBoundary = boundary as RenderRepaintBoundary;

          ui.Image image = await repaintBoundary.toImage();
          ByteData? byteData = await image.toByteData(format: ui.ImageByteFormat.png);
          if (byteData != null) {
            Uint8List? pngBytes = byteData.buffer.asUint8List();

            Directory dir = await LocalPathUtil.getTemporaryPath();
            bool exist = await dir.exists();
            if (!exist) {
              // 若目录不存在，先创建
              await dir.create();
            }

            final imagePath = '${dir.path}/${DateTime.now().millisecondsSinceEpoch}.jpg';
            File imageFile = File(imagePath);
            await imageFile.writeAsBytes(pngBytes);
            filePath = imagePath;

            final result = await ImageGallerySaver.saveImage(pngBytes, quality: 100);
            if (result['isSuccess']) {
              toast('Saved to album');
            } else {
              toast('Unable to save to album');
            }
          }
        }
      }
    } catch (e) {
      toast('Unable to save to album');
    }
    dismiss();
  }

  /// 显示广告
  void showAd() {
    Get.back();
    ApplovinManage().showAdIfReady(ApplovinManage().adUnitId3);
  }
}
