import 'dart:io';

import 'package:classify_photo/classify_photo.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../module/image_picker/image_picker_util.dart';
import '../utils/toast_util.dart';

class PhotoScanHandler {
  static final _photoClassify = ClassifyPhoto();

  static RxBool isSimilarScanned = false.obs;
  static RxBool isPeopleScanned = false.obs;
  static RxBool isScreenShotScanned = false.obs;
  static RxBool isBlurryScanned = false.obs;

  // 人物图片
  static RxList<AssetEntity> peoplePhotos = <AssetEntity>[].obs;

  // 地点图片
  static Rx<AssetEntity?> locationPhoto = Rx<AssetEntity?>(null);

  // 截图照片
  static Rx<AssetEntity?> screenshotPhoto = Rx<AssetEntity?>(null);

  // 模糊照片
  static Rx<AssetEntity?> blurryPhoto = Rx<AssetEntity?>(null);

  // 相似照片
  static RxList<AssetEntity> similarPhotos = <AssetEntity>[].obs;

  /// 执行所有的照片处理操作
  static Future<void> handleAllPhotos() async {
    var request = Platform.isIOS
        ? await Permission.photos.request()
        : await Permission.storage.request();

    if (request.isGranted) {
      PhotoManager.clearFileCache();
      await handleScreenPhotos();
      await handleBlurryPhotos();
      await handlePeoplePhotos();
      await handleSimilarPhotos();
      if (Platform.isAndroid) {
        await handleAndroidPhotos();
      }
    } else if (request.isPermanentlyDenied) {
      ToastUtil.show("Please enable the album permission");
      openAppSettings();
    } else {
      ToastUtil.show("Please enable the album permission");

      isSimilarScanned.value = false;
      isPeopleScanned.value = false;
      isBlurryScanned.value = false;
      isScreenShotScanned.value = false;
    }
  }

  /// 截图照片
  static Future<bool> handleScreenPhotos() async {
    try {
      final photos = await _photoClassify.getScreenshots();
      print('获取截图照片完成: ${photos?.length ?? 0} 组照片');
      isScreenShotScanned.value = true;
      if (photos != null) {
        await ImagePickerUtil.updatePhotos(photos);
        if (ImagePickerUtil.screenshotPhotos.isNotEmpty) {
          var asset = ImagePickerUtil.screenshotPhotos.first;
          screenshotPhoto.value = asset;
        }
      }
    } catch (e, stackTrace) {
      print('获取截图失败: $e\n$stackTrace');
    }
    isScreenShotScanned.value = true;
    return true;
  }

  /// 模糊照片
  static Future<bool> handleBlurryPhotos() async {
    try {
      final photos = await _photoClassify.getBlurryPhotos();
      print('获取模糊照片完成: ${photos?.length ?? 0} 组照片');
      isBlurryScanned.value = true;
      if (photos != null) {
        await ImagePickerUtil.updatePhotos(photos);
        if (ImagePickerUtil.blurryPhotos.isNotEmpty) {
          var asset = ImagePickerUtil.blurryPhotos.first;
          blurryPhoto.value = asset;
        }
        return true;
      }
    } catch (e, stackTrace) {
      print('获取模糊失败: $e\n$stackTrace');
    }
    isBlurryScanned.value = true;
    return true;
  }

  /// 人物照片
  static Future<bool> handlePeoplePhotos() async {
    try {
      final photos = await _photoClassify.getPeoplePhotos();
      print('获取人物照片完成: ${photos?.length ?? 0} 组照片');
      isPeopleScanned.value = true;
      if (photos != null) {
        await ImagePickerUtil.updatePhotos(photos);
        // 处理人物照片
        peoplePhotos.clear();
        if (ImagePickerUtil.peoplePhotos.isNotEmpty) {
          for (var personPhotos in ImagePickerUtil.peoplePhotos) {
            peoplePhotos.add(personPhotos);
            if (peoplePhotos.length == 2) {
              break;
            }
          }
        }
        return true;
      }
    } catch (e, stackTrace) {
      print('获取人物失败: $e\n$stackTrace');
    }
    isPeopleScanned.value = true;
    return true;
  }

  /// 相似照片
  static Future<bool> handleSimilarPhotos() async {
    try {
      print('开始获取相似照片');
      final photos = await _photoClassify.getSimilarPhotos();
      print('获取相似照片完成: ${photos?.length ?? 0} 组照片');
      isSimilarScanned.value = true;
      if (photos != null) {
        await ImagePickerUtil.updatePhotos(photos);
        similarPhotos.clear();
        if (ImagePickerUtil.similarPhotos.isNotEmpty) {
          for (var group in ImagePickerUtil.similarPhotos) {
            for (var asset in group) {
              similarPhotos.add(asset);
              if (similarPhotos.length == 4) {
                break;
              }
            }
          }
        }
        return true;
      }
    } catch (e, stackTrace) {
      print('获取相似失败: $e\n$stackTrace');
    }
    isSimilarScanned.value = true;
    return true;
  }

  /// Android平台处理方式
  static Future<void> handleAndroidPhotos() async {
    final List<AssetEntity> result = await ImagePickerUtil.loadAssets();
    ImagePickerUtil.peoplePhotos.value = result ?? [];
    ImagePickerUtil.locationPhotos['location'] = result ?? [];
    ImagePickerUtil.screenshotPhotos.value = result ?? [];
    const int batchSize = 10;
    for (int i = 0; i < result.length; i += batchSize) {
      int end = (i + batchSize < result.length) ? i + batchSize : result.length;
      List<AssetEntity> batch = result.sublist(i, end);
      ImagePickerUtil.similarPhotos.add(batch);
    }
    ImagePickerUtil.blurryPhotos.value = result ?? [];

    print("handleAndroidPhotos $result");
    print(
        "ImagePickerUtil.peoplePhotos.value ${ImagePickerUtil.peoplePhotos.length}");

    isSimilarScanned.value = true;
    isPeopleScanned.value = true;
    isBlurryScanned.value = true;
    isScreenShotScanned.value = true;

    similarPhotos.clear();
    if (ImagePickerUtil.similarPhotos.isNotEmpty) {
      for (var group in ImagePickerUtil.similarPhotos) {
        print(
            " ImagePickerUtil.similarPhotos ${ImagePickerUtil.similarPhotos.length}");
        for (var asset in group) {
          similarPhotos.add(asset);
          if (similarPhotos.length == 4) {
            break;
          }
        }
      }
    }

    peoplePhotos.clear();
    if (ImagePickerUtil.peoplePhotos.isNotEmpty) {
      for (var personPhotos in ImagePickerUtil.peoplePhotos) {
        peoplePhotos.add(personPhotos);
        if (peoplePhotos.length == 2) {
          break;
        }
      }
    }

    if (ImagePickerUtil.blurryPhotos.isNotEmpty) {
      var asset = ImagePickerUtil.blurryPhotos.first;
      blurryPhoto.value = asset;
    }

    if (ImagePickerUtil.screenshotPhotos.isNotEmpty) {
      var asset = ImagePickerUtil.screenshotPhotos.first;
      screenshotPhoto.value = asset;
    }
  }
}
