import 'dart:async';

import 'package:fis_common/logger/logger.dart';
import 'package:fis_i18n/i18n.dart';
import 'package:fis_jsonrpc/services/index.dart';
import 'package:flutter/material.dart';
import 'package:flyinsono/architecture/define.dart';
import 'package:flyinsono/architecture/router/index.dart';
import 'package:flyinsono/architecture/services/modules/area_region.dart';
import 'package:flyinsono/architecture/states/states.dart';
import 'package:flyinsono/architecture/utils/prompt_box.dart';
import 'package:flyinsono/managers/interfaces/server_config.dart';
import 'package:flyinsono/pages/components/select.dart';
import 'package:flyinsono/pages/main/home_page/controller.dart';
import 'package:flyinsono/rpc.dart';
import 'package:get/get.dart';
import 'index.dart';

///个人信息完善界面控制器
class ProfileCompleteController extends FControllerBase
    with WidgetsBindingObserver {
  ProfileCompleteController();

  ///是否中国地区
  bool isChinaArea = true;

  ///获取地区信息服务
  final areaRegionService = Get.find<AreaRegionService>();

  ///用户个人信息状态
  final state = ProfileCompleteState();

  ///滚动条控制器
  final innerScrollController = ScrollController();

  /// 文本焦点
  final nameFocusNode = FocusNode();
  final mobileFocusNode = FocusNode();
  final emailFocusNode = FocusNode();
  final hospitalFocusNode = FocusNode();

  /// 城市下拉选择框
  final FSelectController<AreaRegionModel> countryController =
      FSelectController();
  final FSelectController<AreaRegionModel> provinceController =
      FSelectController();
  final FSelectController<AreaRegionModel> cityController = FSelectController();

  /// 文本编辑控制器
  late final TextEditingController nameInputController;
  late final TextEditingController mobileInputController;
  late final TextEditingController emailInputController;
  late final TextEditingController hospitalFullNameInputController;
  final ScrollController scrollController = ScrollController();
  final _keyboardHeight = 0.0.obs;

  /// 表单校验
  late final _formValidator = _FormValidator(state);

  /// 键盘弹起高度
  double get keyboardHeight => _keyboardHeight.value;

  ///关闭当前页面
  void onPageClose() {
    _checkCMSUrl();
    router.back(result: false);
  }

  /// 提交
  Future<void> onSubmit() async {
    final valid = _formValidator.validate();
    if (!valid) {
      return;
    }

    setBusy(i18nBook.common.submitting.t);
    try {
      // 有部门取部门，无部门选医院
      String organizationCode = state.departmentSelection ??
          state.hospitalDtoList
              .firstWhere(
                (e) => e.organizationName == state.hospitalName,
              )
              .organizationCode!;
      final name = state.name;
      var result = await rpc.user.alterUserInfoAsync(
        AlterUserInfoRequest(
          token: Store.user.token,
          fullName: name,
          phone: state.mobile,
          email: state.email,
          organizationCode: organizationCode,
          languageCode: i18nBook.locale.languageCode,
        ),
      );
      PromptBox.toast(i18nBook.common.submitted.t);
      busy = false;
      _checkCMSUrl();
      router.back(result: result);
    } catch (e) {
      busy = false;
      router.back();
      logger.e("msg", e);
    }
  }

  ///设置医院名称
  Future<void> setHospitalName() async {
    try {
      if (state.hospitalName == "") {
        state.departmentOptions = [];
        return;
      }
      final matchOrgIndex = state.hospitalDtoList
          .indexWhere((e) => e.organizationName == state.hospitalName);
      if (matchOrgIndex > -1) {
        final hospitalInfo = state.hospitalDtoList[matchOrgIndex];
        try {
          var departments = await rpc.organization.searchOrganizationsAsync(
            SearchOrganizationsRequest(
              token: Store.user.token,
              keyword: "",
              parentCode: hospitalInfo.organizationCode!,
              organizationType: OrganizationTypeEnum.Department,
            ),
          );
          state.departmentOptions = departments
              .map(
                (e) => DepartmentModel(
                  title: e.organizationName!,
                  code: e.organizationCode!,
                ),
              )
              .toList();
        } catch (e) {
          logger.e('msg', e);
        }
      } else {
        state.departmentOptions = [];
      }
    } catch (ex) {
      print(ex);
    }
  }

  ///选择医院
  Future<List<OrganizationDTO>> fetchHospital(String name,
      [bool isloadMore = false]) async {
    final ogranizations = await rpc.organization.searchOrganizationsAsync(
      SearchOrganizationsRequest(
        token: Store.user.token,
        keyword: name,
        parentCode: "",
        pageIndex: state.pageIndex,
        organizationType: OrganizationTypeEnum.Corporation,
      ),
    );
    if (isloadMore) {
      state.hospitalDtoList.addAll(ogranizations);
    } else if (state.pageIndex == 1) {
      state.hospitalDtoList = ogranizations;
    }
    return ogranizations;
  }

  ///加载中国省份
  Future<void> fetchProvinceData() async {
    ///1000000是中国的地域编码
    final options = areaRegionService.findListByParentCode("1000000");
    provinceController.selection = null;
    provinceController.options = options;
  }

  ///根据省份加载城市
  Future<void> fetchCityData(String parentCode) async {
    final options = areaRegionService.findListByParentCode(parentCode);
    cityController.selection = null;
    cityController.options = options;
  }

  //获取用户信息
  Future<UserDTO> getUserInfo() async {
    try {
      final result = await rpc.user.getUserInfoAsync(
        GetUserInfoRequest(token: Store.user.token),
      );
      Store.user.handleUserSyncUpdate(result);
      state.name = result.fullName ?? "";
      nameInputController.text = state.name;
      state.mobile = result.phone ?? "";
      mobileInputController.text = state.mobile;
      state.email = result.email ?? "";
      emailInputController.text = state.email;
      state.createTime = result.createTime!;
      state.hospitalName = result.organizationName ?? "";
      if (result.roleCodes!.length > 0) {
        state.roleCode = result.roleCodes!.first;
      }
      return result;
    } catch (e) {
      logger.e('msg', e);
      return UserDTO();
    }
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    WidgetsBinding.instance.addPersistentFrameCallback((timeStamp) {
      final bottom = MediaQuery.of(Get.context!).viewInsets.bottom;
      if (keyboardHeight != bottom) {
        _keyboardHeight.value = bottom;
      }
    });
  }

  @override
  void onInit() {
    _initState();
    _listenFocusNodes();
    WidgetsBinding.instance.addObserver(this);
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
    getUserInfo();
  }

  @override
  void dispose() {
    _disposeFocusNodes();
    _disposeControllers();
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  void _initState() async {
    nameInputController = TextEditingController();
    mobileInputController = TextEditingController();
    emailInputController = TextEditingController();
    hospitalFullNameInputController = TextEditingController();
    countryController.options =
        areaRegionService.findTopGradeList(); // TODO: 提取
  }

  ///用户设置医院后才能有CMSUrl,用户设置信息后重新获取一次
  Future<void> _checkCMSUrl() async {
    try {
      var homeCOntroller = Get.find<HomePageController>();
      if (homeCOntroller.state.cmsUrl.isEmpty) {
        var cmsUrl = await Get.find<IServerConfigManager>().getCMSUrl();
        if (cmsUrl != null && cmsUrl != homeCOntroller.state.cmsUrl) {
          homeCOntroller.state.cmsUrl = cmsUrl;
        }
      }
    } catch (e) {
      logger.e('ProfileCompleteController _checkCMSUrl ex:', e);
    }
  }

  void _listenFocusNodes() {
    nameFocusNode.addListener(() {
      if (!nameFocusNode.hasFocus) _formValidator.validateName();
    });
    mobileFocusNode.addListener(() {
      if (!mobileFocusNode.hasFocus) _formValidator.validateMobile();
    });
    emailFocusNode.addListener(() {
      if (!emailFocusNode.hasFocus) _formValidator.validateEmail();
    });
    hospitalFocusNode.addListener(() {
      if (hospitalFocusNode.hasFocus) {
        Future.delayed(Duration(milliseconds: 500), () {
          innerScrollController.animateTo(
            hospitalFocusNode.offset.dy - kToolbarHeight - 50,
            curve: Curves.linear,
            duration: Duration(milliseconds: 300),
          );
        });
      } else {
        // Future.delayed(Duration(milliseconds: 300), () {
        //   _formValidator.validateHospital();
        // });
      }
    });
  }

  void _disposeFocusNodes() {
    nameFocusNode.dispose();
    mobileFocusNode.dispose();
    emailFocusNode.dispose();
    hospitalFocusNode.dispose();
  }

  void _disposeControllers() {
    innerScrollController.dispose();

    countryController.dispose();
    provinceController.dispose();
    cityController.dispose();
  }
}

///表单验证
class _FormValidator {
  _FormValidator(this.data);

  final ProfileCompleteState data;
  late final validateState = ProfileCompleteFormValidateState(data);

  ///整体验证
  bool validate() {
    // 验证链
    final chain = [
      validateName,
      if (data.isChinaArea) validateMobile,
      validateEmail,
      validateHospital,
    ];
    // 按序验证
    for (var fn in chain) {
      final valid = fn();
      if (!valid) return false;
    }
    return true;
  }

  bool validateName() {
    if (!validateState.realNameValid) {
      PromptBox.toast(i18nBook.profileComplete.nameFieldValidation.t);
      return false;
    }
    return true;
  }

  bool validateMobile() {
    if (!validateState.mobileValid) {
      PromptBox.toast(i18nBook.profileComplete.phoneFormatValidation.t);
      return false;
    }
    return true;
  }

  bool validateEmail() {
    if (!validateState.emailValid) {
      PromptBox.toast(i18nBook.profileComplete.emailFormatValidation.t);
      return false;
    }
    return true;
  }

  bool validateHospital() {
    if (!validateState.hospitalValid) {
      PromptBox.toast(i18nBook.profileComplete.OrganizationNamePlaceHolder.t);
      return false;
    }
    return true;
  }
}
