import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:location/sdk/wechat/wechat_helper.dart';
import 'package:wechat_kit/wechat_kit.dart';
import '../../data/consts/web_url.dart';
import '../../resource/assets.gen.dart';
import '../../resource/string.gen.dart';
import '../../utils/capture_util.dart';
import 'package:image/image.dart' as img;

class WechatShareUtil {
  WechatShareUtil._();

  static Future<void> shareWebPage() async {
    if (!await WechatHelper.isInstalled()) {
      throw Exception(StringName.wechatNoInstall);
    }
    return WechatHelper.shareUrlToWechat(
        scene: WechatScene.kSession,
        webpageUrl: WebUrl.shareUrl,
        title: StringName.shareFriendTitle,
        description: StringName.shareFriendDesc,
        thumbData: await assetImageToBytes(Assets.images.iconLogoMax.path));
  }

  static Future<Uint8List> assetImageToBytes(String assetPath) async {
    final ByteData byteData = await rootBundle.load(assetPath);
    return byteData.buffer.asUint8List();
  }

  static Future<void> shareWidgetToWeChat(
    GlobalKey repaintKey, {
    int scene = WechatScene.kSession,
    double pixelRatio = 2.5,
    int maxBytes = 1024 * 1024,
  }) async {
    try {
      final isInstall = await WechatHelper.isInstalled();
      if (!isInstall) {
        throw Exception(StringName.wechatNoInstall);
      }

      final captured = await CaptureUtil.captureWidgetToImage(repaintKey);
      if (captured == null) {
        throw Exception('截图失败');
      }

      final compressed =
          await _compressImageToLimit(captured, maxBytes: maxBytes);
      if (compressed == null) {
        debugPrint("图片压缩失败");
        return;
      }

      await WechatHelper.shareImageToWechat(
        scene: scene,
        imageData: compressed,
      );
    } catch (e) {
      throw Exception('分享失败');
    }
  }

  static Future<Uint8List?> _compressImageToLimit(Uint8List data,
      {required int maxBytes}) async {
    final decoded = img.decodeImage(data);
    if (decoded == null) return null;

    int quality = 95;
    late Uint8List result;

    do {
      result = Uint8List.fromList(img.encodeJpg(decoded, quality: quality));
      quality -= 5;
    } while (result.lengthInBytes > maxBytes && quality > 10);

    return result.lengthInBytes <= maxBytes ? result : null;
  }
}
