/*
 * @Author: your name
 * @Date: 2021-04-23 15:39:41
 * @LastEditTime: 2021-12-06 16:22:22
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /react-antd-admin-template/src/utils/request.js
 */
import axios from "axios";
import store from "@/store";
import { Modal } from "antd";
import { getToken } from "@/utils/auth";
import { logout } from "@/store/actions";

//创建一个axios示例
const service = axios.create({
  baseURL: process.env.REACT_APP_BASE_API, // api 的 base_url
  timeout: 5000, // request timeout
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    // Do something before request is sent
    if (store.getState().user.token) {
      config.headers.token = getToken();
    }
    return config;
  },
  (error) => {
    // Do something with request error
    console.log(error); // for debug
    Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response) =>{
    const {data} = response;
    if(data.status===200){
      return response;
    }else if(data.status==499){
      console.log('登录过期');
      const {msg} = data;
      Modal.confirm({
        title: "抱歉，登录已过期请重新登录！",
        okText: "确定",
        onOk() {
          store.dispatch(logout());
        },
        onCancel() {
          console.log("Cancel");
        },
      });
      // return Promise.reject('error');
    }else {
      const {msg} = data;
      Modal.confirm({
        title: "抱歉，出现错误！",
        content:msg,
        okText: "确定",
        onOk() {}
      });
    }
    
  },
  (error) => {
    console.log("err" + error); // for debug
    const {msg } = error.response;
    Modal.confirm({
      title: "抱歉，出现错误！",
      content:msg,
      okText: "确定",
      onOk() { }
    });
    return Promise.reject(error);
  }
);

export default service;
