import 'dart:async';

import 'package:flutter/material.dart';
import 'package:injectable/injectable.dart';
import 'package:wechat_kit/wechat_kit.dart';

import '../di/get_it.dart';
import '../utils/atmob_log.dart';

@lazySingleton
class WechatLoginService {
  final String tag = "WechatLoginService";
  final String _appId = "wx21272929e8fd33e9"; //AppID
  final String? _universalLink = "wx21272929e8fd33e9"; // universalLink

 late final StreamSubscription<WechatResp> _respSub;

  void Function(String code)? _onSuccess;
  void Function(int code, String msg)? _onError;
  VoidCallback? _onCancel;

  String? lastCode;

  WechatLoginService() {
    AtmobLog.d(tag, '$tag....init');
    _init();
  }

  void _init() {
    // 注册 App 并监听回调
    WechatKitPlatform.instance.registerApp(
      appId: _appId,
      universalLink: _universalLink,
    );
    _respSub = WechatKitPlatform.instance.respStream().listen(_handleWechatResp);
  }

  void login({
    required void Function(String code) onSuccess,
    void Function(int code, String msg)? onError,
    VoidCallback? onCancel,
  }) async {
    try {
      final isInstalled = await WechatKitPlatform.instance.isInstalled();
      if (!isInstalled) {
        onError?.call(
          WechatResp.kErrorCodeUnsupport,
          _getErrorMsg(WechatResp.kErrorCodeUnsupport),
        );
        return;
      }

      // 保存回调函数
      _onSuccess = onSuccess;
      _onError = onError;
      _onCancel = onCancel;

      // 发送授权请求
      WechatKitPlatform.instance.auth(
        scope: <String>[WechatScope.kSNSApiUserInfo],
        state: 'wechat_login',
      );
    } catch (e) {
      onError?.call(-999, '微信初始化失败: ${e.toString()}');
    }
  }

  void _handleWechatResp(WechatResp resp) {
    if (resp is WechatAuthResp) {
      debugPrint("【WechatLoginService】收到微信响应: ${resp.errorCode} ${resp.errorMsg}");

      switch (resp.errorCode) {
        case WechatResp.kErrorCodeSuccess:
          if (resp.code != null) {
            lastCode = resp.code;
            _onSuccess?.call(resp.code!);
          } else {
            _onError?.call(-998, '未获取到授权 code');
          }
          break;
        case WechatResp.kErrorCodeUserCancel:
          _onCancel?.call();
          break;
        default:
          _onError?.call(resp.errorCode, _getErrorMsg(resp.errorCode));
      }

      // 一次登录完成后清空回调
      _clearCallbacks();
    }
  }

  void _clearCallbacks() {
    _onSuccess = null;
    _onError = null;
    _onCancel = null;
  }

  String _getErrorMsg(int code) {
    switch (code) {
      case WechatResp.kErrorCodeCommon:
        return '普通错误，可能是网络问题';
      case WechatResp.kErrorCodeUserCancel:
        return '用户取消了登录';
      case WechatResp.kErrorCodeSentFail:
        return '发送请求失败';
      case WechatResp.kErrorCodeAuthDeny:
        return '授权失败';
      case WechatResp.kErrorCodeUnsupport:
        return '未检测到微信客户端';
      default:
        return '未知错误: $code';
    }
  }

  void dispose() {
    _respSub?.cancel();
  }

  static WechatLoginService getInstance() => getIt.get<WechatLoginService>();
}
