import 'dart:io';

import 'package:flip_card/flip_card_controller.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wallpaperx/applovin_max/applovin_manage.dart';
import 'package:wallpaperx/common/components/dialog/bottomsheet_dialog.dart';
import 'package:wallpaperx/common/components/easy_loading.dart';
import 'package:wallpaperx/common/storage/favorite_data.dart';
import 'package:wallpaperx/common/storage/history_data.dart';
import 'package:wallpaperx/common/utils/device_info_util.dart';
import 'package:wallpaperx/common/utils/download_util.dart';
import 'package:wallpaperx/common/utils/log_print.dart';
import 'package:wallpaperx/common/utils/obj_util.dart';
import 'package:wallpaperx/common/utils/permission_util.dart';
import 'package:wallpaperx/common/utils/wallpaper_manage.dart';
import 'package:wallpaperx/entity/generate_info_model.dart';
import 'package:wallpaperx/entity/image_model.dart';
import 'package:wallpaperx/page/favorite/favorite_controller.dart';
import 'package:wallpaperx/page/history/history_controller.dart';

class WallpaperDetV2Controller extends GetxController {
  RxList wallpaperList = [].obs;
  var position = 0;
  var isSetHistory = true;
  var filePath = '';
  late final PageController pageController;
  late final FlipCardController flipCardController;
  RxBool isFavorite = false.obs;
  RxBool showImgInfo = false.obs;

  @override
  void onInit() {
    super.onInit();
    Map<String, dynamic> arguments = Get.arguments ?? {};
    position = arguments['position'] ?? 0;
    isSetHistory = arguments['isSetHistory'] ?? true;
    wallpaperList = arguments['wallpaperList'] ?? <ImageModel>[];
    pageController = PageController(initialPage: position);
    flipCardController = FlipCardController();
    LogPrint.d(wallpaperList[position].imageUrl);
    int index = FavoriteData().getWallpaperData().indexWhere(
        (element) => element.imageUrl == wallpaperList[position].imageUrl);
    if (index != -1) {
      isFavorite.value = true;
    }
  }

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

  @override
  void onReady() {
    super.onReady();
    if (isSetHistory) {
      setHistory(position);
    }
  }

  /// 图片切换
  void onPageChanged(int index) {
    position = index;
    filePath = '';
    if (isSetHistory) {
      setHistory(position);
    }
    update(["buildImageInfo"]);
    int indexOf = FavoriteData().getWallpaperData().indexWhere(
            (element) => element.imageUrl == wallpaperList[position].imageUrl);
    if (indexOf != -1) {
      isFavorite.value = true;
    } else {
      isFavorite.value = false;
    }
  }

  /// 下载
  void onTapDownload() {
    if (Get.isSnackbarOpen) {
      return;
    }
    DownloadUtil.downloadFile('${wallpaperList[position].imageUrl}',
            (savePath) async {
          filePath = savePath;
          bool canSave = true;
          if (Platform.isIOS) {
            canSave = await PermissionUtil.checkPermission(
              [Permission.photosAddOnly],
            );
          }
          if (canSave) {
            final result =
            await ImageGallerySaver.saveImage(File(filePath).readAsBytesSync());
            if (result['isSuccess']) {
              toast('Saved to album');
            } else {
              toast('Unable to save to album');
            }
          }
        });
  }

  /// 收藏
  void onTapFavorite() {
    ImageModel imageModel = wallpaperList[position];
    // 未收藏过的才保存
    int index = FavoriteData()
        .getWallpaperData()
        .indexWhere((element) => element.imageUrl == imageModel.imageUrl);
    LogPrint.d(index);
    if (index == -1) {
      FavoriteData().setWallpaperData(imageModel);
      isFavorite.value = true;
    } else {
      FavoriteData().delete(index);
      isFavorite.value = false;
    }
    // 刷新收藏列表
    if (Get.isRegistered<FavoriteController>()) {
      FavoriteController.to.getData();
      if (wallpaperList.isEmpty) {
        Get.back();
      } else {
        int indexOf = FavoriteData().getWallpaperData().indexWhere(
            (element) => element.imageUrl == wallpaperList[position].imageUrl);
        if (indexOf != -1) {
          isFavorite.value = true;
        } else {
          isFavorite.value = false;
        }
      }
    }
  }

  /// 浏览记录
  void setHistory(index) {
    ImageModel imageModel = wallpaperList[index];
    HistoryData().setWallpaperData(imageModel);
    // 刷新浏览列表
    if (Get.isRegistered<HistoryController>()) {
      HistoryController.to.getData();
    }
  }

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

  /// 跳转分类明细
  void onTapToClsDet(title) {
      Get.back(result: title);
  }

  /// 翻转
  void onTapToggleCard() {
    flipCardController.toggleCard();
  }

  /// 复制
  void clipboard(GenerateInfoModel? generateInfo) {
    Map textMap = {
      "Prompt": generateInfo!.prompt,
      "Negative Prompt": generateInfo.negativePrompt,
    };
    Clipboard.setData(ClipboardData(text: textMap.toString()));
    toast("Copied");
  }

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