
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:o2oa_all_platform/common/index.dart';

import '../../../common/create_form/index.dart';
import '../cms_document/index.dart';
import 'index.dart';

class CmsAppController extends GetxController {
  CmsAppController();

  final state = CmsAppState();
  CmsCategoryData? _category;
  List<CmsCategoryData> publishCategoryList = [];

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

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final map = Get.arguments;
    if (map != null && map["appData"] != null && map["appData"] is CmsAppData) {
      CmsAppData app = map["appData"] as CmsAppData;
      state.app.value = app;
      loadCanPublish();
      final categoryList = app.wrapOutCategoryList ?? [];
      state.categoryList.clear();
      state.categoryList.addAll(categoryList);
      if (map["categoryId"] != null) {
        String categoryId = map["categoryId"] as String;
        for (var i = 0; i < categoryList.length; i++) {
          CmsCategoryData category = categoryList[i];
          if (category.id == categoryId) {
            state.initCategoryIndex = i;
            break;
          }
        }
      }
    } else {
      Loading.toast('cms_app_error'.tr);
      Get.back();
    }
    super.onReady();
  }

  void loadCanPublish() async {
    if (state.app.value != null && state.app.value?.id != null) {
      final app = await CmsAssembleControlService.to
          .getAppCanPublishCategories(state.app.value!.id!);
      if (app?.wrapOutCategoryList?.isNotEmpty == true) {
        publishCategoryList.clear();
        publishCategoryList.addAll(app!.wrapOutCategoryList!);
        state.canPublish = true;
      }
    }
  }

  void clickPublish() {
    _category = null;
    _showCmsCategoryChoose();
  }

  /// 选择分类
  void _showCmsCategoryChoose() {
    final c = Get.context;
    if (c != null) {
      O2UI.showBottomSheetWithCancel(
          c,
          publishCategoryList
              .map((e) => ListTile(
                    onTap: () {
                      Navigator.pop(c);
                      _category = e;
                      _startCreateDocument();
                    },
                    title: Align(
                      alignment: Alignment.center,
                      child: Text(e.categoryName ?? '',
                          style: Theme.of(c).textTheme.bodyMedium),
                    ),
                  ))
              .toList());
    }
  }

  void _startCreateDocument() async {
    if (state.app.value == null || _category == null || _category?.id == null) {
      Loading.toast('cms_create_document_no_args'.tr);
      return;
    }

    var config = state.app.value?.config;
    bool ignoreTitle = false; // 是否忽略标题
    bool latest = true; // 是否查询草稿
    if (config != null && config.isNotEmpty) {
      final map = O2Utils.parseStringToJson(config);
      final ig = map['ignoreTitle'];
      if (ig != null && ig is bool) {
        ignoreTitle = ig;
      }
      final la = map['latest'];
      if (la != null && la is bool) {
        latest = la;
      }
    }
    if (latest) {
      var drafts =
          await CmsAssembleControlService.to.listDocumentDraft(_category!.id!);
      if (drafts != null && drafts.isNotEmpty) {
        OLogger.i('有草稿。。。。直接打开草稿！');
        CmsDocumentPage.open(drafts[0].id!,
            title: drafts[0].title ?? '', options: {"readonly": false});
        return;
      }
    }
    CreateFormPage.startCmsDoc(ignoreTitle, category: _category!);
  }
}
