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

typedef OnResult = void Function(BaseHttpModel httpModel, 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,String imagePath}) async {
    parameters = parameters ?? {};
    if(onResult==null){
      return;
    }
    try {
      FormData formdata;
      if(imagePath != null){
        var name = imagePath.substring(imagePath.lastIndexOf("/") + 1, imagePath.length);
        var suffix = name.substring(name.lastIndexOf(".") + 1, name.length);
        formdata = FormData.fromMap({
          "file": await MultipartFile.fromFile(
            imagePath,                                //图片路径
            filename: name,
          )
        });
      }
      parameters = new Map<String, dynamic>.from(parameters);
      Map<String,String> map = new Map<String,String>();
      if(UserModel.getModel() != null) {
        map[UserModel.getModel().header] = UserModel.getModel().tokenHead + UserModel.getModel().token;
      }
      Response response = await _dio.request(url,
          queryParameters: parameters, data: formdata, options: new Options(method: method,headers: map));
      Map<String, dynamic> result = json.decode(response.toString());
      BaseHttpModel httpModel = BaseHttpModel.fromJson(result);
      if (httpModel.isSuccess()) {
        onResult(httpModel, null);
      }else{
        onResult(httpModel, httpModel.errorMsg());
      }
    } on DioError catch (e) {
      onResult(null, e.message);
    }
  }
}
