import 'package:flutter/services.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';
import 'package:loopin/IM/controller/im_user_info_controller.dart';
import 'package:loopin/IM/im_service.dart';
import 'package:loopin/api/common_api.dart';
import 'package:loopin/service/http.dart';

class Wxsdk {
  static bool _inited = false;

  static final Fluwx fluwx = Fluwx();

  static Future<bool> init() async {
    if (_inited) {
      return true;
    }
    _inited = true;
    final initRes = await fluwx.registerApi(
      appId: 'wxebcdaea31881caab',
      doOnAndroid: true,
      doOnIOS: true,
      universalLink: 'https://wuzhongjie.com.cn/',
    );
    if (initRes) {
      logger.i('微信sdk初始化成功');
      // 全局监听授权回调
      fluwx.addSubscriber(
        (res) async {
          //授权
          if (res is WeChatAuthResponse) {
            if (res.isSuccessful) {
              final code = res.code;
              logger.i('微信回调，code: $code，类型:${res.state}');
              if (res.state == 'getOpenId') {
                // TODO: 使用 code 向后台换取 access_token、unionid
                final serverRes = await Http.post(CommonApi.wxLogin, data: {
                  "source": "wechat_open",
                  "socialCode": "${res.code}",
                  "socialState": "1",
                  "clientId": "428a8310cd442757ae699df5d894f051",
                  "grantType": "social"
                });
                final info = Get.find<ImUserInfoController>();
                info.customInfo['openId'] = serverRes['data']['openId'];
                info.updateOpenId();
                info.customInfo.refresh();
                logger.w(serverRes['data']['openId']);
              }
            } else {
              logger.w('微信授权失败: ${res.errStr}-类型：${res.state}');
            }
          }
          // 分享
          if (res is WeChatShareResponse) {
            logger.w(res.isSuccessful);
            // 这里只能确保打开了微信，是取消了还是确认了没办法知道
            if (res.isSuccessful) {}
          }
        },
      );
    } else {
      logger.i('微信SDK初始化失败：$initRes');
    }
    return initRes;
  }

  /// 调用微信登录
  static Future<void> login() async {
    final result = await fluwx.authBy(
      which: NormalAuth(
        scope: 'snsapi_userinfo',
        state: 'getOpenId',
      ),
    );
    if (!result) {
      logger.e('微信授权请求发送失败');
    }
  }

  ///分享好友
  static Future<bool> shareToFriend({
    required String title,
    required String description,
    required String webpageUrl,
    String thumbnailAssetPath = 'assets/images/logo/logo.png',
  }) async {
    Uint8List? thumbData;
    thumbData = await _loadLocalThumbnail(thumbnailAssetPath);
    final model = WeChatShareWebPageModel(
      webpageUrl,
      title: title,
      description: description,
      thumbData: thumbData,
      scene: WeChatScene.session,
    );
    return Fluwx().share(model);
  }

  ///分享到朋友圈
  static Future<bool> shareToTimeline({
    required String title,
    required String webpageUrl,
    String thumbnailAssetPath = 'assets/images/logo/logo.png',
  }) async {
    Uint8List? thumbData;
    thumbData = await _loadLocalThumbnail(thumbnailAssetPath);
    final model = WeChatShareWebPageModel(
      webpageUrl,
      title: title,
      thumbData: thumbData,
      scene: WeChatScene.timeline,
    );
    return Fluwx().share(model);
  }

  static Future<Uint8List> _loadLocalThumbnail(String assetPath) async {
    final byteData = await rootBundle.load(assetPath);
    final originBytes = byteData.buffer.asUint8List();

    final compressedBytes = await FlutterImageCompress.compressWithList(
      originBytes,
      minWidth: 120, // 微信要求120X120且小于32kb
      minHeight: 120,
      quality: 80, // 控制质量
      format: CompressFormat.jpeg, // 转为 JPEG
    );

    logger.i("thumbData size: ${compressedBytes.length} bytes");

    return compressedBytes;
  }

  /// 跳转小程序
  static Future<void> openMiniApp({required orderId}) async {
    var miniProgram = MiniProgram(
      username: "gh_2ffaecc5508e", // 小程序原始ID
      path: "/pages/index/index?id=$orderId", // 打开时带的路径参数
      miniProgramType: WXMiniProgramType.preview,
    );
    Fluwx().open(target: miniProgram);
  }
}
