import 'package:get/get.dart';

import '../../../../common/api/index.dart';
import '../../../../common/models/index.dart';
import '../../../../common/utils/index.dart';
import 'index.dart';

class ProcessPickerController extends GetxController {
  ProcessPickerController();

  final state = ProcessPickerState();

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

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final map = Get.arguments;
    if (map != null) {
      final mode = map['mode'];
      if (mode != null && mode is ProcessPickerMode) {
        state.mode.value = mode;
      }
    }
    loadApplicationList();
    super.onReady();
  }

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

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

  void loadApplicationList() async {
    Loading.show();
    var list = await ProcessSurfaceService.to.listApplitionTerminalIsMobile();
    if (list != null) {
      List<ProcessApplicationData> newList = [];
      bool setFirstProcessList = false;
      for (var i = 0; i < list.length; i++) {
        final app = list[i];
        final processList = app.processList;
        if (processList != null && processList.isNotEmpty) {
          newList.add(app);
          // 流程选择的时候才需要
          if (state.mode.value == ProcessPickerMode.process) {
            if (!setFirstProcessList) {
              state.currentApp.value = app;
              state.processList.clear();
              state.processList.addAll(processList);
              setFirstProcessList = true;
            }
          }
        }
      }
      state.appList.clear();
      state.appList.addAll(newList);
      Loading.dismiss();
    }
  }

  /// 返回选中的流程
  void clickProcess(ProcessData process) {
    Get.back(result: process);
  }

  /// 点击应用 展现对应的流程列表
  void clickApp(ProcessApplicationData app) {
    if (state.mode.value == ProcessPickerMode.process) {
      state.currentApp.value = app;
      final processList = app.processList ?? [];
      state.processList.clear();
      state.processList.addAll(processList);
    } else {
      // 返回选中的应用
      Get.back(result: app);
    }
  }
}
