import 'package:fis_common/extensions/index.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:fis_ui/index.dart';
import 'package:fis_ui/interface/interactive_container.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/remedical/vocabulary_entry/controller.dart';
import 'package:flyinsono/pages/remedical/vocabulary_entry/state.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

class OrganizationEntryController extends FControllerBase {
  late VocabularyEntryController controller;
  late VocabularyEntryState state;

  OrganizationEntryController(
      VocabularyEntryController vocabularyEntryController) {
    this.controller = vocabularyEntryController;
    this.state = vocabularyEntryController.state;
  }

  /// 添加机构词条库
  Future<void> addOrgThesaurusAsync() async {
    try {
      final thesaurusName = state.createThesaurus['thesaurusName'];
      if (thesaurusName == null ||
          thesaurusName.toString().isNullOrWhiteSpace) {
        PromptBox.toast(i18nBook.remedical.thesaurusNameInputTip.t);
        return;
      }
      final addOrgThesaurusAsync = await rpc.report.addOrgThesaurusAsync(
        AddThesaurusRequest(
          token: Store.user.token,
          languageCode: i18nBook.locale.toCodeString('-'),
          thesaurusName: state.createThesaurus['thesaurusName'],
        ),
      );
      if (addOrgThesaurusAsync) {
        PromptBox.toast(i18nBook.remedical.addSuccess.t);
        controller.getOrgThesaurusPageAsync(true);
        closeEditThesaurusDialog();
        controller.state.vocabularyCard = [];
        controller.state.selectedKey = '';
      } else {
        PromptBox.toast(i18nBook.remedical.addFailed.t);
      }
    } catch (e) {
      logger.e('addOrgThesaurusAsync', e);
    }
  }

  /// 关闭创建 自定义的词条库
  void closeEditThesaurusDialog() {
    state.createThesaurus = <String, dynamic>{};
    Get.back();
  }

  /// 拷贝成机构词条库
  Future<void> copyOrgThesaurusAsync(String thesaurusCode) async {
    try {
      final copyOrgThesaurusAsync = await rpc.report.copyOrgThesaurusAsync(
        CopyOrgThesaurusRequest(
          token: Store.user.token,
          thesaurusCode: thesaurusCode,
        ),
      );
      if (copyOrgThesaurusAsync) {
        PromptBox.toast(i18nBook.remedical.addSuccess.t);
        Get.back();
        controller.getOrgThesaurusPageAsync(true);
      } else {
        PromptBox.toast(i18nBook.remedical.addFailed.t);
      }
    } catch (e) {
      logger.e('copyOrgThesaurusAsync', e);
    }
  }

  /// 添加词条
  Future<bool> addThesaurusContentAsync() async {
    try {
      final thesaurusItemDescription =
          state.vocabularyCardItem.thesaurusItemDescription;
      final thesaurusItemConclusion =
          state.vocabularyCardItem.thesaurusItemConclusion;
      if (thesaurusItemDescription.isNullOrWhiteSpace) {
        PromptBox.toast(i18nBook.remedical.descriptionInput.t);
      } else if (thesaurusItemConclusion.isNullOrWhiteSpace) {
        PromptBox.toast(i18nBook.remedical.concolusionInput.t);
      } else {
        var result = await rpc.report.addThesaurusContentAsync(
          AddThesaurusContentRequest(
            token: Store.user.token,
            thesaurusCode: state.thesaurusCode,
            thesaurusItemDescription: thesaurusItemDescription,
            thesaurusItemConclusion: thesaurusItemConclusion,
            parentItemCode: state.selectedKey,
          ),
        );
        if (result) {
          await Future.delayed(Duration(milliseconds: 10), () {
            PromptBox.toast(i18nBook.remedical.addSuccess.t);
          });
          controller.personalEntryController.closeVocabularyDialogPage();
          return true;
        }
      }
    } catch (e) {
      logger.e('updateThesaurusContentAsync', e);
    }
    return false;
  }

