import 'dart:convert';

import 'package:fis_common/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/router/router.dart';
import 'package:flyinsono/architecture/services/entity/default_entry_setting.dart';
import 'package:flyinsono/architecture/services/entity/local_setting.dart';
import 'package:flyinsono/architecture/services/modules/default_entry_configuration.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/pages/remedical/vocabulary_entry/widgets/edit_vocabulary_entry_dialog.dart';
import 'package:flyinsono/pages/remedical/vocabulary_entry/widgets/entry_info_mobile_page.dart';
import 'package:flyinsono/pages/remedical/vocabulary_entry/widgets/vocabulary_dialog.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

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

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

  DefaultEntrySetting defaultEntrySetting = DefaultEntrySetting.ins;
  late final DefaultEntryService defaultEntryService =
      Get.find<DefaultEntryService>();

  /// 删除词条 or 删除词条分类
  void removeThesaurusItemAsync(
      String thesaurusItemCode, FInteractiveContainer businessParent,
      [bool? isRemoveThesaurusItem = false]) {
    FConfirmAlert.show(
      context: Get.context!,
      title: i18nBook.common.tip.t,
      subTitle: i18nBook.remedical.deleteVocConfirm.t,
      confrimLabel: i18nBook.common.confirm.t,
      cancelLabel: i18nBook.common.cancel.t,
      onConfirm: () async {
        await busyHandle(
          () async {
            final removeThesaurusAsync =
                await rpc.report.removeThesaurusItemAsync(
              RemoveThesaurusItemRequest(
                thesaurusItemCode: thesaurusItemCode,
                thesaurusCode: state.thesaurusCode,
                token: Store.user.token,
              ),
            );
            if (removeThesaurusAsync) {
              PromptBox.toast(i18nBook.remedical.deleteVocSuccess.t);
              controller.isOrg
                  ? await controller.getOrgThesaurusPageAsync()
                  : await controller.getThesaurusPage();
              await controller.getThesaurusItemsAsync();
              controller.onNodeTap('');
              if (isRemoveThesaurusItem!) {
                closeVocabularyDialogPage();
              }
            } else {
              PromptBox.toast(i18nBook.remedical.deleteFailed.t);
            }
          },
          text: i18nBook.remedical.deleting.t,
        );
      },
      businessParent: businessParent,
    );
  }

  /// 创建 编辑 打开词条库弹窗
  void openEditVocabularyEntryPage() async {
    await controller.getCreateThesaurusPage();
    await router.dialog(
      () => EditVocabularyEntryPage(),
    );
  }

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

  /// 创建和 编辑词条内容
  ///
  /// [vocabularyCardItem] 词条卡片内容
  void openVocabularyDialogPage(
    ThesaurusItemDTO? vocabularyCardItem,
    FInteractiveContainer businessParent,
  ) async {
    if (vocabularyCardItem != null) {
      state.vocabularyCardItem = vocabularyCardItem;
    }
    await router.dialog(
      () => VocabularyDialogPage(
        vocabularyCardItem: state.vocabularyCardItem,
        onOkTap: (isEdit) async {
          bool result = false;
          if (isEdit) {
            await controller.organizationEntryController
                .updateThesaurusContentAsync();
          } else {
            result = await controller.organizationEntryController
                .addThesaurusContentAsync();
          }
          if (result) {
            await controller.getThesaurusItemsAsync();
            controller.onNodeTap(state.selectedKey);
          }
        },
        onCancelTap: () => closeVocabularyDialogPage(),
        onDeleteTap: () => removeThesaurusItemAsync(
          state.vocabularyCardItem.thesaurusItemCode!,
          businessParent,
          true,
        ),
      ),
    );
  }

  /// 关闭词条内容
  void closeVocabularyDialogPage() {
    Get.back();
    state.vocabularyCardItem = ThesaurusItemDTO();
  }

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

  /// 添加词条库
  Future<void> addThesaurusAsync() async {
    try {
      final thesaurusName = state.createThesaurus['thesaurusName'];

      if (thesaurusName == null ||
          thesaurusName.toString().isNullOrWhiteSpace) {
        PromptBox.toast(i18nBook.remedical.thesaurusNameInputTip.t);
        return;
      }
      final addThesaurusAsync = await rpc.report.addThesaurusAsync(
        AddThesaurusRequest(
          token: Store.user.token,
          thesaurusName: state.createThesaurus['thesaurusName'],
          languageCode: i18nBook.locale.toCodeString('-'),
        ),
      );
      if (addThesaurusAsync) {
        PromptBox.toast(i18nBook.remedical.addSuccess.t);
        controller.getThesaurusPage(true);
        closeEditThesaurusDialog();
        controller.state.vocabularyCard = [];
        controller.state.selectedKey = '';
      } else {
        PromptBox.toast(i18nBook.remedical.addFailed.t);
      }
    } catch (e) {
      logger.e('addThesaurusAsync', e);
    }
  }

  /// 设置用户默认词条
  Future<void> setUserDefaultThesaurusAsync(String thesaurusCode) async {
    try {
      busy = true;
      final setUserDefaultThesaurusAsync =
          await rpc.report.setUserDefaultThesaurusAsync(
        SetUserDefaultThesaurusRequest(
          token: Store.user.token,
          thesaurusCode: thesaurusCode,
          languageCode: i18nBook.locale.toCodeString('-'),
        ),
      );
      busy = false;
      if (setUserDefaultThesaurusAsync) {
        controller.isOrg
            ? await controller.getOrgThesaurusPageAsync()
            : await controller.getThesaurusPage();
        final getThesaurusItemsAsync = await rpc.report.getThesaurusItemsAsync(
          GetThesaurusItemsRequest(
            token: Store.user.token,
            thesaurusCode: thesaurusCode,
          ),
        );
        defaultEntrySetting.setDefaultEntry(jsonEncode(getThesaurusItemsAsync));
        defaultEntryService.save();

        if (LocalSetting.ins.isUseSecondWindow! &&
            (FPlatform.isMacOS || FPlatform.isWindows)) {
          await rpc.platform.thesaurusChange(Store.user.token);
        }
      }
    } catch (e) {
      busy = false;
      logger.e('setUserDefaultThesaurusAsync', e);
    }
  }

  ///手机端打开词条详情
  Future<void> openEntryInfoMobilePage(
    int index,
    ThesaurusDTO thesaurusDTO,
  ) async {
    state.thesaurusCode = thesaurusDTO.thesaurusCode ?? '';
    state.thesaurusName = thesaurusDTO.thesaurusName ?? '';
    await controller.getThesaurusItemsAsync();
    Get.to(
      () => EntryInfoMobilePage(
        index,
        thesaurusDTO,
      ),
    );
  }

  ///跟据关键字筛选词条
  void getKeyWordsEntry() {
    final keyWord = state.keyWord;
    final allThesaurusItem = state.allThesaurusItem;
    final newThesaurusItems = allThesaurusItem
        .where((element) => _checkElementIsContainsKeyWord(element, keyWord))
        .toList();
    if (newThesaurusItems.isEmpty) {
      PromptBox.toast(i18nBook.remedical.noEntry.t);
    }
    List<ThesaurusItemDTO> parentsItems = [];
    newThesaurusItems.forEach((element) {
      final parentItemCode = element.parentItemCode ?? '';
      if (parentItemCode.isNotEmpty) {
        final paraentItem = allThesaurusItem
            .firstWhereOrNull((p) => p.thesaurusItemCode == parentItemCode);
        if (paraentItem != null) {
          if (!parentsItems.contains(paraentItem) &&
              !newThesaurusItems.contains(paraentItem)) {
            parentsItems.add(paraentItem);
          }
          final grandItemCode = paraentItem.parentItemCode ?? '';
          if (grandItemCode.isNotEmpty) {
            final grandItem = allThesaurusItem
                .firstWhereOrNull((p) => p.thesaurusItemCode == grandItemCode);
            if (grandItem != null) {
              if (!parentsItems.contains(grandItem) &&
                  !newThesaurusItems.contains(grandItem)) {
                parentsItems.add(grandItem);
              }
            }
          }
        }
      }
    });
    newThesaurusItems.addAll(parentsItems);
    state.selectedThesaurusItems = newThesaurusItems;
  }

  bool _checkElementIsContainsKeyWord(
      ThesaurusItemDTO element, String keyWord) {
    final thesaurusItemName = element.thesaurusItemName ?? '';
    final thesaurusItemConclusion = element.thesaurusItemConclusion ?? '';
    final thesaurusItemDescription = element.thesaurusItemDescription ?? '';
    if (thesaurusItemName.contains(keyWord)) {
      return true;
    } else if (thesaurusItemConclusion.contains(keyWord)) {
      return true;
    } else if (thesaurusItemDescription.contains(keyWord)) {
      return true;
    }
    return false;
  }
}
