import 'package:auto_route/src/route/page_route_info.dart';
import 'package:cpt_property/modules/ioan/property_ioan_page.dart';
import 'package:cpt_property/respository/property_resposity.dart';
import 'package:cpt_property/router/page/property_page_router.dart';
import 'package:domain/entity/property_news_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:plugin_platform/http/http_result.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:plugin_platform/engine/toast/toast_engine.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';
import '../../news_detail/property_news_detail_page.dart';
import '../../property/page/property_page.dart';
import '../page/property_news_state.dart';

part 'property_news_vm.g.dart';

@riverpod
class PropertyNewsVm extends _$PropertyNewsVm {
  late PropertyRespository propertyRespositoryInstance;

  bool _needShowPlaceholder = false; //是否展示LoadingView
  int _page = 1;  // 当前页
  int _limit = 10; // 每页数量
  int _count = 0; // 总条数

  Map<String, dynamic> _newsQueryMap = {
    "isCollection": 0,  //  0  未收藏，1 已收藏
  };

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

  PropertyNewsState initState() {
    return PropertyNewsState(
      list: [],
    );
  }

  @override
  PropertyNewsState build() {
    // 引入数据仓库
    propertyRespositoryInstance = ref.read(propertyRespositoryProvider);
    // 初始化状态
    PropertyNewsState state = initState();
    // 初始化列表数据
    return state;
  }

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

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

  // 上拉加载 更多
  Future loadMore() async {
    Log.d("----property_news_vm-----loadMore");
    // await Future.delayed(const Duration(seconds: 2));
    // if(state.list.length >= _count){
    //   return;
    // }else {
    //   int page = _page + 1;
    //   state = state.copyWith(page: page,);
    //   getListData();
    // }
    // 检查 page 是否为 null，并初始化为 1
    _page++;
    getListData();
  }


  // 下拉刷新
  Future onRefresh() async {
    Log.d("----property_news_vm-----onRefresh ");

    // await Future.delayed(const Duration(seconds: 2));
    _page = 1;
    getListData();
  }

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

    getListData();
  }


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

    Log.d("加载listData数据---------------start--${_page}---");
    try {
      //请求网络
      Map<String, dynamic>  params = {
        "isCollection": _newsQueryMap['isCollection'],
        "page": _page,
        "limit": _limit,
      };
      Log.d("请求参数------$params");
      final result = await propertyRespositoryInstance.fetchNewsList(params);
      //校验成功失败
      if (result.isSuccess) {
        handlerResultList((result.data  as PropertyNewsEntity).list);
      } else {
        String errorMessage = result.errorMsg!;
        changeLoadingState(LoadState.State_Error, errorMessage);
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }
    } catch (e) {
      ToastEngine.show("Error: $e");
    }


    // await Future.delayed(const Duration(milliseconds: 1500));
    // final List<Map<String, dynamic>> listData = [
    //   {
    //     "id": 1,
    //     "title": "法国进口高档国家的看过艰苦奋斗是感觉扣税的房价过快岁的法国艰苦奋斗是架构开发更加开放的国际法的是",
    //     "description": "fsklfdsk罚款乱收费上课了发送卡fsklfdsk罚款乱收费上课了发送卡fsklfdsk罚款乱收费上课了发送卡fsklfdsk罚款乱收费上课了发送卡fsklfdsk罚款乱收费上课了发送卡",
    //     "time": "2024-02-15 12:00:00",
    //     "isCollection": true,
    //     "pic": "https://img1.baidu.com/it/u=2500825327,873404587&fm=253&fmt=auto&app=138&f=JPEG?w=750&h=500"
    //   },
    //   {
    //     "id": 2,
    //     "title": "JHKFDSAJKjfkdsfjkasjkjklfajfkajifwoqirujweiqofjndsaikfniasdhfiasdhfiadshfifjadslfjkdlsafjlkadsj",
    //     "description": "oifosjf fjdskafj hjiwehfriohjfiash",
    //     "time": "2024-10-16 12:00:00",
    //     "isCollection": false,
    //     "pic": ""
    //   },
    // ];
    //
    // if (_page == 1) {
    //   //刷新的方式
    //   state = state.copyWith(list: listData);
    //   refreshController.finishRefresh();
    //   //更新展示的状态
    //   changeLoadingState(LoadState.State_Success, null);
    // } else {
    //   //加载更多
    //   final allList = state.list;
    //   if(allList.length >= _count! * _limit!){
    //     //更新展示的状态
    //     changeLoadingState(LoadState.State_Success, null);
    //     refreshController.finishLoad(IndicatorResult.noMore);
    //   }else {
    //     allList.addAll(listData);
    //     state = state.copyWith(list: allList);
    //     refreshController.finishLoad();
    //   }
    // }
    // // 最后赋值
    // _needShowPlaceholder = false;
  }

  void handlerResultList(List<PropertyNewsList>? list) {
    if (list != null && list.isNotEmpty) {
      //有数据，判断是刷新还是加载更多的数据
      if (_page == 1) {
        //刷新的方式
        state.list!.clear();
        state.list!.addAll(list.map((item)=> item.toJson()).toList());
        refreshController.finishRefresh();

        //更新展示的状态
        changeLoadingState(LoadState.State_Success, null);
      } else {
        //加载更多
        final allList = state.list;
        state = state.copyWith(list: allList);
        refreshController.finishLoad();
        // update();
      }
    } else {
      if (_page == 1) {
        //展示无数据的布局
        state.list!.clear();
        changeLoadingState(LoadState.State_Empty, null);
        refreshController.finishRefresh();
      } else {
        //展示加载完成，没有更多数据了
        if(state.list!.length == 0){
          changeLoadingState(LoadState.State_Empty, null);
          refreshController.finishLoad();
        }else {
          if(_needShowPlaceholder){
            changeLoadingState(LoadState.State_Success, null);
          }
        }
        //更新展示的状态
        refreshController.finishLoad(IndicatorResult.noMore);
      }
    }
  }


  // 去新闻详情页
  void goNewsDetailPage(BuildContext? context, int id) {
    Log.d("goNewsDetail");
    PropertyNewsDetailPage.startInstance(context: context, id: id,);
  }

  // 收藏/取消收藏
  void handlerCollection(curItem, bool liked) async {
    try {
      Map<String, dynamic> params = {
        "id": curItem['id'],
      };
      final result = await propertyRespositoryInstance.fetchPropertyNewsLikeClick(params);
      //校验成功失败
      if (result.isSuccess) {
        List<Map<String, dynamic>>? newList = state.list?.map((item) {
          if(item['id'] == curItem['id']){
            return {
              ...item,
              'liked': !liked
            };
          }
          return item;
        }).toList();
        // Log.d("handlerCollection $newList");
        state = state.copyWith(list: newList);
        if(liked){
          ToastEngine.show("取消收藏");
        }else {
          ToastEngine.show("收藏成功");
        }
      } else {
        String errorMessage = result.errorMsg!;
        ToastEngine.show(errorMessage ?? "Network Load Error");
      }

    } catch (e) {
      ToastEngine.show("Error: $e");
    }
  }


  changeQueryMap(Map<String, dynamic> queryMap){
    _newsQueryMap = { ..._newsQueryMap, ...queryMap};
  }

}
