import { queryCurrentUser, queryPermData } from './services/user'
import { history } from 'umi'
import RightContent from '@/components/RightContent'
import { message } from 'antd'
import logo from '../public/logo.svg'
import BasicModal, { BasicDrawer } from '@/components/Modal'

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 currentUser = (await fetchUserInfo()) || {}
    const permData = (await fetchPermData()) || {}

    return {
      fetchUserInfo,
      fetchPermData,
      permData,
      ...currentUser,
      settings: {}
    }
  }
  return {
    fetchUserInfo,
    fetchPermData,
    settings: {}
  }
}

export const layout = ({ initialState }) => {
  return {
    logo,
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.username
    },
    onPageChange: async () => {
      const { location } = history
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser?.staffId && location.pathname !== loginPath) {
        history.replcae('/user/login')
      }
      // if (
      //   initialState?.currentUser?.staffId &&
      //   location.pathname !== loginPath &&
      //   PERMISSION_NEED_PATH.includes(location.pathname) &&
      //   !initialState?.permData
      // ) {
      //   const permData = await initialState.fetchPermData()
      //   permData && setInitialState({ ...initialState, permData })
      // }
    },
    childrenRender: children => (
      <>
        {children}
        <BasicDrawer />
        <BasicModal />
      </>
    ),
    // menuHeaderRender: false,
    ...initialState?.settings
  }
}
