import { ToastAndroid } from 'react-native';
import { NavigationActions, StackActions } from '@react-navigation/native';
import axios, { AxiosResponse, InternalAxiosRequestConfig } from 'axios';
import env from './env';
import utils from '../utils/index';

function jumpTo(){
  //不直接用navigation.navigate是因为登录重新开始之前的页面消除
  const resetAction = StackActions.replace('Login');
  navigation.dispatch(resetAction);
};

function tansParams(params){
  let result = '';
  for (const propName of Object.keys(params)) {
    const value = params[propName];
    const part = encodeURIComponent(propName) + '=';
    if (value !== null && value !== '' && typeof value !== 'undefined') {
      if (typeof value === 'object') {
        for (const key of Object.keys(value)) {
          if (value[key] !== null && value[key] !== '' && typeof value[key] !== 'undefined') {
            const params = propName + '[' + key + ']';
            const subPart = encodeURIComponent(params) + '=';
            result += subPart + encodeURIComponent(value[key]) + '&';
          }
        }
      } else {
        result += part + encodeURIComponent(value) + '&';
      }
    }
  }
  return result;
};

axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8';
axios.defaults.headers['auth'] = true;
// 创建 axios 实例
const service = axios.create({
  baseURL: env,
  timeout: 20000
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    //console.log("config", config)
    const token = '';
    if (token && Boolean(config.headers['auth']) == true) {
      config.headers['Authorization'] = 'JWT ' + token;
    }
    if (!token && Boolean(config.headers['auth']) == true) {
      delete config.headers['auth'];
      const message = '缺少凭证，请重新登录！';
      ToastAndroid.show(message, 5 * 1000);
      jumpTo();
      return Promise.reject(message);
    }
    // get请求修改Content-Type
    if (config.method?.toLowerCase() === 'get') {
      config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    }
    // get请求映射params参数
    if (config.method === 'get' && config.data) {
      let url = config.url + '?' + utils.tansParams(config.data);
      url = url.slice(0, -1);
      config.data = {};
      config.url = url;
    }
    // FormData数据去请求头Content-Type
    if (config.data instanceof FormData) {
      delete config.headers['Content-Type'];
    }
    delete config.headers['auth'];
    return config;
  },
  (error: any) => {
    console.log("333",error);
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (res: AxiosResponse) => {
    console.log("res1111111",res)
    const code = res.data.code;
    const status = res.data.status;
    const message = res.data.message;
    console.log("111111111111")
    if (code === 401) {
      jumpTo();
      ToastAndroid.show(message, 5 * 1000);
      return Promise.reject('凭证已过期，请重新登录！');
    } else if (status == 500) {
      ToastAndroid.show(message, 5 * 1000);
      return Promise.reject(message);
    } else {
      return Promise.resolve(res);
    }
  },
  (error: any) => {
    let { message, response } = error;
    if (message == 'Network Error') {
      message = '网络异常';
    } else if (message.includes('timeout')) {
      message = '请求超时';
    } else if (response.status == 401) {
      jumpTo();
      ToastAndroid.show('请重新登录', 5 * 1000);
      return Promise.reject('凭证已过期，请重新登录！');
    } else if (message.includes('Request failed with status code')) {
      if (response.data.status) {
        message = response.data.message;
      } else {
        message = '系统接口' + message.substr(message.length - 3) + '异常';
      }
    }
    ToastAndroid.show(message, 5 * 1000);
    return Promise.reject(error);
  }
);

export default service;
