import 'dart:math';

import 'package:classify_photo/classify_photo.dart';
import 'package:clean/module/analysis/analysis_state.dart';
import 'package:clean/module/image_picker/image_picker_util.dart';
import 'package:clean/module/privacy/privacy_state.dart';
import 'package:clean/utils/expand.dart';
import 'package:clean/utils/file_utils.dart';
import 'package:clean/utils/image_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../base/base_controller.dart';
import '../../model/asset_info.dart';

class PhotoInfoController extends BaseController {

  Rx<FileType> type = FileType.analysis.obs;

  // 存储所有图片，按月份分组
  RxList<AssetInfo> imageList = <AssetInfo>[].obs;

  // 当前显示的图片索引
  final RxInt currentImageIndex = 0.obs;

  final RxMap<String, dynamic> photoDetails = <String, dynamic>{}.obs;

  RxString createTime = "".obs;

  RxString fileName = "".obs;

  RxString model = "".obs;

  RxString focalLength = "".obs;

  RxString size = "".obs;

  RxString iso = "".obs;

  RxString address = "".obs;

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();

    if (Get.arguments != null) {
      final args = Get.arguments as Map<String, dynamic>;
      imageList.value = Get.arguments["list"] as List<AssetInfo>;
      var argType = Get.arguments["type"] as String;

      if (argType == "privacy") {
        type.value = FileType.privacy;
      } else {
        type.value = FileType.analysis;
      }

      // 设置初始索引
      if (args.containsKey('index')) {
        currentImageIndex.value = args['index'] as int;
      }

      loadPhotoInfo();
    }
  }

  Future<void> loadPhotoInfo() async {

    createTime.value = "";
    fileName.value = "";
    model.value = "";
    focalLength.value = "";
    size.value = "";
    iso.value = "";

    var assetInfo = imageList[currentImageIndex.value];
    photoDetails.value = await ImageUtil.getPhotoDetails(assetInfo);
    if (photoDetails.isNotEmpty) {
      createTime.value = photoDetails["createDate"] as String;
      fileName.value = photoDetails["fileName"] as String;
      if (photoDetails["model"] != null) {
        model.value = (photoDetails["model"] as String);
      }
      if (photoDetails["focalLength"] != null && photoDetails["aperture"] != null) {
        focalLength.value =
        "${photoDetails["focalLength"] as String}mm f/${photoDetails["aperture"] as String}";
      }
      if (photoDetails["size"] != null && photoDetails["width"] != null && photoDetails["height"] != null) {
        var imageSize = ImagePickerUtil.formatFileSize(photoDetails["size"], decimals: 1);
        size.value = "${photoDetails["width"] as int} X ${photoDetails["height"] as int} $imageSize";
      }
      if (photoDetails["iso"] != null && photoDetails["exposureTime"] != null) {
        iso.value = "ISO${photoDetails["iso"]} ${photoDetails["exposureTime"]}s";
      }
    }
  }


  // 切换到下一张图片
  void nextImage() {
    if (currentImageIndex.value < imageList.length - 1) {
      currentImageIndex.value++;
    }
    loadPhotoInfo();
  }

  // 切换到上一张图片
  void previousImage() {
    if (currentImageIndex.value > 0) {
      currentImageIndex.value--;
    }
    loadPhotoInfo();
  }

  void deleteBtnClick(AssetInfo asset, int index) {
    showCupertinoModalPopup(
      context: Get.context!,
      builder: (context) {
        return CupertinoActionSheet(
          title: Text(
            "The file will be deleted from the privacy space",
            style: TextStyle(
              color: "#6E6E6E".color,
              fontSize: 12.sp,
              fontWeight: FontWeight.w300,
            ),
          ),
          actions: <Widget>[
            //操作按钮集合
            CupertinoActionSheetAction(
              onPressed: () {
                Navigator.pop(context);
                FileUtils.deleteAsset(type.value, asset.id.substring(0, 36));

                if (type.value == FileType.privacy) {
                  PrivacyState.removeAsset(asset.id);
                  // 从列表中移除
                  imageList = PrivacyState.imageList;
                }

                if (type.value == FileType.analysis) {
                  AnalysisState.removeAsset(asset.id);
                  // 从列表中移除
                  imageList = AnalysisState.imageList;
                }

                // 如果没有图片了，返回上一页
                if (imageList.isEmpty) {
                  Get.back();
                } else {
                  if (currentImageIndex.value != 0) {
                    currentImageIndex.value = imageList.length - 1;
                  }
                }
              },
              child: Text(
                'Delete',
                style: TextStyle(
                  color: "#FC4C4F".color,
                  fontWeight: FontWeight.w500,
                  fontSize: 16.sp,
                ),
              ),
            ),
          ],
          cancelButton: CupertinoActionSheetAction(
            //取消按钮
            onPressed: () {
              Navigator.pop(context);
            },
            child: Text(
              'Cancel',
              style: TextStyle(
                color: "#007AFF".color,
                fontWeight: FontWeight.w500,
                fontSize: 16.sp,
              ),
            ),
          ),
        );
      },
    );
  }

  // 格式化文件大小显示
  String formatFileSize(int bytes) {
    if (bytes <= 0) return "Delete";

    final units = ['B', 'KB', 'MB', 'GB'];
    int digitGroups = (log(bytes) / log(1024)).floor();

    if (bytes == 0) {
      return "Delete";
    } else {
      return "Delete(${(bytes / pow(1024, digitGroups)).toStringAsFixed(1)} ${units[digitGroups]})";
    }
  }
}
