import 'dart:convert';
import 'dart:io';

import 'package:flutter/services.dart';
import 'package:location/data/consts/build_config.dart';
import 'package:location/data/consts/web_url.dart';
import 'package:location/resource/assets.gen.dart';
import 'package:location/utils/atmob_log.dart';
import 'package:quickpass_yidun_flutter/quickpass_flutter_plugin.dart';

class QuickLoginHelper {
  QuickLoginHelper._();

  static final String tag = 'QuickLoginHelper';

  static final String _businessId = BuildConfig.quickLoginBusinessId;

  static final String userAgreement = WebUrl.userAgreement;
  static final String privacyPolicy = WebUrl.privacyPolicy;

  static final QuickpassFlutterPlugin quickLoginPlugin =
      QuickpassFlutterPlugin();

  static Map<String, dynamic>? _configMap;

  // 新增静态变量存储 preFetchNumber 获取的 ydToken
  static String? _storedYdToken;

  static Future<void> init() {
    return quickLoginPlugin.init(_businessId).then((map) {
      bool result = map?['success'];
      AtmobLog.d(tag, 'init success:$result');
    });
  }

  static EventChannel getEventChannel() {
    return const EventChannel("yd_quicklogin_flutter_event_channel");
  }

  static void closeLoginAuthView() {
    quickLoginPlugin.closeLoginAuthView();
  }

  static Future<void> _setUiConfig() async {
    _configMap ??= await _getFileConfig();
    quickLoginPlugin.setUiConfig(_configMap);
  }

  static Future<Map<String, dynamic>> _getFileConfig() async {
    String file = "";
    if (Platform.isIOS) {
      file = Assets.config.iosQuickLoginConfig;
    } else if (Platform.isAndroid) {
      file = Assets.config.androidQuickLoginConfig;
    }
    return rootBundle.loadString(file).then((value) {
      return {"uiConfig": json.decode(value)};
    });
  }

  // 在初始化方法中添加测试代码（如 initState 或单独的测试按钮

  static void preFetchNumber({
    required void Function(String token) onSuccess,
    required void Function(String? errorMsg) onError,
  }) async {
    Map<dynamic, dynamic>? map = await quickLoginPlugin.preFetchNumber();
    if (map?['success'] == true) {
      var ydToken = map?['token'];
      // 存储 ydToken 到静态变量
      _storedYdToken = ydToken;
      AtmobLog.d(tag, 'preFetchNumber success token:$ydToken');
      onSuccess(ydToken);
    } else {
      //获取预设手机号失败
      var ydToken = map?['token'];
      // 失败时清空存储的 token
      _storedYdToken = ydToken;
      var errorMsg = map?['errorMsg'];
      AtmobLog.e(tag, "preFetchNumber error token:$ydToken,errorMsg:$errorMsg");
      onError(errorMsg);
    }
  }

  static void onePassLogin({
    required void Function(String ydToken, String accessToken) onSuccess,
    required void Function(String? errorMsg) onError,
  }) async {
    try {
      await _setUiConfig();
      Map<dynamic, dynamic>? map = await quickLoginPlugin.onePassLogin();
      if (map?["success"]) {
        var accessToken = map?["accessToken"];
        var ydToken = map?["ydToken"] ?? _storedYdToken;
        AtmobLog.d(tag,
            "onePassLogin success ydToken:$ydToken, accessToken:$accessToken");
        onSuccess(ydToken, accessToken);
      } else {
        var errorMsg = map?["msg"];
        AtmobLog.e(tag, "onePassLogin error msg:$errorMsg");
        onError(errorMsg);
        closeLoginAuthView();
      }
    } catch (e) {
      onError(e.toString());
      closeLoginAuthView();
    }
  }

  static void dispose() {
    _configMap = null;
  }
}
