import axiosConfig from "./axios_config";
import axios, { AxiosError, InternalAxiosRequestConfig } from 'axios';

const service = axios.create(axiosConfig);


export const UserDataStorageName = "StaffAI-UserData"

// 请求拦截
service.interceptors.request.use(

  (config: InternalAxiosRequestConfig) => {

    console.log("config", config)

    let token = ''

    if (typeof window !== 'undefined') {
      const UserData = localStorage.getItem(UserDataStorageName)
      if (UserData) {
        try {
          token = JSON.parse(UserData).auth_token
        } catch (error) {
          console.log("-----", error)
        }

        if (!!token) {
          // config.headers = {
          //   Authorization: token,
          // };
          config.headers.Authorization = token
        }
      }
    }



    return config;
  },
  (error: AxiosError) => {
    console.log(error);
    return Promise.reject(error);
  }
  // config => {


  //   // (config.headers as any).Authorization = 'Bearer' + ' ' + store.getState().chatgpt.token;
  //   // if (config.data) {
  //   //   config.data = JSON.stringify(config.data);
  //   // };
  //   // if (config.method?.toLocaleLowerCase() === 'get') {
  //   //   config.paramsSerializer = function (params) {
  //   //     return qs.stringify(params, { arrayFormat: 'repeat' })
  //   //   }
  //   // };
  //   return config;
  // },
  // (error: any) => {
  //   return Promise.reject(error);
  // }
);

// 响应拦截
service.interceptors.response.use(
  (res: any) => {
    // let data = JSON.parse(res.data);
    let data = res.data;
    console.log("=========interceptors:", data)

    return data;
  },
  (error: { response: { data: any; status: number }; }) => {

    try {
      console.log("=========interceptors err:", error.response.status === 401)
      // let data = JSON.parse(error.response.data);
      if (error.response.status === 401) {
        console.log("go sign in ==> ")
        window.location.href = `/auth/sign-in/`
        return
      };
      return error.response.data
    } catch (error) {
      return error
    }

  }
)

export default service;