import 'package:cpt_auth/modules/select_estate/select_estate_view_model.dart';
import 'package:cpt_auth/modules/select_role/select_role_page.dart';
import 'package:cpt_auth/modules/select_unit/select_unit_state.dart';
import 'package:domain/entity/id_address_entity.dart';
import 'package:domain/repository/profile_repository.dart';
import 'package:flutter/material.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';

import '../select_estate/select_estate_state.dart';
import 'attach_search_unit_dialog.dart';

part 'select_unit_view_model.g.dart';

@riverpod
class SelectUnitViewModel extends _$SelectUnitViewModel with DioCancelableMixin {
  late final ProfileRepository _profileRepository;
  late final SelectEstateViewModel _selectEstateViewModel;
  late final SelectEstateState _selectEstateState;
  BuildContext? _targetContext;

  final unitList = <IdAddressEntity>[];

  @override
  SelectUnitState build() {
    _profileRepository = ref.read(profileRepositoryProvider);
    _selectEstateViewModel = ref.watch(selectEstateViewModelProvider.notifier);
    _selectEstateState = ref.watch(selectEstateViewModelProvider);

    final state = SelectUnitState();
    registerCancellation();
    return state;
  }

  /// 提交选择的街道与单元
  void submitUnit() async {
    // final FocusNode blockFocusNode = state.formData['block']!['focusNode'];
    // final FocusNode unitFocusNode = state.formData['unit']!['focusNode'];
    // final FocusNode roomFocusNode = state.formData['room']!['focusNode'];
    //
    // blockFocusNode.unfocus();
    // unitFocusNode.unfocus();
    // roomFocusNode.unfocus();

    // final TextEditingController blockController = state.formData['block']!['controller'];
    // final TextEditingController unitController = state.formData['unit']!['controller'];
    // final TextEditingController roomController = state.formData['room']!['controller'];

    // final block = blockController.text;
    // final unit = unitController.text;
    // final room = roomController.text;

    // if (Utils.isEmpty(block)) {
    //   ToastEngine.show("Block cannot be empty!");
    //   return;
    // }
    //
    // if (Utils.isEmpty(unit)) {
    //   ToastEngine.show("Unit Number cannot be empty!");
    //   return;
    // }

    if (Utils.isEmpty(state.selectedUnitId)) {
      ToastEngine.show("Select Unit First!");
      return;
    }

    final result = await _profileRepository.estateJoinCheck(unitId: state.selectedUnitId);

    if (result.isSuccess) {
      //存入内存数据
      _selectEstateViewModel.saveUnit(address: state.selectedUnitName, unitId: state.selectedUnitId);
      SelectRolePage.startInstance();
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }

  }

  void pickUnit(BuildContext targetContext) async{
    _targetContext = targetContext;
    if (unitList.isNotEmpty){
      //尝试展示下拉选选项
      showDropDownDialog();
    }else {
      final result = await _profileRepository.searchEstateUnits(estateId: _selectEstateState.selectedEstate?.id, cancelToken: cancelToken);

      if (result.isSuccess) {
        final list = result.list;

        if (list != null && list.isNotEmpty) {
          unitList.clear();
          unitList.addAll(list);
          //尝试展示下拉选选项
          showDropDownDialog();
        }
      } else {
        Log.e(result.errorMsg ?? "UnKnow Error");
      }
    }

  }

  void showDropDownDialog() {
    DialogEngine.showAttach(
      tag: 'unit',
      targetContext: _targetContext!,
      position: DialogPosition.bottom,
      widget: AttachSearchUnitDialog(
        unitList: unitList,
        onSelected: (item) {
          state = state.copyWith(selectedUnitName: item?.address,selectedUnitId: item?.id);
        },
      ),
    );
  }
}
