import 'dart:io';

import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:farmer_client/models/entities/person.dart';
import 'package:farmer_client/widgets/Modal.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import '../services/user.dart';
import '../utils/location.dart';

class AppController extends GetxController {
  // 有了这句, 可以直接 AppController.t 调用
  static AppController t = Get.find();
  GetStorage box = GetStorage();
  final user = Rx<Person>(Person());
  final location = Rxn<Map<String, Object>>();
  final testInt = 1.obs;

  AMapFlutterLocation? _location;

  get locationStr {
    if (null == location.value) return null;

    // 不知道什么问题, 模拟器中 lng 是负值
    double longitude = (location.value!['longitude'] as double).abs();
    double latitude = (location.value!['latitude'] as double).abs();

    return longitude.toString() + "," + latitude.toString();
  }

  void onLocationChange(Map<String, Object> result) {
    location(result);
  }

  @override
  void onInit() {
    super.onInit();

    // 尝试获取 location
    requireLocation(onLocationChange).then((loc) {
      _location = loc;
    }).catchError((e) {
      print(e);

      showAlert(
        title: '获取定位失败',
        message: e.message,
        onConfirm: () => exit(1),
      );
    });

    if (box.read('token') != null) {
      // 尝试获取一次人员信息
      getCurrent().then((person) {
        user(Person.fromJson(person));
      }).catchError((e) {
        print(e);
      });
    }
  }

  @override
  void onClose() {
    if (null != _location) {
      _location?.destroy();
    }
  }
}