import 'package:domain/repository/profile_repository.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_basic/provider/user_config/user_config_service.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/event_bus.dart';
import 'package:shared/utils/log_utils.dart';

import '../estate_upload_success/estate_upload_success_page.dart';
import '../select_estate/select_estate_state.dart';
import '../select_estate/select_estate_view_model.dart';
import 'tenant_doc_state.dart';

part 'tenant_doc_view_model.g.dart';

@riverpod
class TenantDocViewModel extends _$TenantDocViewModel {
  late final ProfileRepository _profileRepository;
  late final SelectEstateState _selectEstateState;

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

    return TenantDocState(docList: [], type: _selectEstateState.type ?? "1");
  }

  //设置已选中的文件数组
  void setDocList(List<String> list) {
    state = state.copyWith(docList: list);
  }

  //提交文件
  void submitDoc() async {
    if (state.docList.isEmpty) {
      ToastEngine.show("Select Documents First");
      return;
    }

    final result = await _profileRepository.joinEstateUnit(
      unitId: _selectEstateState.unitId,
      type: _selectEstateState.type,
      paths: state.docList,
    );

    if (result.isSuccess) {
      final data = result.data;
      final String? sm = data?.sn;
      final String? contactNumber = data?.estate?.information?.contactNumber;
      final String? email = data?.estate?.information?.email;
      //如果有用户信息，说明是在Me页面添加的
      if (UserConfigService.getState().user != null) {
        //刷新Estate页面
        bus.emit(AppConstant.eventEstateRefresh, true);
        //去成功页面
        Log.d("Estate页面");
        EstateUploadSuccessPage.startPop2Estate(sm: sm, contactNumber: contactNumber, email: email);
      } else {
        Log.d("登录页面");
        //如果没有用户信息，说明是在登录页面添加的。
        EstateUploadSuccessPage.startPop2Login(sm: sm, contactNumber: contactNumber, email: email);
      }
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }
}
