import { getToken, removeToken } from './../utils/auth';
import { extend } from 'umi-request'
import { ElMessage } from 'element-plus'
import cleanDeep from 'clean-deep'
import router from '../router';
import { showLoading, hideLoading } from '../utils/loading'
// import { setLogout } from 'src/actions/users'
// import store from 'src/store'

export interface SearchInitParams {
  rows?: string | number;
  page?: string | number;
}

export interface InitSearchRespones {
  data: {
    rows: any[],
    [key: string]: any
  },
  [key: string]: any
}

const request = extend({
  requestType: 'form',
  timeout: 10000
})

request.interceptors.request.use((url, options: any) => {
  let hideLoading = options.hideLoading || false
  if(!hideLoading) {
    showLoading()
  }
  const Authorization = getToken()
  const tenantId = (localStorage.getItem('tenantId') || '')
  const organId = (localStorage.getItem('organId') || '')
  const authHeaders: any = {}
  if (Authorization && !['/api-auth/usernameLogin', '/api-auth/smsLogin', '/api-auth/code/sendSms'].includes(url)) {
    authHeaders.Authorization = Authorization
  }
  if (tenantId) {
    authHeaders.tenantId = tenantId
  }
  if (organId) {
    authHeaders.organId = organId
  }
  return {
    url,
    options: {
      ...options,
      params: cleanDeep(options.params),
      headers: {
        ...options.headers,
        ...authHeaders
      }
    }
  }
})

request.interceptors.response.use(async (res, options) => {
  setTimeout(() => {
    hideLoading()
  }, 200)
  let hideMessage = options.hideMessage || false
  const url = new URL(res.url)
  if (res.status > 299 || res.status < 200) {
    const msg = '服务器错误，状态码' + res.status
    if (!hideMessage) {
      ElMessage.error(msg)
    }
    throw new Error(msg)
  }
  const data = await res.clone().json()
  if (data.code !== 200 && data.errCode !== 0) {
    const msg = data.msg || '处理失败，请重试'
    if(data.code === 401 || data.code === 403) {
      if(!hideMessage) {
        ElMessage.error(`登录过期，请重新登录！`)
      }
      removeToken()
      router.push(`/login`)
    }
    if(data.code === 404) {
      if(!hideMessage) {
        ElMessage.error(`请求资源不存在！`)
      }
      router.push('/404')
    }
    if (!(data.code === 403 || data.code === 401)) {
      if (!hideMessage) {
        ElMessage.error(msg)
      }
    }
    throw new Error(msg)
  }
  return res
})

export default request
