import 'dart:io';

import 'package:app_settings/app_settings.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:image_crop/image_crop.dart';
import 'package:permission_handler/permission_handler.dart';

import '../../../../../common/utils/index.dart';
import '../../../../../common/widgets/index.dart';

class EditAvatarController extends GetxController {
  EditAvatarController();

  _initData() {
    update(["edit_avatar"]);
  }

  final cropKey = GlobalKey<CropState>();

  Rx<File?> imageFile = Rx<File?>(null);
 
  @override
  void onReady() {
    var map = Get.arguments;
    if (map != null) {
      var file = map['file'];
      if (file != null && file is String && file.isNotEmpty) {
        imageFile.value = File(file);
      }
    }
    super.onReady();
    _initData();
  }
 
  void clickSave() async {
    final area = cropKey.currentState?.area;
    if (area == null) {
      OLogger.e('图片裁剪失败！！！！！');
      Get.back();
      return;
    }
    // final permissionsGranted = await _storagePermission();
    // if (!permissionsGranted) {
    //   OLogger.e('没有存储权限，无法存储图片，设置头像失败！');
    //   _goSettings();
    //   return;
    // }
    final result = await ImageCrop.cropImage(
        file: imageFile.value!,
        area: area,
      );
    Get.back(result: result);
  }

  static Future<bool> _storagePermission() async {
    var status = await Permission.storage.status;
    if (status == PermissionStatus.granted) {
      return true;
    } else {
      status = await Permission.storage.request();
      if (status == PermissionStatus.granted) {
        return true;
      }
    }
    return false;
  }

  /// 去设置权限
  void _goSettings() {
    final context = Get.context;
    if (context == null) {
      OLogger.e('没有 context  无法弹窗！');
      return;
    }
    O2UI.showConfirm(context, 'my_profile_avatar_storage_permission'.tr,
        okText: 'common_app_update_install_go_setting'.tr, okPressed: () {
      AppSettings.openAppSettings();
    });
  }
}
