import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/remedical/report/report_edit/controller.dart';
import 'package:flyinsono/pages/remedical/report/report_edit/entitys/report_tag_key.dart';
import 'package:flyinsono/pages/remedical/report/report_edit/state.dart';
import 'package:flyinsono/pages/remedical/report/report_edit/widgets/add_report_tag.dart';
import 'package:flyinsono/rpc.dart';

class AddReportTagController {
  late final ReportEditController controller;
  late final ReportEditState state;

  AddReportTagController(ReportEditController controller) {
    this.controller = controller;
    this.state = controller.state;
  }

  ///打开添加报告标签弹窗
  Future<void> openAddReportTag() async {
    ///是否需要打开判断
    await router.dialog(() => AddReportTag(
        state.allReportTags, state.selectedTags, submitReportTags));
  }

  Future<void> initDatas() async {
    final labels =
        await rpc.report.findReportLabelsAsync(FindReportLabelsRequest(
      token: Store.user.token,
      languageCode: i18nBook.locale.toCodeString('-'),
      recordCode: state.recordCode,
    ));
    labels.forEach((label) {
      final tagKey =
          ReportTagKey(label.reportLabelCode ?? '', label.labelName ?? '');
      if (!state.allReportTags.containsKey(tagKey)) {
        state.allReportTags[tagKey] = label.labelItems ?? [];
      } else {
        logger.e(
            'AddReportTagController _initDatas contains duplicate labels :' +
                tagKey.code);
      }
    });
  }

  ///提交报告标签
  Future<void> submitReportTags(List<String> values) async {
    try {
      final result =
          await rpc.report.modifyReportLabelsAsync(ModifyReportLabelsRequest(
        token: Store.user.token,
        reportCode: state.reportCode,
        reportLabels: values,
      ));
      if (result) {
        PromptBox.toast(i18nBook.remedical.submitSuccess.t);
        Future.delayed(Duration(milliseconds: 500), () {
          router.back();
        });
      } else {
        PromptBox.toast(i18nBook.remedical.submitFail.t);
      }
    } catch (e) {
      logger.e('AddReportTagController submitReportTags ex:', e);
    }
  }
}
