import 'dart:ffi';

import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:injectable/injectable.dart';
import 'package:location/base/base_controller.dart';
import 'package:location/data/repositories/message_repository.dart';
import 'package:location/handler/error_handler.dart';
import 'package:location/module/news/pending_list/news_pending_list_page.dart';
import 'package:location/resource/assets.gen.dart';
import 'package:location/utils/common_expand.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../data/bean/message_info.dart';
import '../../data/bean/request_friend_info.dart';
import '../add_friend/add_friend_page.dart';
import 'news_report/news_report_page.dart';

@injectable
class NewsController extends BaseController {
  final RxDouble _opacity = 0.0.obs;

  double get opacity => _opacity.value;

  final ScrollController scrollController = ScrollController();

  final double _scrollThreshold = 80;

  final MessageRepository messageRepository;

  RequestFriendInfo? get latestFriendRequest =>
      messageRepository.latestFriendRequest.value;

  int get waitingNewsCount => messageRepository.waitingCount.value;

  RxList<MessageInfo> messageList = RxList();

  NewsController(this.messageRepository);

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

  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() {
    NewsPendingListPage.start();
  }

  void requestMessageList() {
    messageRepository.getMessageList().then((response) {
      messageList.clear();
      if (response.list != null) {
        messageList.addAll(response.list!);
      }
      WidgetsBinding.instance.addPostFrameCallback((_) {
        messageRepository.updateLastReadMessageId(
            messageList.isNotEmpty ? messageList.first.id : 0);
      });
    }).catchError((error) {
      ErrorHandler.toastError(error);
    });
  }

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

  ///2:你的好友请求已经被接受
  // 3:你的好友请求已经被拒绝
  // 4:好友发来的求救
  // 5:你的好友删除了你
  void onMessageFunClick(MessageInfo info) {
    if (info.type == 4) {
      debugPrint('好友发来的求救');
      //跳转到打电话界面
      _launchDialer(info.senderPhone);
    }
  }

  void _launchDialer(String phoneNumber) async {
    final Uri uri = Uri.parse('tel:$phoneNumber');
    if (await canLaunchUrl(uri)) {
      await launchUrl(uri);
    } else {
      throw '无法跳转拨号界面';
    }
  }

  void onMessageWaitingClick() {
    NewsPendingListPage.start();
  }

  ///添加跳转到加新的朋友
  void onAddJumpToAddNewFriend() {
    AddFriendPage.show();
  }

  ///举报事件
  void onReportEventClick() {
    showCupertinoModalPopup(
      context: Get.context!,
      builder: (context) =>
          CupertinoActionSheet(
            actions: [
              CupertinoActionSheetAction(
                  child: Row(
                    children: [
                      SizedBox(width: 18.w,),
                      Assets.images.iconNewsReport.image(
                          width: 20.w, height: 20.w),
                      SizedBox(width: 6.w,),
                      Text(
                        '举报',
                        style: TextStyle(
                            fontSize: 13.sp,
                            color: "#333333".color,
                            fontWeight: FontWeight.w400),
                      ),
                    ],
                  ),
                  onPressed: () {
                    Navigator.pop(context);
                    NewsReportPage.start();
                  }
              ),
            ],
          ),
    );
  }

  ///用户是否在长安
  void onUserIsLongEventClick(int longIndex) {
    print("longIndexsfsdfs---${longIndex}");
    onReportEventClick();
  }
}