  /// 更新词条
  Future<bool> updateThesaurusContentAsync() async {
    try {
      final thesaurusItemDescription =
          state.vocabularyCardItem.thesaurusItemDescription;
      final thesaurusItemConclusion =
          state.vocabularyCardItem.thesaurusItemConclusion;
      if (thesaurusItemDescription.isNullOrWhiteSpace) {
        PromptBox.toast(i18nBook.remedical.descriptionInput.t);
      } else if (thesaurusItemConclusion.isNullOrWhiteSpace) {
        PromptBox.toast(i18nBook.remedical.thesaurusInput.t);
      } else {
        var result = await rpc.report.updateThesaurusContentAsync(
          UpdateThesaurusContentRequest(
            token: Store.user.token,
            thesaurusCode: state.thesaurusCode,
            thesaurusItemCode: state.vocabularyCardItem.thesaurusItemCode,
            thesaurusItemDescription:
                state.vocabularyCardItem.thesaurusItemDescription,
            thesaurusItemConclusion:
                state.vocabularyCardItem.thesaurusItemConclusion,
            parentItemCode: state.vocabularyCardItem.parentItemCode,
          ),
        );
        if (result) {
          controller
              .thesaurusClickitem(state.vocabularyCardItem.parentItemCode!)
              .then(
                (value) => PromptBox.toast(i18nBook.remedical.editSuccess.t),
              );
          controller.personalEntryController.closeVocabularyDialogPage();
          return true;
        }
      }
    } catch (e) {
      logger.e('updateThesaurusContentAsync', e);
    }
    return false;
  }

  /// 创建词条分类
  Future<void> addThesaurusClassifyAsync() async {
    Store.app.setBusy(i18nBook.remedical.creating.t);
    try {
      final String thesaurusItemName =
          state.createClassification['thesaurusItemName'] ?? "";
      if (thesaurusItemName.isEmpty) {
        PromptBox.toast(i18nBook.remedical.inputCatName.t);
        return;
      }
      final addThesaurusClassifyAsync =
          await rpc.report.addThesaurusClassifyAsync(
        AddThesaurusClassifyRequest(
          token: Store.user.token,
          thesaurusCode: state.thesaurusCode,
          thesaurusItemName: thesaurusItemName,
          parentItemCode: state.createClassification['parentItemCode'],
        ),
      );
      if (addThesaurusClassifyAsync) {
        controller.closeEntryClassifcationDialog();
        controller.getThesaurusItemsAsync();
      } else {
        PromptBox.toast(i18nBook.remedical.creatFailed.t);
      }
    } catch (e) {
      logger.e('addThesaurusClassifyAsync', e);
    }
    Store.app.cancelBusy();
  }

  /// 编辑词条分类
  Future<void> updateThesaurusClassifyAsync(String thesaurusItemCode) async {
    Store.app.setBusy(i18nBook.remedical.creating.t);
    try {
      final thesaurusItemName =
          state.createClassification['thesaurusItemName'].toString();
      if (thesaurusItemName.isNullOrWhiteSpace) {
        PromptBox.toast(i18nBook.remedical.inputCatName.t);
        return;
      }
      final updateThesaurusClassifyAsync =
          await rpc.report.updateThesaurusClassifyAsync(
        UpdateThesaurusClassifyRequest(
          token: Store.user.token,
          thesaurusCode: state.thesaurusCode,
          thesaurusItemName: thesaurusItemName,
          parentItemCode: state.createClassification['parentItemCode'],
          thesaurusItemCode: thesaurusItemCode,
        ),
      );
      if (updateThesaurusClassifyAsync) {
        controller.closeEntryClassifcationDialog();
        controller.getThesaurusItemsAsync();
      } else {
        PromptBox.toast(i18nBook.remedical.creatFailed.t);
      }
    } catch (e) {
      logger.e('updateThesaurusClassifyAsync', e);
    }
    Store.app.cancelBusy();
  }

  /// 删除机构词条库
  void removeOrgThesaurusAsync(
      String thesaurusCode, FInteractiveContainer businessParent) async {
    FConfirmAlert.show(
      context: Get.context!,
      title: i18nBook.common.tip.t,
      subTitle: i18nBook.remedical.deleteOrgVocBaseConrim.t,
      confrimLabel: i18nBook.common.confirm.t,
      cancelLabel: i18nBook.common.cancel.t,
      onConfirm: () async {
        await busyHandle(
          () async {
            final removeOrgThesaurusAsync =
                await rpc.report.removeOrgThesaurusAsync(
              RemoveThesaurusRequest(
                thesaurusCode: thesaurusCode,
                token: Store.user.token,
              ),
            );
            if (removeOrgThesaurusAsync) {
              PromptBox.toast(i18nBook.remedical.deleteVocBaseSuccess.t);
              await controller.getOrgThesaurusPageAsync(true);
            } else {
              PromptBox.toast(i18nBook.remedical.deleteFailed.t);
            }
          },
          text: i18nBook.remedical.deleting.t,
        );
      },
      businessParent: businessParent,
    );
  }
}
