import 'dart:convert';
// import 'package:dio/dio.dart';
import 'package:fis_common/env/env.dart';
import 'package:fis_common/logger/logger.dart';
import 'package:flutter/services.dart';
// import 'package:flyinsono/architecture/utils/web.dart';

/// 应用参数(随编译引入)
class AppParameters {
  // static final _now = DateTime.now();
  static final _path = "assets/app_params.json";
  static late final _DataModel _data;
  static bool _hasInit = false;

  /// 数据内容
  static _DataModel get data => _data;

  /// 加载预置参数数据
  static Future<void> load() async {
    if (_hasInit) return;
    try {
      final dynamic jsonMap;
      final json = await rootBundle.loadString(_path, cache: false);
      jsonMap = jsonDecode(json);
      _data = _DataModel.fromJson(jsonMap);
    } catch (e) {
      logger.e("Load AppConfig error.", e);
      _data = _DataModel();
    }
    _hasInit = true;
  }

  // static Future<dynamic> _getWebJson() async {
  //   final url =
  //       "${WebUtils.rootPath}assets/$_path?v=${_now.millisecondsSinceEpoch}";
  //   final response = await Dio().get(url);
  //   return response.data;
  // }
}

///服务器信息数据模型
class _DataModel {
  static const C_DEFAULT_GATEWAY = "https://hk.flyinsono.com";
  static const C_REPORT_DESIGNER = "https:2.flyinsono.com/report/#";
  static const C_DEFAULT_STATIC_ROOT =
      "http://cloud.flyinsono.com:9001/static/themes";
  static const List<String> C_DEFAULT_FLYINSONOSERVERS = [];
  static const List<String> C_DEFAULT_REMOVE_REMOVE_LOGO_DOMAINS = [];

  _DataModel({
    this.serverGateway = C_DEFAULT_GATEWAY,
    this.themeSourceRoot = C_DEFAULT_STATIC_ROOT,
    this.flyinsonoServers = C_DEFAULT_FLYINSONOSERVERS,
    this.reportDesignerRoot = C_REPORT_DESIGNER,
    this.externalLivePlayerUrl = "",
    this.removeLogoDomains = C_DEFAULT_REMOVE_REMOVE_LOGO_DOMAINS,
  });
  factory _DataModel.fromJson(Map<String, dynamic> map) {
    List<dynamic> flyinsonoServers = map['flyinsonoServers'] ?? [];
    List<String> servers = [];
    for (var server in flyinsonoServers) {
      servers.add(server);
    }
    List<dynamic> removeLogoDomains = map['remove_logo_domains'] ?? [];
    List<String> domains = [];
    for (var domain in removeLogoDomains) {
      domains.add(domain);
    }
    return _DataModel(
      serverGateway: map['server_gateway'] ?? C_DEFAULT_GATEWAY,
      themeSourceRoot: map['theme_source_root'] ?? C_DEFAULT_STATIC_ROOT,
      flyinsonoServers: servers,
      reportDesignerRoot: (FPlatform.isMacOS || FPlatform.isWindows)
          ? map['local_report_designer']
          : map['report_designer_root'],
      externalLivePlayerUrl: map['external_live_player_url'] ?? "",
      removeLogoDomains: domains,
    );
  }

  String serverGateway;
  String themeSourceRoot;
  List<String> flyinsonoServers;
  String reportDesignerRoot;
  String
      externalLivePlayerUrl; // 部署在外部的 Nodeplayer 播放器地址（需要带 fis.plus）否则用不了，置空则使用内置的播放器
  List<String> removeLogoDomains;
}
