import { queryCurrentUser, queryPermData } from './services/user'
import type { RequestConfig } from 'umi'
import { ErrorShowType } from 'umi'
import { history } from 'umi'
import RightContent from '@/components/RightContent'
import { message, notification } from 'antd'
import logo from '../public/logo.svg'
import { getToken } from '@/utils/auth'
import { tryChangeWorkStatus } from './components/RightContent/Book'
import { getAuthCache, setAuthCache } from './utils/auth'
import { LAYOUT_COLLAPSED_KEY } from './utils/cache/cacheEnum'
import consts from './consts'
import ModalStore from './components/ModalStore/import'
import { stringify } from 'qs'
import MessageDetail from './pages/Hr/Notification/components/MessageDetail'

const loginPath = '/user/login'

export async function getInitialState() {
  // 如果是登录页面，不执行
  const fetchUserInfo = async () => {
    try {
      const res = await queryCurrentUser()
      return res.data
    } catch (error) {
      history.push(loginPath)
    }
    return undefined
  }

  const fetchPermData = async () => {
    try {
      const res = await queryPermData()
      return res.data
    } catch (error) {
      message.error('获取数据权限失败，请联系管理员')
    }
    return {}
  }
  // 如果是登录页面，不执行
  if (history.location.pathname !== loginPath) {
    const userInfo = (await fetchUserInfo()) || {}
    const permData = (await fetchPermData()) || {}
    const collapsed = getAuthCache(LAYOUT_COLLAPSED_KEY) || false
    return {
      fetchUserInfo,
      fetchPermData,
      permData,
      ...userInfo,
      settings: { collapsed, defaultCollapsed: collapsed }
    }
  }
  return {
    fetchUserInfo,
    fetchPermData,
    settings: {}
  }
}

export const layout = ({ initialState, setInitialState }) => {
  const onCollapse = collapsed => {
    setInitialState({ ...initialState, settings: { ...initialState.settings, collapsed } })
    setAuthCache(LAYOUT_COLLAPSED_KEY, collapsed)
  }

  return {
    logo,
    rightContentRender: () => (
      <ModalStore _modalMap={{ D_NOTICE_DETAIL: MessageDetail }}>
        <RightContent />
      </ModalStore>
    ),
    disableContentMargin: false,
    waterMarkProps: initialState.currentUser && {
      fontColor: 'rgba(0,0,0,.1)',
      offsetTop: 200,
      content: `${initialState.currentUser?.username}  ${initialState.currentUser?.telephone.slice(-4)}`
    },

    onPageChange: async location => {
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser?.staffId && location.pathname !== loginPath) {
        history.replace({
          pathname: loginPath,
          search: stringify({
            redirect: history.location.pathname
          })
        })
      } else {
        location.pathname !== loginPath &&
          tryChangeWorkStatus(initialState?.currentUser?.staffId, location.pathname)
      }
    },
    childrenRender: children => <ModalStore>{children}</ModalStore>,
    ...initialState?.settings,
    breakpoint: false,
    onCollapse
  }
}

let notificationLimit = 0 // 最大1
const errorHandler = error => {
  const { data, info } = error
  if (info) {
    const { errorMessage = '请求失败', showType, errorCode } = info
    if (consts.TOKEN_INVALID_CODE.includes(errorCode) && window.location.pathname !== loginPath) {
      history.replace({
        pathname: loginPath,
        search: stringify({
          redirect: window.location.pathname
        })
      })
    }
    switch (showType) {
      case ErrorShowType.ERROR_MESSAGE:
        message.error(errorMessage)
        break
      case ErrorShowType.WARN_MESSAGE:
        message.warn(errorMessage)
        break
      case ErrorShowType.NOTIFICATION:
        if (!notificationLimit) {
          const title = consts.TOKEN_INVALID_CODE.includes(errorCode) ? '用户信息过期' : '请求失败'
          notification.error({
            message: title,
            description: errorMessage
          })
          notificationLimit++
        }
        break
      default:
        break
    }
    return Promise.reject(data)
  } else {
    notification.error({
      description: '您的网络发生异常，无法连接服务器',
      message: '网络异常'
    })
  }
  return Promise.reject(error)
}

const authHeaderInterceptor = (url, options) => {
  const token = getToken()
  if (token) {
    // 在白名单里的请求放过
    if (consts.TOKEN_WHITE_LIST.includes(url)) {
      return { url, options }
    }
    // eslint-disable-next-line no-param-reassign
    options.headers[consts.TOKEN_HEADER] = `bearer ${token}`
    return { url, options }
  }
  return { url, options }
}

export const request: RequestConfig = {
  errorHandler,
  prefix: '/api',
  // 默认错误处理
  credentials: 'include', // 默认请求是否带上cookie
  prefix: consts.PREFIX_URL,
  cache: 'no-cache',
  errorConfig: {
    adaptor: resData => {
      if (notificationLimit !== 0 && resData.code === consts.RET_CODE.SUCCESS) {
        notificationLimit = 0
      }
      return {
        success: resData.code === consts.RET_CODE.SUCCESS,
        errorMessage: resData.msg,
        errorCode: resData.code,
        showType: resData.showType
      }
    }
  },
  requestInterceptors: [authHeaderInterceptor]
}
