import axios from 'axios';
import config from '../config/config';
import axiosAdapterUniapp from 'axios-adapter-uniapp';
const service = axios.create({
  baseURL: config.baseApi, // url = base url + request url
  headers: {
    'X-Requested-With': 'XMLHttpRequest',
    'Content-Type': 'application/json-patch+json',
  },
  adapter: axiosAdapterUniapp,
  timeout: 5000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    if (uni.getStorageSync('ukey')) {
      config.headers['Authorization'] = 'Bearer ' + uni.getStorageSync('ukey');
    }

    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    const res = response.data;

    if (res.status == 250) {
      uni.showToast({
        title: `提示${res.msg}`,
        icon: 'error',
        duration: 1000,
      });
    }
    if (res.code == 30) {
      uni.showToast({
        title: `token已经过期需要重新登录`,
        icon: 'error',
        duration: 1000,
      });

      uni.removeStorageSync('ukey');

      uni.redirectTo({
        url: '/pages/login/login',
      });

      return;
    }

    return res;
  },
  (error) => {
    console.log('err' + error); // for debug
    return Promise.reject(error);
  }
);

export default service;
