import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/data/consts/error_code.dart';
import 'package:electronic_assistant/data/repositories/account_repository.dart';
import 'package:electronic_assistant/resource/string.gen.dart';
import 'package:electronic_assistant/utils/error_handler.dart';
import 'package:electronic_assistant/utils/http_handler.dart';
import 'package:electronic_assistant/utils/toast_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';

import '../../../router/app_pages.dart';

class ChatStartController extends BaseController {
  final professionController = TextEditingController();
  final postController = TextEditingController();

  @override
  void onReady() {
    super.onReady();
    String? profession = accountRepository.userInfo.value?.profession;
    if (profession != null) {
      professionController.text = profession;
    }
    String? post = accountRepository.userInfo.value?.post;
    if (post != null) {
      postController.text = post;
    }
  }

  void onNextStep() {
    if (professionController.text.isEmpty) {
      ToastUtil.showToast(StringName.accountProfessionSuggest.tr);
      return;
    }
    if (postController.text.isEmpty) {
      ToastUtil.showToast(StringName.accountPostSuggest.tr);
      return;
    }
    accountRepository
        .updateUserInfo(professionController.text, postController.text)
        .then((data) {
      Get.back(result: true);
      ToastUtil.showToast(StringName.accountProfessionAndPostUpdateSuccess.tr);
    }).catchError((error) {
      if (error is ServerErrorException) {
        if (error.code == ErrorCode.errorCodeNoLogin) {
          Get.toNamed(RoutePath.login)?.then((loginSuccess) {
            loginSuccess != null && loginSuccess ? onNextStep() : null;
          });
        }
      }
      ErrorHandler.toastError(error);
    });
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }
}
