import 'dart:async';

import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/rpc.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/router.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/pages/remedical/consultation/controller.dart';
import 'package:flyinsono/pages/remedical/consultation/state.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';

///报告分享页面控制器
///
///[controller] 诊断页面控制器
class ReportShareController extends FControllerBase {
  late ConsultationController controller;
  late FConsultationState state;
  ReportShareController(ConsultationController consultationController) {
    this.controller = consultationController;
    this.state = controller.state;
  }

  ///添加报告短信分享手机号
  bool addSharePhoneNumbers() {
    final phone = controller.targetAcountController.text;
    if (!phone.isPhoneNumber) {
      PromptBox.toast(i18nBook.user.phoneFormError.t);
      return false;
    } else if (state.selectedPhoneNumbers.contains(phone)) {
      PromptBox.toast(i18nBook.common.phoneExists.t);
      return false;
    }
    state.selectedPhoneNumbers.add(phone);
    controller.targetAcountController.text = "";
    return true;
  }

  /// 短信分享报告
  ///
  /// 若实时诊断的报告code为null就拿远程诊断的报告code
  Future<void> submitShareSMS(String? reportToShare) async {
    final result = await rpc.report.shareReportBySmsAsync(
      ShareReportBySmsRequest(
        mobileList: state.selectedPhoneNumbers,
        token: Store.user.token,
        reportCode: reportToShare ?? state.reportCode,
        languageCode: i18nBook.locale.toCodeString('-'),
      ),
    );
    if (result) {
      PromptBox.toast(i18nBook.user.operationSuccess.t);
      router.back();
    } else {
      PromptBox.toast(i18nBook.user.operationFailed.t);
    }
  }

  ///邮箱分享
  bool addShareEmail() {
    final email = controller.targetAcountController.text;
    if (!email.isEmail) {
      PromptBox.toast(i18nBook.user.emailError.t);
      return false;
    } else if (state.selectedEmails.contains(email)) {
      PromptBox.toast(i18nBook.common.emailExists.t);
      return false;
    }
    state.selectedEmails.add(email);
    controller.targetAcountController.text = "";
    return true;
  }

  /// 邮箱分享报告
  ///
  /// 若实时诊断的报告code为null就拿远程诊断的报告code
  Future<void> submitShareEmail(String? reportToShare) async {
    final result = await rpc.report.shareReportByEmailAsync(
      ShareReportByEmailRequest(
        emailList: state.selectedEmails,
        token: Store.user.token,
        reportCode: reportToShare ?? state.reportCode,
        languageCode: i18nBook.locale.toCodeString('-'),
      ),
    );
    if (result) {
      PromptBox.toast(i18nBook.user.operationSuccess.t);
      router.back();
    } else {
      PromptBox.toast(i18nBook.user.operationFailed.t);
    }
  }
}
