import axios from "axios"
import pathToRegexp from "path-to-regexp"
import { message } from "antd"
import config from "../commons"
const {page:{loginpage}} =config

axios.interceptors.request.use(
  config => {
      config.headers.common['WWW-Authenticate']=null;
      return config;
  },
  err => {
      return Promise.reject(err);
});


axios.interceptors.response.use(
  response => {
      return response;
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          const config = {
            content:"身份信息已过期，正在重新验证……",
            key:'logout'
          }
          message.warning(config)
          window.location.href=loginpage
      }
    }
    return Promise.reject(error.response.data)   // 返回接口返回的错误信息
  }
);



const fetch = options => {
  let { method = "get", data, url, config, ...opts } = options

  try {
    // const match = pathToRegexp.parse(url)
    url = pathToRegexp.compile(url)(data)
    // match.forEach(item => {
    //   if (item instanceof Object && data[item.name]) {
    //     delete data[item.name]
    //   }
    // })
    // For Ugly IE 304, Must add timestamp
    // url = url + `?t=${Date.now()}`
  } catch (e) {
    //message.error(e.message)
  }

  switch (method.toLowerCase()) {
    case "get":
      return axios.get(
        url,
        {
          params: data,
        },
        config
      )
    case "delete":
      return axios.delete(
        url,
        {
          data: data,
        },
        config
      )
    case "post":
      return axios.post(url, data, config)
    case "put":
      return axios.put(url, data, config)
    case "patch":
      return axios.patch(url, data, config)
    default:
      return axios(options)
  }
}

export default function request(options, successdo, errordo) {
  fetch(options)
    .then(response => {
      //console.log(response)
      if(response.status==302){
        console.log('redirect')
        window.location.reload();
      }
      //console.log("finish success try")
      if(successdo)
        successdo(response)
      else
        message.success('操作成功')
    })
    .catch(error => {
      //console.log('try throw 302')
      //console.log(error)
      //console.log(error.response)
      if(errordo)
        errordo(error)
    })
}
