import 'package:cpt_auth/modules/select_estate/select_estate_state.dart';
import 'package:cpt_auth/modules/select_unit/select_unit_page.dart';
import 'package:domain/entity/id_name_entity.dart';
import 'package:domain/repository/profile_repository.dart';
import 'package:flutter/cupertino.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 'dialog/attach_search_dialog.dart';

part 'select_estate_view_model.g.dart';

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

  @override
  SelectEstateState build() {
    _profileRepository = ref.read(profileRepositoryProvider);
    final state = SelectEstateState();
    registerCancellation();
    return state;
  }

  /// 提交并进入下一步
  void submitEstate() {
    if (state.selectedEstate == null) {
      ToastEngine.show("Select Estate First");
      return;
    }

    SelectUnitPage.startInstance();
  }

  /// 关键字搜索房产
  void searchEstate(BuildContext targetContext, String? keyword) async {
    _targetContext = targetContext;
    final result = await _profileRepository.searchEstate(keyword: keyword, cancelToken: cancelToken);

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

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

  //Attach下拉选
  void showDropDownDialog({bool needReLocation = false}) {
    if (_targetContext == null) return;
    if (state.estateList == null || state.estateList!.isEmpty) return;

    if (needReLocation) {
      Log.d("需要重新定位弹出");
      DialogEngine.dismiss(tag: 'estate');
    }
    if (!DialogEngine.checkIsExist(tag: 'estate') || needReLocation) {
      DialogEngine.showAttach(
        tag: 'estate',
        targetContext: _targetContext!,
        position: DialogPosition.bottom,
        widget: AttachSearchDialog(
          onSelected: (item) {
            state = state.copyWith(selectedEstate: item);
            final TextEditingController controller = state.formData['estate']!['controller'];
            controller.text = item?.name ?? "";
          },
        ),
      );
    }
  }

  /// 保存第二步的单元等信息
  void saveUnit({required String? address, required String? unitId}) {
    state = state.copyWith(address: address,unitId: unitId);
  }

  /// 保存第三步的角色信息
  void saveRoleType({required String type}) {
    state = state.copyWith(type: type);
  }
}
