import 'package:dio/dio.dart';
import 'package:netrain_flutter_app/zhangfeng/Network/BaseHttpModel.dart';
import 'BaseHttpModel.dart';
import 'UrlPath.dart';

typedef OnResult = void Function(BaseHttpModel t, String errorMsg) ;

class HttpManager {
  static HttpManager _instance = HttpManager._internal();
  Dio _dio;

  factory HttpManager() => _instance;

  ///通用全局单例，第一次使用时初始化
  HttpManager._internal({String baseUrl}) {
    if (null == _dio) {
      _dio = new Dio(new BaseOptions(
          baseUrl: UrlPath.baseUrl, connectTimeout: 15000));
    }
  }

  static HttpManager getInstance({String baseUrl}) {
    if (baseUrl == null) {
      return _instance._normal();
    } else {
      return _instance._baseUrl(baseUrl);
    }
  }

  //用于指定特定域名
  HttpManager _baseUrl(String baseUrl) {
    if (_dio != null) {
      _dio.options.baseUrl = baseUrl;
    }
    return this;
  }

  //一般请求，默认域名
  HttpManager _normal() {
    if (_dio != null) {
      if (_dio.options.baseUrl != UrlPath.baseUrl) {
        _dio.options.baseUrl = UrlPath.baseUrl;
      }
    }
    return this;
  }

  request(String url,
      {parameters,
        method = 'GET',
        OnResult onResult}) async {
    parameters = parameters ?? {};
    if(onResult==null){
      return;
    }
    try {
      Response response = await _dio.request(url,
          queryParameters: parameters, options: new Options(method: method));
      BaseHttpModel httpModel = BaseHttpModel.fromJson(response.data);
      if (httpModel.isSuccess()) {
        onResult(httpModel, null);
      }else{
        onResult(httpModel, httpModel.errorMsg());
      }
    } on DioError catch (e) {
      onResult(null, e.message);
    }
  }
}
