
import 'package:cs_resources/generated/assets.dart';
import 'package:domain/entity/garage_sale_rent_entity.dart';
import 'package:domain/entity/newsfeed_detail_entity.dart';
import 'package:domain/entity/paid_service_detail_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:plugin_platform/engine/loading/loading_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:router/ext/auto_router_extensions.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 'service_pay_success_state.dart';

part 'service_pay_success_vm.g.dart';

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


  int? _id;

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

  ServicePaySuccessState initState() {
    return ServicePaySuccessState(
        datas: null,
    );
  }

  @override
  ServicePaySuccessState build(){
    // 引入数据仓库
    // servicesRespositoryInstance = ref.read(commonGarageRespositoryProvider);
    servicesRespositoryInstance = ref.read(servicesRespositoryProvider);
    final state = initState();
    Log.d("--------------------------build---------------------");

    return state;
  }


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

  setInitPageData({required int id,}){
    _id = id;
  }

  // 初始化页面数据
  initPageData(BuildContext context) {
    Log.d("--------------------------initPageData---------------------");
    changeLoadingState(LoadState.State_Success, null);
    // WidgetsBinding.instance.addPostFrameCallback((_){
    // });
  }

  // 上拉加载 更多
  Future loadMore() async {
    _page++;
    getListData();
  }


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


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

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

    List<Map<String, dynamic>> list = [
      {
        'id':1,
        'service_type': 0,  // 0 房屋保洁 1 空调保洁  2 维修
        'cover_img':  'https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500',
        'resources': ['https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500'],
        'title': 'House Cleaning Services',
        'duration': 'Daily cleaning for 2 hours',
        'totalPrice': 66,
        'visit_time': '14 0ct 2024 15:00',
        'order_time': '13 0ct 2024 12:00',
        'status_text': 'In Progress',
        'status_code': 0,
        'company_name': 'HONG YE GROUP PTE LTD',
      },
      {
        'id':2,
        'service_type': 0,  // 0 房屋保洁 1 空调保洁  2 维修
        'cover_img':  'https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500',
        'resources': ['https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500'],
        'title': 'House Cleaning Services',
        'duration': 'Daily cleaning for 2 hours',
        'totalPrice': 66,
        'visit_time': '14 0ct 2024 15:00',
        'order_time': '13 0ct 2024 12:00',
        'status_text': 'In Progress',
        'status_code': 1,
        'company_name': 'HONG YE GROUP PTE LTD',
      },
      {
        'id':3,
        'service_type': 0,  // 0 房屋保洁 1 空调保洁  2 维修
        'cover_img':  'https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500',
        'resources': ['https://img2.baidu.com/it/u=3489233687,2364672159&fm=253&fmt=auto&app=120&f=JPEG?w=507&h=500'],
        'title': 'House Cleaning Services',
        'duration': 'Daily cleaning for 2 hours',
        'totalPrice': 66,
        'visit_time': '14 0ct 2024 15:00',
        'order_time': '13 0ct 2024 12:00',
        'status_text': 'In Progress',
        'status_code': 1,
        'company_name': 'HONG YE GROUP PTE LTD',
      },
    ];
    handlerResultData(true, list:list);

    // try {
    //   //请求网络
    //   Map<String, dynamic>  params = {
    //     "type": 1,  // 类型(1=Sale,2=Rent)
    //     "category_id": _queryParams['category_id'],
    //     "keyword": _queryParams['keyword'],
    //     "page": _page,
    //     "limit": _limit,
    //   };
    //   Log.d("请求参数------$params");
    //   final result = await servicesRespositoryInstance.fetchGarageDataList(params);
    //   //校验成功失败
    //   if (result.isSuccess) {
    //     // handlerResultList((result.data as GarageSaleRentEntity).list as List<GarageSaleRentList>, isLoadMore ?? false);
    //   } else {
    //     String errorMessage = result.errorMsg!;
    //     changeLoadingState(LoadState.State_Error, errorMessage);
    //     ToastEngine.show(result.errorMsg ?? "Network Load Error");
    //   }
    // } catch (e) {
    //   ToastEngine.show("Error: $e");
    // }

    // 最后赋值
    _needShowPlaceholder = false;

  }

  handlerResultData(bool isList, {List<Map<String, dynamic>>? list, dynamic? data}){
    Future.delayed(const Duration(seconds: 1)).then((value) {
      if(isList){
        // list 数据模式
        // if(list != null && list.isNotEmpty){
        //   if(_page == 1){
        //     state.list.clear();
        //     state.list!.addAll(list);
        //     refreshController.finishRefresh();
        //     changeLoadingState(LoadState.State_Success, null);
        //   }else {
        //     final allList = state.list;
        //     allList!.addAll(list);
        //     state = state.copyWith(list: allList);
        //     refreshController.finishLoad();
        //   }
        // }else {
        //   if(_page == 1){
        //     state.list.clear();
        //     changeLoadingState(LoadState.State_Empty, null);
        //     refreshController.finishRefresh();
        //   }else {
        //     refreshController.finishLoad(IndicatorResult.noMore);
        //   }
        // }
      }else {
        // 单个数据模式
        if(data!=null){
          if(_page == 1){
            refreshController.finishRefresh();
          }else{
            refreshController.finishLoad();
          }
          changeLoadingState(LoadState.State_Success, null);
        }else {
          if(_page == 1){
            refreshController.finishRefresh();
          }else{
            refreshController.finishLoad();
          }
          changeLoadingState(LoadState.State_Empty, null);
        }
      }
    });
  }

  //获取订单详情数据
  fetchOrderDetailData(int id) async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading, null);
    }
    // LoadingEngine.show();
    // 延迟获取数据
    // await Future.delayed(const Duration(milliseconds: 2000));
    final result = await servicesRespositoryInstance.fetchPaidServiceCleanOrderDetail(id: id.toString());
    // LoadingEngine.dismiss();
    if (result.isSuccess) {
      state = state.copyWith(datas: result.data );
      changeLoadingState(LoadState.State_Success, null);
    } else {
      changeLoadingState(LoadState.State_Error, result.errorMsg ?? "UnKnow Error");
    }
  }
}