import Taro from '@tarojs/taro';

import { getRoleType } from '@/utils/app';
import { isDev } from '@/utils/common';

import { getToken } from './utils';

const tokenInterceptor: Taro.interceptor = (chain: Taro.Chain) => {
  const requestParams = chain.requestParams;
  const token = getToken();
  // console.log('tokenInterceptor', requestParams.url, token);
  if (token) {
    requestParams.header = {
      ...requestParams.header,
      Authorization: 'Bearer ' + token,
    };
  }
  return chain.proceed(requestParams).then(res => res);
};

const roleInterceptor: Taro.interceptor = (chain: Taro.Chain) => {
  const requestParams = chain.requestParams;
  const roleType = getRoleType();
  requestParams.header = {
    ...requestParams.header,
    'role-type': roleType,
  };
  return chain.proceed(requestParams).then(res => res);
};

const interceptors = [tokenInterceptor, roleInterceptor];

if (isDev()) {
  // logInterceptor - 用于打印请求的相关信息
  interceptors.push(Taro.interceptors.logInterceptor);
}

export default interceptors;
