import 'package:fis_common/logger/logger.dart';
import 'package:flutter/foundation.dart';
import 'package:get/get.dart';

import '../store/modules/app.dart';
import '../store/store.dart';

typedef AsyncVoidCallback = Future<void> Function();

extension RxExt<T> on Rx<T> {
  /// 更新值
  void updateValue(T newValue) {
    if (newValue != value) {
      value = newValue;
    }
  }
}

abstract class FControllerBase extends GetxController {
  final AppState appState = Store.app;

  bool get busy => appState.busy;
  set busy(v) => appState.busy = v;

  void setBusy(String text) => appState.setBusy(text);

  void cancelBusy() => busy = false;

  Future<void> busyHandle(AsyncVoidCallback callback, {String? text}) async {
    if (text != null) {
      setBusy(text);
    } else {
      busy = true;
    }
    try {
      await callback();
    } catch (e) {
      logger.e("Unhandled page busy error", e);
    }
    busy = false;
  }

  @override
  void onReady() {
    super.onReady();
    busy = true;
    onLoad().then((_) {
      busy = false;
    });
  }

  @protected
  Future<void> onLoad() async {}
}
