
import 'package:cpt_community/modules/community/following/following_vm.dart';
import 'package:cpt_community/modules/community/foryou/foryou_vm.dart';
import 'package:cpt_community/modules/my_posts/my_posts_newsfeed/my_posts_newsfeed_vm.dart';
import 'package:cpt_community/respository/common_newsfeed.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:domain/entity/newsfeed_detail_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:plugin_basic/provider/user_config/user_config_service.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/color_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/ext/ex_widget.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/my_text_view.dart';
import 'package:widgets/widget_export.dart';
import '../../../components/comments_dialog.dart';

import '../news/news_vm.dart';
import 'comments_input.dart';
import 'newsfeed_detail_state.dart';
import 'newsfeed_detail_page.dart';

part 'newsfeed_detail_vm.g.dart';


@riverpod
class NewsfeedDetailVm extends _$NewsfeedDetailVm {
  late CommonNewsFeedRespository repositoryInstance;

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

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

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

  int? _detailId;
  String? _detailType = 'news';  // news  following foryou  mypostsNews


  NewsfeedDetailState initState() {
    return NewsfeedDetailState();
  }


  @override
  NewsfeedDetailState build(){
    // 引入数据仓库
    repositoryInstance = ref.read(commonNewsFeedRespositoryProvider);
    final state = initState();
    // 第一次挂载后
    // WidgetsBinding.instance!.addPostFrameCallback((_) {
    // }

    // Log.d("---------444-----------------build---------------${state.detailInfo}------");
    return state;
  }

  setCurrentDetailType(String detailPageType){
    Log.d("设置当前页面类型---------$detailPageType");
    _detailType = detailPageType;
  }

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

  // 初始化页面数据
  initPageData({int? id, String? type}) {
    Log.d("----property_news_vm-----initPageData   ${state.loadingState}");
    _detailId = id ?? _detailId;
    if(type != null){
      setCurrentDetailType(type);
    }

    onRefresh(id: _detailId, type: type);
  }

  // 上拉加载 更多
  Future loadMore({int? id, String? type}) async {
    Log.d("----property_news_vm-----loadMore");
    // _page++;
    // getListData(id:id, type:type);
    getDetailInfo(id:_detailId, type:_detailType, isRefresh: false);
    // refreshController.finishLoad();
  }


  // 下拉刷新
  Future onRefresh({int? id, String? type}) async {
    Log.d("----property_news_vm-----onRefresh ");

    // await Future.delayed(const Duration(seconds: 2));
    _page = 1;
    getDetailInfo(id:id, type:type);
  }

  // 重试请求
  Future retryRequest({int? id, String? type}) async {
    state = state.copyWith(page: 1);
    _needShowPlaceholder = true;
    getListData(id:id, type:type);
  }

  // 获取详情信息
  Future getDetailInfo<T>({int? id, String? type, bool isRefresh = true}) async {
    try{
      if (_needShowPlaceholder) {
        changeLoadingState(LoadState.State_Loading, null);
      }
      Map<String, dynamic> params = {
        'id': id,
      };
      final result = await repositoryInstance.fetchNewsFeedDetailInfo(params);
      if(result.isSuccess){

        state = state.copyWith(
          detailInfo: result.data as NewsfeedDetailEntity,
        );

        changeLoadingState(LoadState.State_Success, null);
        if(isRefresh){
          refreshController.finishRefresh();
        }else {
          refreshController.finishLoad(IndicatorResult.noMore);
        }
      }else {
        String errorMessage = result.errorMsg!;
        changeLoadingState(LoadState.State_Error, errorMessage);
        ToastEngine.show(result.errorMsg ?? "Network Load Error");
      }

      _needShowPlaceholder = false;
    }catch(error){

    }
  }


