import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:loopin/IM/im_message.dart';
import 'package:loopin/IM/im_service.dart';
import 'package:loopin/utils/index.dart';
import 'package:tencent_cloud_chat_sdk/enum/message_elem_type.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_message.dart';

class ChatDetailController extends GetxController {
  final String id;

  ChatDetailController({required this.id});
  final ScrollController chatController = ScrollController();
  final RxList<V2TimMessage> chatList = <V2TimMessage>[].obs;
  final RxBool isFriend = true.obs;
  final RxInt followType = 0.obs;
  final RxBool toolFlag = true.obs; // 工具栏使用权限(针对群聊的)

  void updateChatListWithTimeLabels(List<V2TimMessage> originMessages) async {
    final idRes = await ImService.instance.selfUserId();
    if (idRes.success) {
      final selfUserId = idRes.data;
      List<V2TimMessage> displayMessages = [];

      for (int i = 0; i < originMessages.length; i++) {
        final current = originMessages[i];
        final currentTimestamp = current.timestamp ?? 0;

        // 判断是否需要给当前这条消息加时间标签
        bool needInsertLabel = false;

        if (i == originMessages.length - 1) {
          // 最后一条消息，加时间标签
          needInsertLabel = true;
        } else if (current.localCustomData == 'time_label' || current.elemType == MessageElemType.V2TIM_ELEM_TYPE_GROUP_TIPS) {
          //
          needInsertLabel = true;
        } else {
          final next = originMessages[i + 1];
          final nextTimestamp = next.timestamp ?? 0;
          final diff = currentTimestamp - nextTimestamp;

          if (diff > 180) {
            needInsertLabel = true;
          }
        }

        // if (i == 0) {
        //   // 第一条一定插时间
        //   needInsertLabel = true;
        // } else {
        //   final prev = originMessages[i - 1];
        //   final prevTimestamp = prev.timestamp ?? 0;
        //   final diff = currentTimestamp - prevTimestamp;

        //   if (diff > 180) {
        //     needInsertLabel = true;
        //   }
        // }
        // 把当前消息先插入，label后插入
        displayMessages.add(current);
        if (needInsertLabel) {
          final labelTime = Utils.formatChatTime(currentTimestamp);
          final timeLabel = await IMMessage().insertTimeLabel(labelTime, selfUserId);
          displayMessages.add(timeLabel.data);
        }
      }
      // 新加载的记录放在最上面
      chatList.addAll(displayMessages);
    }
  }

  ///滚动
  void scrollToBottom() {
    if (chatController.hasClients) {
      chatController.animateTo(
        0,
        duration: Duration(milliseconds: 200),
        curve: Curves.easeOut,
      );
    }
    // Future.delayed(Duration(milliseconds: 300), () {
    //   if (chatController.hasClients) {
    //     chatController.animateTo(
    //       chatController.position.maxScrollExtent,
    //       duration: Duration(milliseconds: 200),
    //       curve: Curves.easeOut,
    //     );
    //   }
    // });
  }

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