import axios from "axios";
import router from "../router";
import { showToast  } from "@nutui/nutui";
import tool from './tool';

let axiosPromiseCancel = [];
const CancelToken = axios.CancelToken;

let toast = null

let instance = axios.create({
  timeout: 1000 * 60,
  // baseURL: 'http://192.168.1.15:82'
  baseURL: 'https://nk.ifarmcloud.com/api'
})

// 请求拦截器
instance.interceptors.request.use(
  config => {

    const token = tool.data.get('snowy_token')
    const orgId = tool.data.get('snowy_org_id')
    const account =tool.data.get('snowy_user_info')?.account

    token && (config.headers.token = '' + token)

    config.cancelToken = new CancelToken((cancel) => {
      axiosPromiseCancel.push(cancel);
    });
    let data = config.data || config.params || {}

    if(account !== 'superAdmin') {
      orgId && ( data.orgId = orgId)
    }

    return config
  },
  error => Promise.error(error)
)

// 相应拦截器
instance.interceptors.response.use(
  response => {
    if(toast) {
      toast.hide();
    }
    toast = null;
    if(response.data.code === 200) {
      return response.data
    } else {
      errorHandle(response.data.code, response.data.msg)
    }
    // return response.data
    // const code = response.data.code;
    // if(code === 10000) {
    //   return response.data
    // } else {
    //   errorHandle(code, response.data.message)
    // }
  },
  error => {
    if(toast) {
      toast.hide();
    }
    toast = null;
    errorHandle(error.response.status, error.response.msg)
    return Promise.reject(error);
  }
)

/**
 *
 * 登录
 *
 * **/
const cancel = () => {
  axiosPromiseCancel.forEach(e=>{
    e && e()
  });
  axiosPromiseCancel = [];
}

const toLogin = () => {
  router.replace({
    path: '/login',
  })
}

/**
 * 请求失败后的错误统一处理
 * @param {Number} status 请求失败的状态码
 */

const errorHandle = (status, age) => {
  switch (status) {
    case 401:
      toLogin();
      cancel()
      showToast.fail('登录令牌不存在，请登录');
      break;
    case 403:
      toLogin();
      cancel()
      showToast.fail('登录令牌到期，即将重新登录');
      tool.data.remove('snowy_token')
      tool.data.remove('snowy_org_id')
      tool.data.remove('snowy_user_info')
      break;
    case 500:
      showToast.fail(age);
      break;
    default:
      return;
  }
}

export default instance


