
import 'dart:async';

import 'package:cpt_services/constants_services.dart';
import 'package:cpt_services/modules/services/repair/repair_page.dart';
import 'package:cpt_services/modules/services/services_page.dart';
import 'package:domain/entity/service_category_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.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/ext_dart.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/widget_export.dart';
import 'package:widgets/dialog/dialog_content_wrap.dart';
import '../../../respository/services_respository.dart';
import '../../../router/page/services_page_router.dart';
import 'services_main_page.dart';
import 'services_main_state.dart';

part 'services_main_vm.g.dart';


@riverpod
class ServiceMainVm extends _$ServiceMainVm {
  late ServicesRespository serviceRespositoryInstance;

  int _detailId = 0;
  int _detailServiceTypeCode = 0;

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

  int _page = 1;  // 当前页
  int _limit = 10; // 每页数量
  int _count = 0; // 总条数

  int _totalnum = 130;

  int totalnum = 50;

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

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

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

    return state;
  }


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


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

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


  // 下拉刷新
  Future onRefresh() async {
    _page = 1;
    getServicesData();
  }


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

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


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


  Future getServicesData<T>() async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading, null);
    }

    try {
      Map<String, dynamic> params = {
        "parent_id": '',
      };
      final result = await serviceRespositoryInstance.fetchServiceCateGoryList(params);
      if(result.isSuccess){
        state = state.copyWith(datas: result.list as List<ServiceCategoryEntity>);
        changeLoadingState(LoadState.State_Success, null);
        refreshController.finishRefresh();
      } 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;
  }
  
  // 去付费服务/维修服务  列表页
  goToPaidOrRepairListPage(BuildContext context, int id, String type, ServiceCategoryEntity entity){
    state = state.copyWith(
        curCategory: entity
    );
    if(id == servicesConstants.servicesType[1]?['id']){
      ServicesPage.startInstance(parentCategoryId: id);
    }else if(id == servicesConstants.servicesType[4]?['id']){
      RepairPage.startInstance(parentCategoryId: id);
    }else {
      ToastEngine.show("暂未开放");
    }
  }
}
