import 'dart:convert';
import 'dart:io';

import 'package:airbridge_flutter_sdk/airbridge_flutter_sdk.dart';
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/event_repository.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:disk_space/disk_space.dart';
import 'package:flutter/Material.dart';
import 'package:flutter/cupertino.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';
import '../../data/consts/event_report_id.dart';
import '../../data/repositories/config_repository.dart';
import '../../handler/event_handler.dart';
import '../../handler/photo_scan_handler.dart';
import '../../widget/multi_segment_circle_indicator.dart';

class HomeController extends BaseController {

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

  // 相似图片
  RxList<AssetEntity> similarPhotos = PhotoScanHandler.similarPhotos;

  // 人物图片
  RxList<AssetEntity> peoplePhotos = PhotoScanHandler.peoplePhotos;

  // 地点图片
  Rx<AssetEntity?> locationPhoto = PhotoScanHandler.locationPhoto;

  // 截图照片
  Rx<AssetEntity?> screenshotPhoto = PhotoScanHandler.screenshotPhoto;

  // 模糊照片
  Rx<AssetEntity?> blurryPhoto = PhotoScanHandler.blurryPhoto;

  // 是否扫描完成
  RxBool isSimilarScanned = PhotoScanHandler.isSimilarScanned;

  // 是否扫描完成
  RxBool isPeopleScanned = PhotoScanHandler.isPeopleScanned;

  // 是否扫描完成
  RxBool isScreenShotScanned = PhotoScanHandler.isScreenShotScanned;

  // 是否扫描完成
  RxBool isBlurryScanned = PhotoScanHandler.isBlurryScanned;

  Rx<double> totalSpace = PhotoScanHandler.totalSpace;
  Rx<double> usedSpace = PhotoScanHandler.usedSpace;
  Rx<double> photoSpace = PhotoScanHandler.photoSpace;
  Rx<double> freeSpace = PhotoScanHandler.freeSpace;

  Rx<String> totalSpaceStr = PhotoScanHandler.totalSpaceStr;
  Rx<String> usedSpaceStr = PhotoScanHandler.usedSpaceStr;
  Rx<String> photoSpaceStr = PhotoScanHandler.photoSpaceStr;
  Rx<String> freeSpaceStr = PhotoScanHandler.freeSpaceStr;

  // 计算已用存储百分比
  double get usedSpacePercentage => PhotoScanHandler.usedSpacePercentage;

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

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

  List<PieData> get pieDataList => [
    PieData("PhotoSpace", photoSpacePercentage, Colors.blue),
    PieData("OtherUsed", usedSpacePercentage - photoSpacePercentage,
        Colors.red),
    PieData("totalSpace", totalSpace.value, Colors.grey.withOpacity(0.1)),
  ];

  // 存储是否扫描完成
  RxBool isStorageScanned =  PhotoScanHandler.isStorageScanned;

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

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

    configRepository.refreshConfig();
    await userRepository.getUserInfo();

    if (userRepository.userInfo.value != null) {
      Airbridge.setUserID(userRepository.userInfo.value!.ssid);

      // 接收归因结果
      Airbridge.setOnAttributionReceived((result) {
        print(result);
        Map<String, String> attr = <String, String>{};
        attr["attributedChannel"] = "Appstore";
        Airbridge.fetchDeviceUUID(onSuccess: (uuid) {
          eventRepository.attrPush(uuid, "airbridge", jsonEncode(result));
        });
      });
    }

    EventHandler.pushInstall();

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

    var status = await Permission.photos.status;
    if (status.isGranted || status.isLimited) {
      if (status.isLimited) {
        _showLimitedAccessPrompt();
      }
    } else if (status.isPermanentlyDenied) {
      ToastUtil.show("Please enable the album permission");
      _showLimitedAccessPrompt();
      isSimilarScanned.value = true;
      isPeopleScanned.value = true;
      isBlurryScanned.value = true;
      isScreenShotScanned.value = true;
    } else {
      ToastUtil.show("Please enable the album permission");
      _showLimitedAccessPrompt();
      isSimilarScanned.value = true;
      isPeopleScanned.value = true;
      isBlurryScanned.value = true;
      isScreenShotScanned.value = true;
    }
  }

  void _showLimitedAccessPrompt() {
    showDialog<bool>(
      context: Get.context!,
      builder: (BuildContext context) {
        return CupertinoAlertDialog(
          title: Text("Full access permission required"),
          content: Text("We need full access permission to scan your entire library and find more duplicate content"),
          actions: <Widget>[
            CupertinoDialogAction(
              isDefaultAction: false,
              isDestructiveAction: true,
              onPressed: () {
                Navigator.of(context).pop(false);
              },
              child: Text("Cancel"),
            ),
            CupertinoDialogAction(
              isDefaultAction: true,
              onPressed: () {
                openAppSettings();
                Navigator.of(context).pop(false);
              },
              child: Text("Open Setting"),
            ),
          ],
        );
      },
    );
  }

  @override
  void onReady() {
    super.onReady();
    // EventHandler.report(EventId.event_03000);
  }

  // Future<void> handleScreenPhotos() async {
  //   final photoClassify = ClassifyPhoto();
  //   try {
  //     print('开始获取截图照片');
  //     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');
  //     print('Stack trace: $stackTrace');
  //   }
  // }
  //
  // Future<void> handleBlurryPhotos() async {
  //   final photoClassify = ClassifyPhoto();
  //   try {
  //     print('开始获取模糊照片');
  //     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;
  //       }
  //     }
  //   } catch (e, stackTrace) {
  //     print('获取照片失败: $e');
  //     print('Stack trace: $stackTrace');
  //   }
  // }
  //
  // Future<void> handlePeoplePhotos() async {
  //   final photoClassify = ClassifyPhoto();
  //   try {
  //     print('开始获取人物照片');
  //     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;
  //           }
  //         }
  //       }
  //     }
  //   } catch (e, stackTrace) {
  //     print('获取照片失败: $e');
  //     print('Stack trace: $stackTrace');
  //   }
  // }
  //
  // Future<void> handleSimilarPhotos() async {
  //   final photoClassify = ClassifyPhoto();
  //   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;
  //             }
  //           }
  //         }
  //       }
  //     }
  //   } catch (e, stackTrace) {
  //     print('获取照片失败: $e');
  //     print('Stack trace: $stackTrace');
  //   }
  // }

  // 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');
    EventHandler.report(EventId.event_03001);
    _navigateAndStartPage(SimilarPhotoPage.start);
  }

  peopleCleanClick() {
    print('peopleCleanClick');
    EventHandler.report(EventId.event_03002);
    _navigateAndStartPage(PeoplePhotoPage.start);
  }

  locationCleanClick() {
    print('locationCleanClick');
    EventHandler.report(EventId.event_03003);
    _navigateAndStartPage(LocationsPhotoPage.start);
  }

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

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

  titleVipClick() {
    EventHandler.report(EventId.event_02000);
    Get.toNamed(RoutePath.store);
  }
}
