
import 'package:auto_route/src/route/page_route_info.dart';
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:flutter/cupertino.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_evaluate_create_success/evaluate_create_success_page.dart';
import 'service_evaluate_create_state.dart';

part 'service_evaluate_create_vm.g.dart';

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

  int? _id;
  int? _serviceTypeCode;


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


  ServiceEvaluateCreateState initState() {
    return ServiceEvaluateCreateState(
      loadingState: LoadState.State_Success,
      notesErrorText: '',
      formData: {
        'notes': {
          'value': '',
          'controller': TextEditingController(),
          'hintText': '',
          'focusNode': FocusNode(),
          'obsecure': false,
        },
      },
      imgList: [],
    );
  }


  @override
  ServiceEvaluateCreateState build() {
    // 初始化状态
    servicesRespositoryInstance = ref.read(servicesRespositoryProvider);
    ServiceEvaluateCreateState state = initState();

    // 当前渲染完成后执行一次
    WidgetsBinding.instance!.addPostFrameCallback((_) {
      initListener(state);
      ref.onDispose(() {
        onDispose(state);
      });
    });

    return state;
  }


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

  setInitPageData(BuildContext context, {int? id, int? serviceTypeCode,}) {
    _id = id;
    _serviceTypeCode = serviceTypeCode;
  }
  // 初始化页面数据
  initPageData({int? id,}) {
    _id = id;
    // changeLoadingState(LoadState.State_Success, null);

    // 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(datas:null);
    // 注意：由于 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);
    }

    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);
        }
      }
    });
  }


  // 获取聚焦的node
  FocusNode getFocusNode(Map<String, dynamic> formData, String keyStr) {
    return formData![keyStr]!['focusNode'];
  }

  // 取消表单聚焦状态
  void _dismissKeyboard({String? keyStr}) {
    if(keyStr!.isNotEmpty){
      Log.d("FeedbackCreateViewModel 取消单个表单 $keyStr 聚焦状态");
      final FocusNode sigleItemFocusNode = state.formData[keyStr]!['focusNode'];
      sigleItemFocusNode!.unfocus();
    }else {
      Log.d("FeedbackCreateViewModel 取消所有表单聚焦状态");
      // 遍历 formData 的所有表单 然后逐一取消聚焦
      Map<String, dynamic> formData = state.formData;
      for(String key in formData.keys){
        final FocusNode sigleItemFocusNode = formData[key]['focusNode'];
        sigleItemFocusNode!.unfocus();
      }
    }
  }

  // 获取表单的值
  dynamic _getFormFieldValue({List<String>? keys, String? keyStr}) {
    if(keyStr!.isEmpty){
      Log.d("获取指定集合的表单值");
      if(keys!.isNotEmpty){
        // 遍历keys获取指定多个 keys 的表单value
        Map<String, dynamic> resultValueMap = {};
        for (String itemStr in keys!) {
          TextEditingController sigleItemController = state.formData[itemStr]!['controller'];
          resultValueMap[itemStr] = sigleItemController!.text;
        }
        return resultValueMap;
      }
    }else if(keyStr!.isNotEmpty){
      Log.d("获取单个表单值  ${keyStr}");
      // 获取单个表单的value
      final TextEditingController sigleItemController = state.formData[keyStr]!['controller'];
      return sigleItemController!.text;
    }
  }

  ///提交反馈
  Future submitGaragesalePost(BuildContext context, {VoidCallback? sCallback, VoidCallback? fCallback}) async{
    // Log.d("GaragesalePostPageState 提交表单");
    // state = state.copyWith(titleErrorText: null, notesErrorText: null);
    // _dismissKeyboard(keyStr: "");
    //
    // // 获取表单的值
    // String  saleValue= state.saleSelectedOption ?? "";
    // String  categoryValue= state.categorySelectedOption ?? "";
    // int categoryId;
    // String  contactTypeValue= state.contactTypeSelectedOption ?? "";
    //
    // String  titleValue= _getFormFieldValue(keyStr: 'title');
    // String  contactInfoValue= _getFormFieldValue(keyStr: 'contactInfo');
    // String  priceValue= _getFormFieldValue(keyStr: 'price');
    // String  notesValue= _getFormFieldValue(keyStr: 'notes');
    //
    // Log.d('当前待提交的 sale:$saleValue category:$categoryValue contactTypeValue:$contactTypeValue title:$titleValue  contactInfoValue:$contactInfoValue  price:$priceValue  notes:$notesValue  imgList:${state.imgList}');
    //
    //
    // if (Utils.isEmpty(saleValue)) {
    //   ToastEngine.show('Sale is empty');
    //   return;
    // }
    // if (Utils.isEmpty(categoryValue)) {
    //   ToastEngine.show('Category is empty');
    //   return;
    // }else {
    //   // 通过 categoryValue 值 来获取 categoryId
    //   Log.d("_resCategoryOptionsList  $_resCategoryOptionsList");
    //   try {
    //     Map<String, dynamic>? categoryItem = _resCategoryOptionsList.firstWhere((element) => element['name'] == categoryValue, orElse: () => {'id': -1});
    //     categoryId = categoryItem?['id'];
    //   } catch (e) {
    //     Log.d("未找到匹配的 categoryValue: $categoryValue");
    //     ToastEngine.show('Category is invalid');
    //     return;
    //   }
    // }
    // if (Utils.isEmpty(contactTypeValue)) {
    //   ToastEngine.show('ContactType is empty');
    //   return;
    // }
    //
    // if (Utils.isEmpty(titleValue)) {
    //   state = state.copyWith(titleErrorText: 'Title is empty',);
    //   return;
    // }else {
    //   state.titleErrorText = null;
    //   state = state.copyWith(titleErrorText: null);
    // }
    //
    // if (Utils.isEmpty(contactInfoValue)) {
    //   state = state.copyWith(contactInfoErrorText: 'ContactInfo is empty',);
    //   return;
    // }else {
    //   state.contactInfoErrorText = null;
    //   state = state.copyWith(contactInfoErrorText: null);
    // }
    //
    // if (Utils.isEmpty(priceValue)) {
    //   state = state.copyWith(priceErrorText: 'Price is empty',);
    //   return;
    // }else {
    //   // state.priceErrorText = null;
    //   state = state.copyWith(priceErrorText: null);
    // }
    //
    // if (Utils.isEmpty(notesValue)) {
    //   state = state.copyWith(notesErrorText: 'notes is empty');
    //   return;
    // }else {
    //   state = state.copyWith(notesErrorText: null);
    // }
    //
    // String totalContactStr = '';
    // if(contactTypeValue == 'Mobile Phone'){
    //   totalContactStr = 'mobile:$contactInfoValue';
    // }else if(contactTypeValue == 'WhatsApp'){
    //   totalContactStr = 'whatsapp:$contactInfoValue';
    // }else if(contactTypeValue == 'Email'){
    //   totalContactStr = 'email:$contactInfoValue';
    // }
    //
    // // 提交数据
    // final resResult = await handlerSubmitPost(
    //   type: saleValue == 'For Sale'? 1:2,
    //   titleValue: titleValue,
    //   categoryId: categoryId!,
    //   priceValue: priceValue,
    //   notesValue: notesValue,
    //   contactValue: totalContactStr,
    //   imgList: state.imgList,
    // );

    // if(resResult.isSuccess){
      // // 更新用户信息
      // UserConfigService.getInstance().refreshUserInfo();
      //
      // final communitVm = ref.read(communityVmProvider.notifier);
      // communitVm.getCurrentPageViewVm(null).initPageData();
      // // Navigator.pop(context);
      // appRouter.maybePop();
    // }
  }

  // Future<HttpResult<Object>> handlerSubmitPost({
  //   required int type,
  //   required String titleValue,
  //   required int categoryId,
  //   required String priceValue,
  //   required String contactValue,
  //   required String notesValue,
  //   required List imgList,
  // }) async{
  //   final params = <String, dynamic>{
  //     "type": type, // 1 = Sale  2 = Rent
  //     "category_id": categoryId,
  //     "title": titleValue,
  //     "price": priceValue,
  //     "notes": notesValue,
  //     "contact": contactValue,  // string($例如：whatsapp:+8617671757687 或 mobile:+8617671757687)
  //     "resources": imgList,
  //   };
  //   final result =  await commonGarageRespositoryInstance.fetchPublishGarage(params);
  //   return result;
  // }


  //选中图片
  void setImgList(List<String> list) {
    state = state.copyWith(imgList: list);
  }

  //初始化监听
  void initListener(ServiceEvaluateCreateState initState) {

    // 获取表单的焦点节点
    // final FocusNode focusNode = getFocusNode(state.formData, 'title');
    //
    // focusNode.addListener(() {
    //   // 获取焦点的时候清空错误文本
    //   if (focusNode.hasFocus) {
    //     state = state.copyWith(contactInfoErrorText: null, titleErrorText: null, priceErrorText:null, notesErrorText: null);
    //   }
    // });
  }

  //销毁资源
  void onDispose(ServiceEvaluateCreateState initState) {
    // 获取表单的焦点节点
    // final FocusNode focusNode = getFocusNode(state.formData, 'title');
    // final FocusNode focusNodePrice = getFocusNode(state.formData, 'price');
    // focusNode.dispose();
    // focusNodePrice.dispose();

    Log.d("GaragesalePostPageState 销毁 onDispose");
  }

  setScore(BuildContext context, double score){
    state = state.copyWith(score: score);
  }
  setNotes(BuildContext context, String notes){
    state = state.copyWith(notes: notes);
  }
  handlerEvaluateSubmit(BuildContext context,) async {

    if(state.notes == null || state.notes!.isEmpty){
      return ToastEngine.show("Comment is empty");
    }

    if(state.imgList == null || state.imgList!.length  == 0){
      return ToastEngine.show("Picture is empty");
    }

     try {
      //请求网络
      Map<String, dynamic>  params = {
        "order_id": _id,
        "score": state.score??5.0,
        "comment":state.notes,
        "resources": state.imgList,
      };
      Log.d("请求参数------$params");
      final result = await servicesRespositoryInstance.fetchPublishEvaluation(params);
      //校验成功失败
      if (result.isSuccess) {
        Log.d("handlerEvaluateSubmit");
        context.appRouter
            .pushAndPopUntil(const EvaluateCreateSuccessPageRoute(),
                predicate: (Route<dynamic> route) {
          // 根据具体条件返回 true 或 false
          // Log.d("888 ${route.settings}");
          return route.settings.name != 'ServiceEvaluateCreatePageRoute';
        });
      } else {
        String errorMessage = result.errorMsg!;
        changeLoadingState(LoadState.State_Error, errorMessage);
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }
    } catch (e) {
      ToastEngine.show("Error: $e");
    }
    
  }
}