/*
 * @Author: lei 2897821407@qq.com
 * @Date: 2022-09-05 09:58:04
 * @LastEditors: lei 2897821407@qq.com
 * @LastEditTime: 2022-09-05 11:13:00
 * @FilePath: \dexnav_web\src\utils\request.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from 'axios';
// import { TOKEN_NAME } from '@/config/global';
// import Cookies from 'js-cookie';
// import Store, { store } from '@/store/index';
import { MessagePlugin } from 'tdesign-vue-next';

const instance = axios.create({
  // baseURL: host,
  // timeout: 1000,
  withCredentials: true,
});

// instance.interceptors.request.use((config) => {
//   // let token = Cookies.get(TOKEN_NAME);
//   // if (token) {
//   //   config.headers['Authorization'] = token;
//   // }
//   // return config;
// });

instance.defaults.timeout = 60000;

instance.interceptors.response.use(
  (response) => {
    const router = useRouter();
    const Cookie = useCookie('userCookie');
    const { data, headers } = response;
    // 判断是否有authorization
    try {
      if (headers.hasOwnProperty('authorization')) {
        let newToken = headers.authorization.slice(
          7,
          headers.authorization.length
        );
        // 更新cookie
        Cookie.value = newToken;
      }
    } catch (e) {
      console.log(e);
    }
    // 如果-1，则为限制ip,跳转限制页面
    if (data.code === -1) {
      router.push({
        path: '/refuse',
      });
      return;
    }
    if (data.code === 200) {
      return data.data;
    } else if (data.code === 0) {
      return data;
    } else if (data.code === 2) {
      MessagePlugin.closeAll();
      MessagePlugin.warning('登录信息已过期');
      router.push({
        path: '/login',
      });
      return;
    } else {
      //@ts-ignore
      if (response.config.needCode) {
        return data;
      } else {
        MessagePlugin.closeAll();
        MessagePlugin.error(data.msg || '请求错误,请稍后重试');
        return Promise.reject(data.msg);
      }
    }
  },
  (err) => {
    const { config } = err;
    const { code, message: msg } = err.response.data;
    MessagePlugin.error(msg || '请求错误,请稍后重试');
    if (!config || !config.retry) return Promise.reject(err);

    config.retryCount = config.retryCount || 0;

    if (config.retryCount >= config.retry) {
      return Promise.reject(err);
    }

    config.retryCount += 1;

    const backoff = new Promise((resolve) => {
      setTimeout(() => {
        resolve(null);
      }, config.retryDelay || 1);
    });

    return backoff.then(() => instance(config));
  }
);

export default instance;
