import axios, {
  AxiosError,
  AxiosHeaders,
  AxiosInstance,
  AxiosProgressEvent,
  AxiosRequestConfig,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "@ohos/axios";
import { AppCache } from '../app/AppCache';
import { UserCache } from '../app/UserCache';
import { StringUtils } from '../util/StringUtils';

// private _baseUrl: string = "http://192.168.43.98:8080/hc/phone/";

// axios 请求配置
const config: AxiosRequestConfig = {
  // baseURL: AppCache.getAppCache().getServiceAddress(),
  baseURL: "http://20.90.2.2/pcenter_app_out/",
  timeout: 1000 * 30,
  connectTimeout: 30 * 1000,
  readTimeout: 30 * 1000,
}

// 定义返回值类型
interface Result<T = ESObject> {
  code: number;
  message: string;
  data: T;
}

class Http {
  // axios 实例
  private instance: AxiosInstance;

  // 构造函数初始化
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(config);
    //定义拦截器
    this.interceptors();
  }

  private interceptors() {
    // axios 发送请求之前的处理
    this.instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
      // 在请求头部携带token
      let token = UserCache.getUserCache().getUserInfo();
      if (token) {
        // 把 token 放到 headers 里面
        config.headers!['userInfo'] = token;
      }
      let pgToken = AppCache.getAppCache().getPgToken;
      if (pgToken) {
        config.headers!['Authorization'] = pgToken;
      }
      // 打印请求URL
      console.log('请求URL: ' + config.url);
      // 打印请求参数
      if (config.params) {
        console.log('请求参数(params): ' + JSON.stringify(config.params));
      }

      if (config.data) {
        console.log('请求参数(data): ' + JSON.stringify(config.data));
      }
      if (config.headers) {
        console.log('请求参数(data): ' + JSON.stringify(config.headers));
      }
      console.log('请求参数', JSON.stringify(config));
      return config;

    }, (error: ESObject) => {
      error.data = {};
      error.data.msg = '服务器异常，请联系管理员！'
      return error;
    })
    // axios 请求返回之后的处理
    // 请求返回处理
    this.instance.interceptors.response.use((res: AxiosResponse) => {
     let config:InternalAxiosRequestConfig =  res.config
      // 打印请求URL
      console.log(`code: ${res.status} |: ${config.url}`);
      // 打印请求参数
      if (config.params) {
        console.log('请求参数(params): ' + JSON.stringify(config.params));
      }
      if (config.data) {
        console.log('请求参数(data): ' + JSON.stringify(config.data));
      }
      if (config.headers) {
        console.log('请求参数(data): ' + JSON.stringify(config.headers));
      }
      if (res.config.responseType == 'array_buffer' || res.config.responseType == 'ARRAY_BUFFER') {
        return res;
      }
      let msg = JSON.stringify(res.data);
      msg = StringUtils.toJsonParaphrase(msg);
      console.info('获取到的数据:' + msg);
      if (res.status != 200) {
        console.log(res.data.msg || '服务器出错啦');
        return Promise.reject(res.data.msg || '服务器出错啦');
      }
      return res.data;
    }, (error: AxiosError) => {
      console.log('进入错误！');
      // error.data = {};
      if (error.code == "2300028") {
        error.message = "网络超时";
      } else {
        if (error && error.response) {
          switch (error.response.status) {
            case 400:
              error.message = "错误请求";
              break;
            case 401:
              error.message = "未授权，请登录";
              break;
            case 403:
              error.message = "拒绝访问";
              break;
            case 404:
              error.message = "请求错误，未找到该资源";
              break;
            case 405:
              error.message = "请求方法未允许";
              break;
            case 408:
              error.message = "请求超时";
              break;
            case 500:
              error.message = "服务器端出错";
              break;
            case 501:
              error.message = "网络未实现";
              break;
            case 502:
              error.message = "网络错误";
              break;
            case 503:
              error.message = "服务不可用";
              break;
            case 504:
              error.message = "网络超时";
              break;
            case 505:
              error.message = "http版本不支持该请求";
              break;
            default:
              error.message = `连接错误${error.response.status}`;
          }
        } else {
          error.message = "连接到服务器失败";
        }
      }
      console.log(error.message)
      return Promise.reject(error);
    })
  }

  // GET方法
  get<T = Result>(url: string, params?: object, headers?: AxiosHeaders): Promise<T> {
    return this.instance.get(url, { params, headers: headers });
  }

  // POST方法
  post<T = Result>(url: string, data?: object, headers?: AxiosHeaders): Promise<T> {
    return this.instance.post(url, data, { headers: headers });
  }

  // POST方法
  postFromJson<T = Result>(url: string, data?: string): Promise<T> {
    return this.instance.post(url, data,
      { headers: new AxiosHeaders({ 'Content-Type': 'application/json; charset=utf-8' }) });
  }

  // POST方法
  postFromBody<T = Result>(url: string, data?: object, headers?: AxiosHeaders): Promise<T> {
    return this.instance.post(url, null, { params: data, headers: headers });
  }

  // PUT方法
  put<T = Result>(url: string, data?: object): Promise<T> {
    return this.instance.put(url, data);
  }

  // DELETE方法
  delete<T = Result>(url: string): Promise<T> {
    return this.instance.delete(url);
  }

  /**
   * 下载文件
   * @param url
   * @returns A required parameter cannot follow an optional parameter.
   */
  download<T = Result>(url: string, filePath: string,
    callback?: (progressEvent: AxiosProgressEvent) => void): Promise<T> {
    return this.instance.post(url, null,{ filePath: filePath,responseType:'ARRAY_BUFFER',
      headers:new AxiosHeaders({
      'Content-Type': `application/x-www-form-urlencoded;`}),
      onDownloadProgress: callback });
  }
}

export default new Http(config);



