
import 'package:cpt_community/respository/common_newsfeed.dart';
import 'package:cs_resources/generated/assets.dart';
import 'package:cs_resources/generated/l10n.dart';
import 'package:flutter/material.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_basic/provider/user_config/user_config_service.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:router/path/router_path.dart';
import 'package:shared/utils/color_utils.dart';
import 'package:shared/utils/event_bus.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:auto_route/auto_route.dart';
import 'package:shared/utils/util.dart';


import '../community_vm.dart';
import 'newsfeed_post_page_state.dart';

part 'newsfeed_post_vm.g.dart';

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

  NewsfeedPostPageState initState() {
    return NewsfeedPostPageState(
        mindFieldErrorText: null,
        formData: {
          'mind': {
            'value': '',
            'controller': TextEditingController(),
            'hintText': S.current.what_on_your_mind,
            'focusNode': FocusNode(),
            'obsecure': false,
          }
        },
        imgList: [],
    );
  }

  @override
  NewsfeedPostPageState build() {
    // 引入数据仓库
    repositoryInstance = ref.read(commonNewsFeedRespositoryProvider);
    // 初始化状态
    NewsfeedPostPageState state = initState();

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

    return state;
  }

  // //选择选项
  // void pickCategory() {
  //   _dismissKeyboard();
  //
  //   OptionPickerUtil.showCupertinoOptionPicker(
  //     items: state.optionList,
  //     initialSelectIndex: 0,
  //     onPickerChanged: (_, index) {
  //       state = state.copyWith(selectedOption: state.optionList[index]);
  //     },
  //   );
  // }

  // 获取聚焦的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){
      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){
      // 获取单个表单的value
      final TextEditingController sigleItemController = state.formData[keyStr]!['controller'];
      return sigleItemController.text;
    }
  }

  ///newsfeed 发布提交
  Future submitNewsfeedPost(BuildContext? context, {VoidCallback? sCallback, VoidCallback? fCallback}) async {
    state = state.copyWith(mindFieldErrorText: null);

    _dismissKeyboard(keyStr: 'mind');

    // 获取表单的值
    String mindValue = _getFormFieldValue(keyStr: 'mind');

    Log.d('当前待提交的 mind:$mindValue  imgList:${state.imgList}');


    if (Utils.isEmpty(mindValue)) {
      state = state.copyWith(mindFieldErrorText: "Mind cannot be empty!");
      ToastEngine.show("${state.mindFieldErrorText}");
      return false;
    }

    if(state.imgList.isEmpty){
      ToastEngine.show("ImgList cannot be empty");
      return false;
    }

    final resResult = await handlerSubmitPostNewsfeed(mindValue, state.imgList,  sCallback: sCallback, fCallback: fCallback);

    if(resResult!=null && resResult){
      final communitVm = ref.read(communityVmProvider.notifier);
      communitVm.getCurrentPageViewVm(null).initPageData();
      // Navigator.pop(context);
      appRouter.maybePop();
    }
  }

  // 发布
  Future<bool> handlerSubmitPostNewsfeed(String mindValue,List<String> imgList,{VoidCallback? sCallback, VoidCallback? fCallback}) async{
    try {
      final result = await repositoryInstance.fetchNewsfeedPublish({
        "content": mindValue,
        "resources": imgList
      });
      if (result.isSuccess) {
        sCallback?.call();
        // 更新用户信息
        UserConfigService.getInstance().refreshUserInfo();
        return true;
      }else {
        fCallback?.call();
        return false;
      }
    }catch(e){
      Log.d("发布newsfeed 失败 $e");
      return false;
    }
  }

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

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

    // 获取表单的焦点节点
    final FocusNode focusNode = getFocusNode(state.formData, 'mind');

    focusNode.addListener(() {
      // 获取焦点的时候清空错误文本
      if (focusNode.hasFocus) {
        state = state.copyWith(mindFieldErrorText: null);
      }
    });
  }

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

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


}
