import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:loopin/IM/im_service.dart';
import 'package:shirne_dialog/shirne_dialog.dart';
import 'package:tencent_cloud_chat_sdk/models/v2_tim_user_full_info.dart';

class ImUserInfoController extends GetxController {
  @override
  void onInit() {
    super.onInit();
    logger.i('开始IM用户信息初始化');
    init(V2TimUserFullInfo(customInfo: {
      "coverBg": "",
      "area": "",
      "areaCode": "",
      "openId": "",
      "tag": "",
    }));
  }

  V2TimUserFullInfo? rawUserInfo;

  final userID = ''.obs;
  final nickname = ''.obs;
  final faceUrl = ''.obs;
  final signature = ''.obs;
  final gender = 0.obs;
  final allowType = 0.obs;
  final customInfo = <String, String>{
    "coverBg": "",
    "area": "",
    "areaCode": "",
    "openId": "",
    "tag": "",
  }.obs;
  final role = 0.obs;
  final level = 0.obs;
  final birthday = 0.obs;

  void init(V2TimUserFullInfo userInfo) {
    logger.i(userInfo.toJson());
    rawUserInfo = userInfo;
    userID.value = userInfo.userID ?? '';
    nickname.value = userInfo.nickName ?? '';
    faceUrl.value = userInfo.faceUrl ?? '';
    signature.value = userInfo.selfSignature ?? '';
    gender.value = userInfo.gender ?? 0;
    allowType.value = userInfo.allowType ?? 0;
    customInfo.assignAll(userInfo.customInfo ??
        {
          "coverBg": "",
          "area": "",
          "areaCode": "",
          "openId": "",
          "tag": "",
        });
    // final safeMap = <String, String>{};
    // userInfo.customInfo?.forEach((key, value) {
    //   safeMap[key] = value;
    // });

    // customInfo.assignAll({
    //   "coverBg": "",
    //   "area": "",
    //   "areaCode": "",
    //   "openId": "",
    //   "tag": "",
    //   ...safeMap, // 覆盖默认值
    // });

    role.value = userInfo.role ?? 0;
    level.value = userInfo.level ?? 0;
    birthday.value = userInfo.birthday ?? 0;
  }

  Future<void> refreshUserInfo() async {
    try {
      final updatedUserInfo = await ImService.instance.selfInfo();
      if (updatedUserInfo.success) {
        init(updatedUserInfo.data);
      }
    } catch (e) {
      logger.e('刷新用户信息失败: $e');
    }
  }

  /// 更新昵称
  Future<bool> updateNickname(newnickname) async {
    final res = await ImService.instance.setSelfInfo(userFullInfo: V2TimUserFullInfo(nickName: newnickname));
    if (res.success) {
      nickname.value = newnickname;
    } else {
      logger.i(res.desc);
      if (res.code == 80001) {
        MyDialog.toast('昵称违规', icon: Icon(Icons.warning), style: ToastStyle(backgroundColor: Colors.red.withAlpha(200)));
      }
    }
    return res.success;
  }

  /// 更新简介
  Future<bool> updateSignature(newsignature) async {
    final res = await ImService.instance.setSelfInfo(userFullInfo: V2TimUserFullInfo(selfSignature: newsignature));
    if (res.success) {
      signature.value = newsignature;
    } else {
      logger.i(res.desc);
      if (res.code == 80001) {
        MyDialog.toast('简介内容违规', icon: Icon(Icons.warning), style: ToastStyle(backgroundColor: Colors.red.withAlpha(200)));
      }
    }
    return res.success;
  }

  /// 更新头像
  Future<void> updateFaceUrl() async {
    if (faceUrl.value.trim().isEmpty) return;
    await ImService.instance.setSelfInfo(userFullInfo: V2TimUserFullInfo(faceUrl: faceUrl.value));
  }

  /// 更新背景图
  Future<void> updateCover() async {
    final coverBg = customInfo['coverBg'];
    if (coverBg == null || coverBg.trim().isEmpty) return;
    await ImService.instance.setSelfInfo(userFullInfo: V2TimUserFullInfo(customInfo: customInfo));
  }

  /// 更新openId
  Future<void> updateOpenId() async {
    final openId = customInfo['openId'];
    if (openId == null || openId.trim().isEmpty) return;
    await ImService.instance.setSelfInfo(userFullInfo: V2TimUserFullInfo(customInfo: customInfo));
  }
  // customInfo.update("coverBg", (value) => coverBgUrl);

  /// 更新所在地
  Future<void> updateArea() async {
    final area = customInfo['area'];
    if (area == null || area.trim().isEmpty) return;
    final areaCode = customInfo['areaCode'];
    if (areaCode == null || areaCode.trim().isEmpty) return;
    await ImService.instance.setSelfInfo(userFullInfo: V2TimUserFullInfo(customInfo: customInfo));
  }

  ///更新生日
  Future<void> updateBirthday() async {
    if (birthday.value < 0) return;
    await ImService.instance.setSelfInfo(userFullInfo: V2TimUserFullInfo(birthday: birthday.value));
  }

  ///更新性别
  Future<void> updateGender() async {
    if (gender.value < 0) return;
    await ImService.instance.setSelfInfo(userFullInfo: V2TimUserFullInfo(gender: gender.value));
  }
}
