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

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

let toast = null

let instance = axios.create({
  timeout: 1000 * 60,
  baseURL: 'https://img.ifarmcloud.com/guoweiApi/'
})

// 请求拦截器
instance.interceptors.request.use(
  config => {
    if(config.url === '/send/play') {
      toast = showToast.loading('数据获取中', { cover: true, duration: 0 });
    }

    const token = localStorage.getItem('gw_token');

    token && (config.headers.accessToken = token)

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

    const farmId = localStorage.getItem('gw_farmId')

    farmId && ( data.farmId = farmId)

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

// 相应拦截器
instance.interceptors.response.use(
  response => {
    if(toast) {
      toast.hide();
    }
    toast = null;
    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)
    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('登录令牌到期，即将重新登录');
      localStorage.removeItem('gw_token');
      localStorage.removeItem('gw_userName');
      localStorage.removeItem('gw_userId');
      localStorage.removeItem('gw_userInfo');
      localStorage.removeItem('gw_farmId')
      break;
    case 500:
      showToast.fail('500-服务器未知异常');
      break;
    default:
      return;
  }
}

export default instance


