import 'package:cs_resources/theme/app_colors_theme.dart';
import 'package:flutter/cupertino.dart';
import 'package:plugin_basic/provider/user_config/user_config_service.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/dialog/app_custom_dialog.dart';

import '../../../respository/common_newsfeed.dart';
import '../my_follow/my_follow_vm.dart';
import '../my_follower/my_follower_vm.dart';
import 'item_following.dart';

part 'item_following_vm.g.dart';


Map<String, dynamic> MyFollowingType = {
  "isFollowType": '1',
  "isFollowerType": '2',
};

@riverpod
class ItemFollowingVm extends _$ItemFollowingVm {
  late CommonNewsFeedRespository commonNewsFeedRespositoryInstance;
  @override
  build(){
    // 引入数据仓库
    commonNewsFeedRespositoryInstance = ref.read(commonNewsFeedRespositoryProvider);
    final state = {};
    Log.d("--------------------------build---------------------");
    return state;
  }

  // 关注/取消关注
  handlerFollow(BuildContext? context, int to_user_id, bool isFollow, String itemType, Function(bool)? callback) async{
    Log.d("点击了 关注");
    if(isFollow){
      await DialogEngine.show(
          tag: "cancelFollow",
          position: DialogPosition.center,
          widget: AppCustomDialog(
            message: 'Are you sure you want to cancel follow',
            dialogWidth: MediaQuery.of(context!).size.width * 0.8,
            // contentBoxMaxHeight: 350,
            // contentBoxMinHeight: 300,
            isShowConfirmBtn:  true,
            isShowCancelBtn: true,
            confirmTxt: "Ok",
            confirmAction: (){
              // 点击了确定
              Log.d("----点击了确定按钮");
              excuteCancelFollow(context, to_user_id, isFollow, itemType!, callback);
            },
          )
      );

    }
  }

  Future<bool> excuteCancelFollow(BuildContext context, int to_user_id, bool isFollow, String itemType, Function(bool)? callback) async{
    try {
      final result = await commonNewsFeedRespositoryInstance.handlerFollowOrCancel({
        "to_user_id": to_user_id,
      });
      bool flag = false;
      if(result.isSuccess){
        if(itemType == MyFollowingType['isFollowType']){
          // 删除 my_follow_list 中 id 为 to_user_id 的item
          final myFollowVm = ref.read(myFollowVmProvider.notifier);
          myFollowVm.softDeleteItem(to_user_id);
        }else if(itemType == MyFollowingType['isFollowerType']){
          // final myFlowerVm = ref.read(myFollowerVmProvider.notifier);
        }
        // 同步用户信息
        UserConfigService.getInstance().refreshUserInfo();
        flag = true;
      }else {
        flag = false;
      }
      callback?.call(flag);
      return flag;

    }catch(error){
      Log.d("error: $error");
      return false;
    }
  }
}