  // 获取list 列表数据
  Future getListData<T>({int? id, String? type}) async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading, null);
    }
    Log.d("加载listData数据---------------start--$_page---");
    //   try {
    //     //请求网络
    //     Map<String, dynamic>  params = {
    //       "page": _page,
    //       "limit": _limit,
    //     };
    //     Log.d("请求参数------$params");
    //     final result = await propertyNewsRepository.fetchPropertyNewsList(params);
    //     Log.d("请求完成结果------${result.data}");
    //     //校验成功失败
    //     if (result.isSuccess) {
    //       // state = state.copyWith(serverTime: result.data);
    //       state = state;
    //   handleList(listResult.data?.rows);
    //       ToastEngine.show("获取数据成功");
    //     } else {
    //   errorMessage = listResult.errorMsg;
    //   changeLoadingState(LoadState.State_Error);
    //       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 = [
    //   {
    //     'userId': 1,
    //     'userName': 'William Jefferson',
    //     'avator': 'https://img1.baidu.com/it/u=3890726495,1572750319&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=500',
    //     'time': 'June 17,2016 at 7:23 p.m.',
    //     'content': 'She said YES and our lives changed.Thank you all for coming to my propose today.We hope everyone can ……[More]'
    //   },
    //   {
    //     'userId': 2,
    //     'userName': 'Ander Jackson',
    //     'avator': 'https://iknow-pic.cdn.bcebos.com/d439b6003af33a87f27f0584d45c10385343b519',
    //     'time': 'June 17,2016 at 7:23 p.m.',
    //     'content': 'She said YES and our lives changed.Thank you all for coming to my propose today.We hope everyone can ……[More]'
    //   },
    // ];


    // if (_page == 1) {
    //   //刷新的方式
    //   state = state.copyWith(list: listData);
    //   refreshController.finishRefresh();
    //   // //更新展示的状态
    //   changeLoadingState(LoadState.State_Success, null);
    // } else {
    //   //加载更多
    //   final allList = state.list;
    //   allList.addAll(listData);
    //   refreshController.finishLoad();
    //   state = state.copyWith(list: allList);
    // }
    //
    // // 最后赋值
    // _needShowPlaceholder = false;

    await Future.delayed(const Duration(milliseconds: 1500));
    refreshController.finishLoad();
  }

  // 点击了 关注/取消关注按钮
  Future<bool> handlerFollow(BuildContext? context, int to_user_id,int cardId, bool isFollow) async{
    Log.d("newsfeed_detail_vm 中 当前的 _detailType $_detailType to_user_id:$to_user_id cardId:$cardId isFollow:$isFollow  点击了 关注/取消关注");
    bool result = false;
    if(_detailType == 'news'){
      Log.d("调用 newvm 中的关注/取消关注方法");
      // 调用列表中的 点赞方法
      final newsfeedVm = ref.read(newsVmProvider.notifier);
      result = await newsfeedVm.handlerFollow(context, to_user_id, cardId, isFollow);
    }else if(_detailType == 'following'){
      Log.d("调用 followingVm 中的关注/取消关注方法");
      // 调用列表中的 点赞方法
      final followingVm = ref.read(followingVmProvider.notifier);
      result = await followingVm.handlerFollow(context, to_user_id, cardId, isFollow);
    }else if(_detailType == 'foryou'){
      Log.d("调用 forYouVm 中的关注/取消关注方法");
      // 调用列表中的 点赞方法
      final forYouVm = ref.read(foryouVmProvider.notifier);
      result = await forYouVm.handlerFollow(context, to_user_id, cardId, isFollow);
    }else if(_detailType == 'mypostsNews'){
      Log.d("调用 mypostsNews 中的关注/取消关注方法");
      // 调用列表中的 点赞方法
      final myPostsNewsVm = ref.read(myPostsNewsfeedVmProvider.notifier);
      result = await myPostsNewsVm.handlerFollow(context, to_user_id, cardId, isFollow);
    }

    if(result){
      // 成功了
      // 修改cardId 对应的 card item 的 account 里面的 followed
      if(cardId!=null){
        NewsfeedDetailEntity detailInfoDta = state.detailInfo!;
        NewsfeedDetailAccount card_account = detailInfoDta!.account?? NewsfeedDetailAccount();
        card_account.followed = !(card_account!.followed?? false);
        state = state.copyWith(detailInfo: detailInfoDta);
      }

      // 同步用户信息
      UserConfigService.getInstance().refreshUserInfo();
    }
    return result;
  }

  // 点击了 评论 按钮
  handlerCommentClick(BuildContext context, int newsfeedId, int to_user_id, String to_user_name, bool isReply ) async{
    Log.d("点击了评论按钮 newsfeedId:  $newsfeedId  to_user_id:  $to_user_id  to_user_name:  $to_user_name  isReply:  $isReply ");

    String hintText = S.current.enter_comment;
    if(isReply){
      hintText = 'Reply to $to_user_name: ';
      // 修改对话框的 提示文字
    }else {
      to_user_id = 0; // 评论对象ID(默认传0)
      String hintText = S.current.enter_comment;
    }
    state = state.copyWith(commentFieldInfo: {
      'value': '',
      'controller': TextEditingController(),
      'hintText': hintText,
      'focusNode': FocusNode(),
      'obsecure': false,
    });

    BuildContext contextPage = context;
    // double height = MediaQuery.of(contextPage).size.height;
    double commentInputHeight = 150.0;
    await DialogEngine.show(
      tag: "newsFeedComments",
      position: DialogPosition.bottom,
      widget: CommentsDialog(
        isShowConfirmBtn: false,
        isShowCancelBtn: false,
        height: commentInputHeight,
        confirmAction: (){},
        cancelAction: null,
        messageBuilder: (context) {
          return Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Expanded(
                  child: Container(
                    margin: const EdgeInsets.only(left:15, right:15,top: 20, bottom: 20),
                    width: double.infinity,
                    height: commentInputHeight,
                    padding: const EdgeInsets.all(15),
                    decoration: BoxDecoration(
                        color: context.appColors.backgroundDark,
                        borderRadius: BorderRadius.circular(5),
                        boxShadow: [
                          BoxShadow(
                            color: Colors.grey.withOpacity(0.1),
                            spreadRadius:1,
                            blurRadius: 1,
                            offset: const Offset(0.5, 0.5), // changes position of shadow
                          ),
                        ]
                    ),
                    child: CommentsTextareaInput( showCounter:false, autoFocus: true),
                  ),
              ),
              Container(
                margin: const EdgeInsets.only(right: 10),
                height: commentInputHeight,
                decoration: BoxDecoration(
                  color: context.appColors.textPrimary,
                  borderRadius: BorderRadius.circular(5),
                ),
                child: Center(
                  child: IconButton(
                    icon: Icon(Icons.send, color: context.appColors.textWhite, size: 25,),
                    onPressed: null,
                  ),
                ),
              ).onTap(() async{
                Log.d("点击了发送按钮");
                // 收起键盘
                handlerKeyboardShowHide(false);
                // 获取评论内容
                String commentContent = getCommentContent()??'';
                bool asyncResult = await handlerSubmitComment(context: context, newsfeedId: newsfeedId, to_user_id: to_user_id, commentContent: commentContent);
                if(asyncResult){
                  // 成功后 需要 清理输入框以及关闭 同时收起键盘 同时 刷新评论数据
                  resetCommentField();
                  DialogEngine.dismiss(tag: "newsFeedComments");
                  // 刷新评论数据
                  handlerSetCommentsList();
                }
              }),
            ]
          );
        },
      ),
    );
  }

  // 刷新评论列表
  handlerSetCommentsList(){
    onRefresh(id:_detailId,type: _detailType);
  }

  // 提交评论
  Future<bool> handlerSubmitComment({BuildContext? context, required int newsfeedId, int? to_user_id = 0, required String commentContent} ) async{
    Log.d("点击提交评论 newsfeedId: $newsfeedId  to_user_id: $to_user_id  commentContent； $commentContent");
    try{
      Map<String, dynamic> params = {
        "id": newsfeedId,
        "content": commentContent,
        "to_user_id": to_user_id,
      };
      final result = await repositoryInstance.fetchNewsfeedCommentSubmit(params);
      if(result.isSuccess){
        // 成功后 需要 清理输入框以及关闭 同时收起键盘 同时 刷新评论数据
        return true;
      }else {
        return false;
      }
    }catch(error){
      return false;
    }
  }

  // 点击了 Like 按钮
  Future<bool> handlerLikeClick(BuildContext? context, int id,  bool isLike) async{
    Log.d("newsfeed_detail_vm 中 当前的 _detailType $_detailType 点击了点赞按钮 id:$id  isLike: $isLike");

    bool result = false;
    if(_detailType == 'news'){
      Log.d("调用 newvm 中的点赞方法");
      // 调用列表中的 点赞方法
      final newsfeedVm = ref.read(newsVmProvider.notifier);
      result = await newsfeedVm.handlerLikeClick(id, isLike, null);
    }else if(_detailType == 'following'){
      Log.d("调用 followingVm 中的点赞方法");
      // 调用列表中的 点赞方法
      final followingVm = ref.read(followingVmProvider.notifier);
      result = await followingVm.handlerLikeClick(id, isLike, null);
    }else if(_detailType == 'foryou'){
      Log.d("调用 forYouVm 中的点赞方法");
      // 调用列表中的 点赞方法
      final forYouVm = ref.read(foryouVmProvider.notifier);
      result = await forYouVm.handlerLikeClick(id, isLike, null);
    }else if(_detailType == 'mypostsNews'){
      Log.d("调用 myPostsVm 中的点赞方法");
      // 调用列表中的 点赞方法
      final myPostsVm = ref.read(myPostsNewsfeedVmProvider.notifier);
      result = await myPostsVm.handlerLikeClick(id, isLike, null, null);
    }

    if(result){
      // 成功了
      // 修改 comments 数量 和 收藏数
      NewsfeedDetailEntity detailInfoCopy = state.detailInfo!;
      int likeCount = detailInfoCopy!.likesCount??0;
      bool liked = detailInfoCopy!.liked??false;
      // List<NewsfeedDetailComments>? commentList = detailInfoCopy!.comments;
      // num commentCount = commentList?.length?? 0;
      detailInfoCopy!.liked = !liked;
      if(isLike){
        detailInfoCopy!.likesCount = likeCount - 1;
      }else{
        detailInfoCopy!.likesCount = likeCount + 1;
      }
      state = state.copyWith(detailInfo: detailInfoCopy);
    }

    return result;
  }

  // 隐藏/显示 键盘
  void handlerKeyboardShowHide(bool show){
    Log.d("点击了键盘显示/隐藏");
    if(show){
      state.commentFieldInfo?['focusNode']?.focus();
    }else {
      state.commentFieldInfo?['focusNode']?.unfocus();
    }
  }
  // 获取评论内容
  String getCommentContent(){
    Log.d("评论框的内容 ${state.commentFieldInfo!['controller']?.text??''}");
    return state.commentFieldInfo!['controller']?.text??'';
  }

  // 清空评论
  resetCommentField(){
    state.commentFieldInfo!['controller']!.clear();
  }
}

