import 'package:cs_resources/generated/assets.dart';
import 'package:domain/entity/garage_sale_history_entity.dart';
import 'package:domain/entity/garage_sale_rent_entity.dart';
import 'package:domain/entity/newsfeed_detail_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:plugin_basic/constants/app_constant.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:router/ext/auto_router_extensions.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 '../../../respository/services_respository.dart';
import '../../../router/page/services_page_router.dart';
import '../clean_order_detail/clean_order_detail_page.dart';
import 'history_state.dart';

part 'history_vm.g.dart';

@riverpod
class HistoryVm extends _$HistoryVm with DioCancelableMixin {
  late ServicesRespository servicesRespositoryInstance;
  bool _needShowPlaceholder = false; //是否展示LoadingView
  int _page = 1; // 当前页
  int _limit = 10; // 每页数量
  int _count = 0; // 总条数

  Map<String, dynamic> _queryParams = {
    'keyword': '',
  };

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

  HistoryState initState() {
    return HistoryState(list: []);
  }

  @override
  HistoryState build() {
    servicesRespositoryInstance = ref.read(servicesRespositoryProvider);
    // 引入数据仓库
    // servicesRespositoryInstance = ref.read(commonGarageRespositoryProvider);
    final state = initState();
    registerEventBus();
    Log.d("--------------------------build---------------------");
    registerCancellation(callback: () {
      unregisterEventBus();
    });

    return state;
  }

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

  // 初始化页面数据
  initPageData() {
    Log.d("----home_service_vm-----initPageData   ${state.loadingState}");
    onRefresh();
  }

  // 上拉加载 更多
  Future loadMore() async {
    Log.d("----home_service_vm-----loadMore");
    _page++;
    getListData();
  }

  // 下拉刷新
  Future onRefresh() async {
    // 当前pageView 页面正处于显示状态
    Log.d("----forsale_vm-----onRefresh ");
    // await Future.delayed(const Duration(seconds: 2));
    _page = 1;
    getListData();
  }

  // 手动进行刷新
  Future triggerRefresh() async {
    Log.d("trggerRefresh");
    refreshController.callRefresh();
  }

  // 手动进行刷新
  Future directRefresh() async {
    state = state.copyWith(list: []);
    // 注意：由于 nestedscrollview 嵌套easyfresh 组件  refreshController.callRefresh() 自动刷新只能滚动顶部但是不会触发下拉刷新，这里调用是 用到了将其滚动到顶部的作用，进而刷新操作主动掉接口
    // https://github.com/xuelongqy/flutter_easy_refresh/issues/692
    refreshController.callRefresh();
    refreshController.resetFooter();
    _page = 1;
    _needShowPlaceholder = true;
    getListData();
  }

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

  // 获取list 列表数据
  Future getListData<T>({bool? isLoadMore}) async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading, null);
    }

    // 获取列表
    var listResult = await servicesRespositoryInstance.fetchPaidServiceOrderList(
      type: "history",
      keyword: _queryParams['keyword']??'',
      curPage: _page,
      limit: _limit,
      cancelToken: cancelToken,
    );

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

    // 最后赋值
    _needShowPlaceholder = false;
  }

  // 处理数据与展示的逻辑
  void handleList(List<GarageSaleHistoryList>? list) {
    if (list != null && list.isNotEmpty) {
      //有数据，判断是刷新还是加载更多的数据
      if (_page == 1) {
        //刷新的方式
        state = state.copyWith(list: list);
        refreshController.finishRefresh();

        //更新展示的状态
        changeLoadingState(LoadState.State_Success, null);
      } else {
        //加载更多
        state.list.addAll(List<GarageSaleHistoryList>.from(state.list)..addAll(list));
        refreshController.finishLoad();
      }
    } else {
      if (_page == 1) {
        //展示无数据的布局
        state = state.copyWith(list: []);
        changeLoadingState(LoadState.State_Empty, null);
        refreshController.finishRefresh();
      } else {
        //展示加载完成，没有更多数据了
        refreshController.finishLoad(IndicatorResult.noMore);
      }
    }
  }

  // 设置当前的 _queryParams
  setCurrentQueryParams(Map<String, dynamic> params) {
    _queryParams.addAll(params);
  }

  // 获取当前的 _queryParams
  Map<String, dynamic> getCurrentQueryParams(String? key) {
    if (key != null && key!.isNotEmpty) {
      return _queryParams[key];
    }
    return _queryParams;
  }

  // EventBus 的事件接收
  Subscription? subscribe;

  void registerEventBus() {
    subscribe = bus.on(AppConstant.eventServiceOrderRefresh, (arg) {
      if (arg is String) {
        final String id = arg;
        Log.d("需要删除的订单id:$id");
        //从页面列表中找到对应的id并删除对应的Item
        final updatedList = state.list.where((element) => element.id != id).toList();
        state = state.copyWith(list: updatedList);
      }
    });
  }

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

  //  去详情页面
  gotoCleanOrderDetailPage(BuildContext context, int id, int? cleanServiceTypeId,) {
    CleanOrderDetailPage.startInstance(id: id, cleanServiceTypeId: cleanServiceTypeId,);
  }
}
