import 'package:cpt_profile/modules/my_estate/dialog/remove_account_dialog.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:domain/entity/user_me_entity.dart';
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/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/notify/notify_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/event_bus.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import 'my_estate_state.dart';

part 'my_estate_view_model.g.dart';

@riverpod
class MyEstateViewModel extends _$MyEstateViewModel with DioCancelableMixin {
  late final ProfileRepository _profileRepository;

  @override
  MyEstateState build() {
    _profileRepository = ref.read(profileRepositoryProvider);
    final state = MyEstateState(datas: []);

    onInit();
    registerCancellation(callback: () {
      unregisterEventBus();
    });
    return state;
  }

  var _needShowPlaceholder = true; //是否展示LoadingView

  // Refresh 控制器
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishRefresh: true, //允许刷新
    controlFinishLoad: false, //允许加载
  );

  //刷新页面状态
  void changeLoadingState(LoadState loadState, String? errorMsg) {
    state = state.copyWith(loadingState: loadState, errorMessage: errorMsg);
  }

  // Refresh 刷新事件
  Future onRefresh() async {
    fetchList();
  }

  // 重试请求
  Future retryRequest() async {
    _needShowPlaceholder = true;
    fetchList();
  }

  /// 获取服务器数据
  Future fetchList() async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading, null);
    }

    // 获取 Applied 列表
    var result = await _profileRepository.fetchUserInfo(
      cancelToken: cancelToken,
    );

    // 处理数据
    if (result.isSuccess) {
      handleList(result.data?.estates);
    } else {
      changeLoadingState(LoadState.State_Error, result.errorMsg);
    }

    // 最后赋值
    _needShowPlaceholder = false;
  }

  // 处理数据与展示的逻辑
  void handleList(List<UserMeEstates>? list) {
    if (list != null && list.isNotEmpty) {
      //有数据
      state = state.copyWith(datas: list, loadingState: LoadState.State_Success);
    } else {
      //展示无数据的布局
      state = state.copyWith(datas: [], loadingState: LoadState.State_Empty, errorMessage: null);
    }

    refreshController.finishRefresh();
  }

  /// 展示移除账号的提示弹窗
  void showRemoveEstateDialog(String? unitId) {
    DialogEngine.show(widget: RemoveAccountDialog(
      confirmAction: () {
        _doDeleteEstateUnit(unitId);
      },
    ));
  }

  // 删除指定的单元
  void _doDeleteEstateUnit(String? unitId) async {
    final result = await _profileRepository.deleteEstateUnit(unitId: unitId, cancelToken: cancelToken);
    if (result.isSuccess) {
      refreshController.callRefresh();
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }

  /// 设置默认的房产单元
  void setEstateUnitDefault(UserMeEstatesAccounts? account) async {
    if (account == null || account.isDefault == 1) {
      //已经是默认的不需要操作了
      return;
    }

    final unitId = account.unit?.id;

    final result = await _profileRepository.setUnitAsDefault(unitId: unitId, cancelToken: cancelToken);

    if (result.isSuccess) {
      NotifyEngine.showSuccess(S.current.successful);

      // 创建一个新的数据列表并更新 isDefault 状态
      List<UserMeEstates> newDatas = state.datas.map((estate) {
        var newEstate = estate.copyWith(
          accounts: estate.accounts?.map((account) {
            return account.copyWith(
              isDefault: account.unit?.id == unitId ? 1 : 0,
            );
          }).toList(),
        );
        return newEstate;
      }).toList();

      //这里需要传入一个新对象啊，而不是上面的state.datas对象
      state = state.copyWith(datas: newDatas);

      //刷新用户的信息
      UserConfigService.getInstance().refreshUserInfo();
    } else {
      ToastEngine.show(result.errorMsg ?? "UnKnow Error");
    }
  }

  //初始化
  void onInit() {
    registerEventBus();
  }

  Subscription? subscribe;

  void registerEventBus() {
    subscribe = bus.on(AppConstant.eventEstateRefresh, (arg) {
      Log.d("收到信息-需要刷新My Estate的列表");
      refreshController.callRefresh();
    });
  }

  void unregisterEventBus() {
    bus.off(AppConstant.eventEstateRefresh, subscribe);
  }
}
