import 'dart:io';

import 'package:classify_photo/classify_photo.dart';
import 'package:clean/base/base_controller.dart';
import 'package:clean/data/consts/constants.dart';
import 'package:clean/data/repositories/user_repository.dart';
import 'package:clean/module/image_picker/image_picker_util.dart';
import 'package:clean/module/locations_photo/locations_photo_view.dart';
import 'package:clean/module/people_photo/people_photo_view.dart';
import 'package:clean/module/screenshots_blurry/screenshots_view.dart';
import 'package:clean/module/similar_photo/similar_photo_view.dart';
import 'package:clean/router/app_pages.dart';
import 'package:clean/utils/toast_util.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../data/api/response/user_info_response.dart';

class HomeController extends BaseController {
  Rx<double> totalSpace = 0.0.obs;
  Rx<double> usedSpace = 0.0.obs;
  Rx<double> photoSpace = 0.0.obs;
  Rx<double> freeSpace = 0.0.obs;

  Rx<String> totalSpaceStr = "".obs;
  Rx<String> usedSpaceStr = "".obs;
  Rx<String> photoSpaceStr = "".obs;
  Rx<String> freeSpaceStr = "".obs;

  // 计算已用存储百分比
  double get usedSpacePercentage => (usedSpace.value / totalSpace.value) * 100;

  // 计算照片占用存储百分比
  double get photoSpacePercentage =>
      (photoSpace.value / totalSpace.value) * 100;

  // 计算可用存储百分比
  double get freeSpacePercentage => (freeSpace.value / totalSpace.value) * 100;

  RxList<String> similarImages =
      List.generate(4, (index) => 'iconHomeNoPhoto').obs;
  RxInt imageCount = 0.obs;

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

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

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

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

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

  // 是否扫描完成
  RxBool isScanned = false.obs;

  UserInfoResponse? get userInfo => userRepository.userInfo.value;

  @override
  Future<void> onInit() async {
    // TODO: implement onInit
    super.onInit();

    if (Platform.isAndroid) {
      loadPhotosFromDirectory();
    }

    if (await Permission.photos.request().isGranted) {
      PhotoManager.clearFileCache();
      getStorageInfo();

      handlePhotos();
    } else {
      ToastUtil.show("Please enable the album permission");
    }

    await userRepository.getUserInfo();

    if (!isFirstIntoApp() && !userRepository.isVip()) {
      Get.toNamed(RoutePath.discount);
    }
    setFirstIntoApp(false);
  }

  Future<void> loadPhotosFromDirectory() async {
    if (ImagePickerUtil.peoplePhotos.isEmpty ||
        ImagePickerUtil.similarPhotos.isEmpty ||
        ImagePickerUtil.locationPhotos.isEmpty ||
        ImagePickerUtil.screenshotPhotos.isEmpty) {
      try {
        final List<AssetEntity> result = await ImagePickerUtil.loadAssets();
        ImagePickerUtil.peoplePhotos.value = result ?? [];

        ImagePickerUtil.locationPhotos['location'] = result ?? [];

        ImagePickerUtil.screenshotPhotos.value = result ?? [];

        ImagePickerUtil.similarPhotos.add(result ?? []);

        ImagePickerUtil.blurryPhotos.value = result ?? [];
      } catch (e) {
        print('Error loading photos: $e');
      }
    }
  }

  Future<void> getStorageInfo() async {
    final classifyPhoto = ClassifyPhoto();

    try {
      final storageInfo = await classifyPhoto.getStorageInfo();

      // 转换为 GB
      final totalSpaceGB = storageInfo['totalSpace']! / (1000 * 1000 * 1000);
      final freeSpaceGB = storageInfo['freeSpace']! / (1024 * 1024 * 1024);
      final usedSpaceGB = storageInfo['usedSpace']! / (1024 * 1024 * 1024);
      final photoSpaceGB = storageInfo['photoSpace']! / (1024 * 1024 * 1024);

      totalSpaceStr.value = ImagePickerUtil.formatFileSize(
          storageInfo['totalSpace']!,
          decimals: 1);
      freeSpaceStr.value = ImagePickerUtil.formatFileSize(
          storageInfo['freeSpace']!,
          decimals: 1);
      usedSpaceStr.value = ImagePickerUtil.formatFileSize(
          storageInfo['usedSpace']!,
          decimals: 1);
      photoSpaceStr.value = ImagePickerUtil.formatFileSize(
          storageInfo['photoSpace']!,
          decimals: 1);

      totalSpace.value = totalSpaceGB.round().toDouble();
      freeSpace.value = freeSpaceGB;
      usedSpace.value = usedSpaceGB;
      photoSpace.value = photoSpaceGB;

      print('总容量: $totalSpaceStr');
      print('可用空间: $freeSpaceStr');
      print('已用空间: $usedSpaceStr');
      print('照片占用: $photoSpaceStr');
    } catch (e) {
      print('获取存储信息失败: $e');
    }
  }

  Future<void> handlePhotos() async {
    final photoClassify = ClassifyPhoto();
    try {
      print('开始获取照片');
      final photos = await photoClassify.getPhoto();
      print('获取照片完成: ${photos?.length ?? 0} 组照片');

      // 已完成扫描
      isScanned.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;
              }
            }
          }
        }

        // 处理地点照片
        locationPhoto.value = null;
        if (ImagePickerUtil.locationPhotos.isNotEmpty) {
          // 获取第一个地点的第一张照片
          final firstLocationPhotos =
              ImagePickerUtil.locationPhotos.values.first;
          if (firstLocationPhotos.isNotEmpty) {
            var asset = firstLocationPhotos.first;
            locationPhoto.value = asset;
          }
        }

        // 处理人物照片
        peoplePhotos.clear();
        if (ImagePickerUtil.peoplePhotos.isNotEmpty) {
          for (var personPhotos in ImagePickerUtil.peoplePhotos) {
            peoplePhotos.add(personPhotos);
            if (peoplePhotos.length == 2) {
              break;
            }
          }
        }

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

        if (ImagePickerUtil.blurryPhotos.isNotEmpty) {
          var asset = ImagePickerUtil.blurryPhotos.first;
          blurryPhoto.value = asset;
        }
      }
    } catch (e, stackTrace) {
      print('获取照片失败: $e');
      print('Stack trace: $stackTrace');
    }
  }
  void _navigateAndStartPage(Function pageStartFunction) {
    // if (isFirstClickHomeClean()) {
    //   setFirstClickHomeClean(false);
    //   Get.toNamed(RoutePath.discount)?.then((value) {
    //     pageStartFunction();
    //   });
    // } else {
      pageStartFunction();
    // }
  }

  similarCleanClick() {
    print('similarCleanClick');
    _navigateAndStartPage(SimilarPhotoPage.start);
  }

  peopleCleanClick() {
    print('peopleCleanClick');
    _navigateAndStartPage(PeoplePhotoPage.start);
  }

  locationCleanClick() {
    print('locationCleanClick');
    _navigateAndStartPage(LocationsPhotoPage.start);
  }

  screenshotCleanClick() {
    print('screenshotCleanClick');
    _navigateAndStartPage(() => ScreenshotsPage.start("Screenshots"));
  }

  blurryCleanClick() {
    print('blurCleanClick');
    _navigateAndStartPage(() => ScreenshotsPage.start("Blurry"));
  }
}
