import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:injectable/injectable.dart';
import 'package:location/base/base_controller.dart';
import 'package:location/data/repositories/account_repository.dart';
import 'package:location/data/repositories/friends_repository.dart';
import 'package:location/module/friend/setting/friend_setting_page.dart';
import 'package:location/module/news/news_page.dart';
import '../../data/bean/member_status_info.dart';
import '../../data/bean/user_info.dart';
import '../../dialog/common_alert_dialog_impl.dart';
import '../../dialog/common_confirm_dialog_impl.dart';
import '../../sdk/wechat/wechat_share_util.dart';
import '../../utils/toast_util.dart';
import '../login/login_page.dart';
import '../member/member_page.dart';
import '../track/track_page.dart';

@injectable
class FriendController extends BaseController {
  final AccountRepository accountRepository;
  final FriendsRepository friendsRepository;

  UserInfo get mineUserInfo => accountRepository.mineUserInfo.value;

  UserInfo? get virtualFriendInfo => friendsRepository.virtualFriendInfo.value;

  Rxn<MemberStatusInfo> get memberStatusInfo =>
      accountRepository.memberStatusInfo;

  RxList<UserInfo> get friendsList => friendsRepository.friendsList;

  final ScrollController scrollController = ScrollController();

  final RxDouble _opacity = 0.0.obs;

  double get opacity => _opacity.value;

  final double _scrollThreshold = 80;

  FriendController(this.accountRepository, this.friendsRepository);

  @override
  void onReady() {
    super.onReady();
    scrollController.addListener(_handleScroll);
  }

  void _handleScroll() {
    final double offset = scrollController.offset;
    if (offset <= _scrollThreshold) {
      _opacity.value = 0.0;
    } else {
      double opacity = ((offset - _scrollThreshold) / 200).clamp(0.0, 1.0);
      _opacity.value = opacity;
    }
  }

  void back() {
    Get.back();
  }

  void newsClick() {
    NewsPage.start();
  }

  @override
  void onClose() {
    super.onClose();
    scrollController.dispose();
  }

  void onEditClick(UserInfo e) {
    FriendSettingPage.start(e);
  }

  void onViewTraceClick(UserInfo userInfo) {
    if (!accountRepository.isLogin.value) {
      showTraceTipsDialog(onConfirm: () {
        LoginPage.start();
      });
      return;
    }
    if (!(userInfo.virtual ?? false) && accountRepository.memberIsExpired()) {
      MemberPage.start();
      return;
    }

    if (userInfo.blockedMe == true) {
      showBlockMeTipDialog(confirmOnTap: () {
        WechatShareUtil.shareWebPage().catchError((error) {
          ToastUtil.show(error.toString());
        });
      });
      return;
    }
    TrackPage.start(userInfo);
  }
}
