import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:fun_selfie_app/utils/storage.dart';
import 'package:crypto/crypto.dart';
import 'package:fun_selfie_app/utils/common_toast.dart';

class DioInterceptors extends Interceptor {
  @override
  void onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    // 对非open的接口的请求参数全部增加userId
    // if (!options.path.contains("open")) {
    //   options.queryParameters["userId"] = "xxx";
    // }

    // 头部添加token
    // options.headers["token"] = "xxx";
    String userMsg = await StorageUtil.getString('userMsg');
    if (userMsg.isEmpty) return;
    Map userMsgObj = jsonDecode(userMsg);
    String? appId = userMsgObj['configName'];
    String? secret = userMsgObj['configPass'];
    // String? website = 'http://118.123.247.197:8080/jeecg-boot/';
    var ts = DateTime.now().millisecondsSinceEpoch.toString();
    var token = md5
        .convert(utf8.encode(appId.toString() + secret.toString() + ts))
        .toString();
    options.headers['X-APPID'] = appId;
    options.headers['X-SECRET-TOKEN'] = token;
    options.headers['ts'] = ts;
    // options.baseUrl = website.toString();

    // 更多业务需求

    handler.next(options);

    // super.onRequest(options, handler);
  }

  @override
  void onResponse(Response response, ResponseInterceptorHandler handler) async {
    // 请求成功是对数据做基本处理
    if (response.statusCode == 200) {
      response.data = response.data['result'];
    } else {
      CommonToast.errToast(
          '出错了,'.toString() + response.statusMessage.toString());
    }

    // 对某些单独的url返回数据做特殊处理
    if (response.requestOptions.baseUrl.contains("???????")) {
      //....
    }

    // 重点
    handler.next(response);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    String? data = err.response?.data;
    if (data != null) {
      Map dataObj = jsonDecode(data);
      CommonToast.errToast('出错了，'.toString() + dataObj['message']);
    } else {
      Object? error = err.error;
      CommonToast.errToast('网络出错了，${error.toString()}');
    }

    super.onError(err, handler);
  }
}
