import { notification } from "antd";
import axiosConfig from "./axios_config";
import axios from 'axios';

const service = axios.create(axiosConfig);

// 请求拦截
service.interceptors.request.use(
  config => {

    console.log("config", config)

    const token = '' + localStorage.getItem('token')
    if (!!token) {
      config.headers = {
        Authorization: token,
      };
    }

    // (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("==> ", res, data)

    if (data.header.code != 0) {

      if (data.header.code == 1001) {

        notification.info({
          message: `请重新登录`,
          description: data.header.message,
        })

        window.location.href = "/user/login"

        return Promise.reject("")

      }

      notification.error({
        message: `请求错误 ${data.header.status}: ${res.config.url}`,
        description: data.header.message,
      });
      return Promise.reject("")
    }

    return data;
  },
  (error) => {

    try {

      console.log("response: ", error)
      notification.error({
        message: `请求错误 ${error.status}: ${error.url}`,
        description: error,
      });
      // let data = JSON.parse(error.response.data);
      // // if (data.code === 500) {
      // //   console.log(error)
      // // };
      // return data
    } catch (error) {
      console.log(error)
    }

    window.location.href = "/user/login"

  }
)

// service.interceptors.response.use(function (response) {
//   // Any status code that lie within the range of 2xx cause this function to trigger
//   // Do something with response data
//   return response;
// }, function (error) {
//   // Any status codes that falls outside the range of 2xx cause this function to trigger
//   // Do something with response error
//   return Promise.reject(error);
// });

export default service;