// @ts-ignore
import Fly from "flyio/dist/npm/wx"
import config from "@/config";
import { useUserStore } from '@/store/userStore';
const { serverBaseUrl } = config;
const requestConfig = {
  baseURL: serverBaseUrl,
  timeout: 30000,
  headers: {
    "Content-Type": "application/json",
  },
  withCredentials: false,
};
const fly = new Fly();
fly.config = requestConfig;

const refreshFly = new Fly();
refreshFly.config = requestConfig;

fly.interceptors.request.use((request: any) => {
  const userStore = useUserStore();
  const token = userStore.accessToken;
  if (request.headers['TempToken']) {
    request.headers['Authorization'] = `Bearer ${request.headers['TempToken']}`;
  } else if (token) {
    request.headers['Authorization'] = 'Bearer ' + token;
  }
  const examType = userStore.getExamType;
  const location = userStore.getLocation;
  if (examType) {
    request.headers['examType'] = examType;
  }
  if (location) {
    request.headers['location'] = encodeURIComponent(location);
  }
  return request;
});
fly.interceptors.response.use(
  function (this: { lock: () => void; unlock: () => void }, response: any) { // 不要使用箭头函数，否则调用this.lock时this指向不对
    const result = response.data;
    try {
      const { code, msg } = result;
      if (code === 401) {
        logout();
      } else {
        if (code !== 200) {
          uni.$ie.showToast(msg);
          return Promise.reject(result);
        } else {
          return Promise.resolve(result);
        }
      }
    } catch (err) {
      return Promise.reject(result);
    }
  },
  function (err: Error, promise: Promise<any>) {
    return Promise.reject(err);
  }
);
function logout() {
  const userStore = useUserStore();
  userStore.logout();
  uni.reLaunch({
    url: '/pagesSystem/pages/login/login'
  });
}
export default fly;
