import { Button, message, notification, Result } from 'antd';
import axios, { AxiosRequestConfig } from 'axios'

// 标识登录过期的状态
let expired = false;

function Ajax(url?: string, params?: AxiosRequestConfig) {
  const ajax = axios.create({
    //   baseURL: api, // api的base_url  process.env.BASE_API,,注意局域网访问时，不能使用localhost
    timeout: 60 * 1000 * 5, // 请求超时时间
    headers: { ['Authorization']: 'Bearer ' + localStorage.getItem('Admin-Token') }
  });
  return ajax({
    ...params,
    url,
    method: params?.method ? params?.method : 'GET'
  }).then(res => {
    let resData = res?.data || { code: 600 }
    if (resData.code === 500) {
      let msg = localStorage.getItem('ErrMsg')
      if (resData.msg === '令牌验证失败') {//
        if (window.location.pathname !== '/login') {
          if (!msg) {
            const key = `open${Date.now()}`;
            const btn = (
              <Button type="primary" onClick={() => {
                localStorage.removeItem('Admin-Token')
                sessionStorage.removeItem('userId')
                notification.destroy(key)
                localStorage.removeItem('ErrMsg')
                window.location.href = window.location.origin + '/#/login'
              }}>
                重新登录
              </Button>
            );
            const description = (
              <Result
                status="500"
                title='令牌验证失败！'
                subTitle="长时间没有操作，令牌失效请重新登录！"
                extra={btn}
              />
            )
            localStorage.setItem('ErrMsg', 'true')
            notification.open({
              message: '',
              description,
              duration: null,
              // getContainer: () => document.getElementById('notificationPop') as any  || document.getElementById('root') as any,
              key,
              style: { zIndex: 999999, right: '50%', top: '50%', transform: 'translate(50%, -50%)', position: 'fixed', transition: 'all 0s' },
              onClose: () => {
                localStorage.removeItem('Admin-Token')
                sessionStorage.removeItem('userId')
                localStorage.removeItem('ErrMsg')
                window.location.href = window.location.origin + '/#/login'
              }
            });
          }
          return { ...resData }
        } else {
          localStorage.removeItem('Admin-Token')
          sessionStorage.removeItem('userId')
        }
      }
      if (!msg) {
        localStorage.setItem('ErrMsg', 'true')
        notification.error({
          message: resData.msg,
          onClose: () => {
            localStorage.removeItem('ErrMsg')
          }
        });
      }
    }
    if (resData.code === 310) {//权限错误
      localStorage.removeItem('Admin-Token')
      sessionStorage.removeItem('userId')
      if (expired) return; // 避免多次触发
      expired = true;
      message.error({
        content: resData.msg,
        duration: 2,
        onClose: () => {
          window.location.href = window.location.origin + '/#/login'
        }
      })
    }
    return res.data
  }).catch(err => {
    return Promise.reject(err)
  })
}
export default Ajax