import 'package:get/get.dart';

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

class CmsCategoryPickerController extends GetxController {
  CmsCategoryPickerController();

  final state = CmsCategoryPickerState();

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

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

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

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

  Future<void> loadCanPublishAppList() async {
    var appList = await CmsAssembleControlService.to.listAppWithCategoryUserCanPublish();
    if (appList != null && appList.isNotEmpty) {
      List<CmsCategoryData> categoryList = [];
      for (var element in appList) { 
        var cateList = element.wrapOutCategoryList ?? [];
        if (cateList.isNotEmpty) {
          for (var cate in cateList) {
            cate.appName = element.appName; // 分组按照这个appName字段来进行
            cate.withApp = element; // 选择器需要传回app对象
            categoryList.add(cate);
          }
        }
      }
      state.categoryList.clear();
      state.categoryList.addAll(categoryList);
    }
  }

  void clickBackResult(CmsCategoryData category) {
    Get.back(result: category);
  }
}
