import axios, { AxiosInstance, AxiosResponse } from 'axios'
import { RequestConfig, RequestInterceptors } from './types'
import { storage } from '@/utils'
import { constant } from '@/config'
import { message } from 'antd';
import { PostRefresh } from '@/api/Login';
class Request {
  // axios实例
  instance: AxiosInstance

  // 拦截器对象
  interceptorsObj?: RequestInterceptors

  constructor(config: RequestConfig) {
    // 创建实例
    this.instance = axios.create(config)
    // 类请求拦截器
    this.instance.interceptors.request.use(
      (req: any) => {
        const user = JSON.parse(storage.getItem('user') as string);
        if (user) {
          // 如果有token给请求头加上
          if (req.url.indexOf('auth/refresh?refreshToken=') === -1) {
            req.headers.Authorization = `Bearer ${user.token}`
          }
          req.timeout = constant.CONFIG_REQUEST_TIMEOUT_TIME
        }
        if (req.contentType) {
          req.headers["Content-Type"] = req.contentType;
        }
        return req
      },
      (_err: any) => {
      }
    )

    // 类响应拦截器
    this.instance.interceptors.response.use(
      (res: AxiosResponse) => {
        const { data: resData, status, config } = res
        if (status == constant.CONFIG_CODE_SUCCESS && resData && Object.prototype.toString.call(resData) == '[object Object]') {
          resData.success = false
          resData.code == constant.CONFIG_CODE_SUCCESS && (resData.success = true)
        }
        resData.headers = res.headers['content-disposition'];
        if (resData.code !== 200) {
          if (config.responseType === 'blob') {
            const reader = new FileReader() as any;
            reader.readAsText(res.data, "utf-8");
            reader.onload = function () {
              if (reader.result) {
                try {
                  message.error(JSON.parse(reader.result).message)
                } catch (error) {

                }
              }
            };
          } else {
            message.error(resData.message)
          }
        }
        if (resData.code === 1403) {
          toLogin()
        }
        return resData
      },
      (err: any) => {

        // 根据自己业务/接口返回做相应调整
        if (err.response) {
          const { status } = err.response
          switch (status) {
            case 401:
              updatePostRefresh()
              break
            case 403:
              updatePostRefresh()
              break
            default:
              message.error(err.message)
              break;
          }
        } else {
          switch (err.code) {
            case "ECONNABORTED":
              message.error('网络连接超时，请检查网络状态')
              break;
            case "ERR_NETWORK":
              message.error('网络已断开，请检查网络状态')
              break;
            default:
              message.error(err.message)
              break;
          }
        }
      }
    )
  }

  request<T>(config: RequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      // storage.setItem('loading', true)
      if (config.interceptors?.requestInterceptors) {
        config = config.interceptors.requestInterceptors(config)
      }
      this.instance
        .request<any, T>(config)
        .then((res: T) => {
          // 如果我们为单个响应设置拦截器，这里使用单个响应的拦截器
          if (config.interceptors?.responseInterceptors) {
            res = config.interceptors.responseInterceptors<T>(res)
          }
          resolve(res || { code: 0 } as any)
        })
        .catch((err: any) => {
          reject(err)
        }).finally(() => {
          // storage.setItem('loading', false)
        })
    })
  }
}
function toLogin() {
  storage.setItem('userLogin', false)
}
function updatePostRefresh() {
  let user = JSON.parse(storage.getItem('user') as string);
  if (user) {
    PostRefresh(user.refresh_token).then((res) => {
      if (res.code == 200) {
        storage.setItem('user', JSON.stringify(res.data))
        storage.setItem('userLogin', true)
      } else {
        toLogin()
      }
    })
  } else {
    toLogin()
  }
}
export default Request
