import 'package:get/get.dart';

import '../../../../../common/api/index.dart';
import '../../../../../common/models/index.dart';
import '../../../../../common/routers/index.dart';
import '../../../../../common/widgets/index.dart';
import 'index.dart';

class EmpowerController extends GetxController {
  EmpowerController();

  final state = EmpowerState();

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    loadEmpowerList();
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  loadEmpowerList() async {
    state.empowerList.clear();
    List<EmpowerData>? list;
    if (state.listType.value == EmpowerType.myEmpower) {
      list = await OrganizationPersonalService.to.myEmpowerList();
    } else {
      list = await OrganizationPersonalService.to.empowerToMeList();
    }
    if (list != null) {
      state.empowerList.addAll(list);
    }
  }

  void changeType(EmpowerType type) {
    state.listType.value = type;
    loadEmpowerList();
  }

  void deleteItem(EmpowerData info) {
    if (state.listType.value == EmpowerType.empowerToMe) {
      return;
    }
    final context = Get.context;
    if (context == null) {
      return;
    }
    O2UI.showConfirm(context, 'account_safe_empower_delete_confirm_message'.tr, okPressed: () {
      deleteItemOnline(info);
    });
  }

  deleteItemOnline(EmpowerData info) async {
    if ( info.id?.isEmpty == true) {
      return;
    }
    final result = await OrganizationPersonalService.to.empowerDelete(info.id!);
    if (result != null) {
      loadEmpowerList();
    }
  }

  goCreateEmpower() async {
    await Get.toNamed(O2OARoutes.homeSettingsAccountSafeEmpowerCreate);
    loadEmpowerList();
  }
}
