
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 '../services/user.dart';
import '../utils/location.dart';

class AppController extends GetxController {
  // 有了这句, 可以直接 AppController.t 调用
  static AppController t = Get.find();

  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;

    double longitude = location.value!['longitude'] as double;
    double latitude = location.value!['latitude'] as double;

    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),
      );
    });


    // 尝试获取一次人员信息
    getCurrent().then((person) {
      user(Person.fromJson(person));

    }).catchError((e) {
      print(e);
    });
  }

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

}