import { queryCurrentUser, queryPermData } from './services/user'
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/Modal1'

const loginPath = '/user/login'

// 重新构建MenuData，解决重定向没有权限的路由
// const generateMenu = (menuData, permission) => menuData.map(menu => {

// })

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()) || {}

    // if (userInfo?.currentUser?.staffId) {
    //   const { username, staffId: id, wsToken: token } = userInfo?.currentUser
    //   ws.init(`ws://cld2qa.com/summon/v1/chat/link?username=${username}&id=${id}&token=${token}`, {
    //     onMessage
    //   })
    // }

    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,
    // menu: {
    //   params: {
    //     userId: initialState?.currentUser?.staffId
    //   },
    //   request: (_, defaultMenuData) => {
    //     console.log('defaultMenuData', defaultMenuData)

    //     return defaultMenuData
    //   }
    // },
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.username
    },
    onPageChange: async location => {
      // 如果没有登录，重定向到 login
      if (!initialState?.currentUser?.staffId && location.pathname !== loginPath) {
        history.replace('/user/login')
      } else {
        location.pathname !== loginPath &&
          tryChangeWorkStatus(initialState?.currentUser?.staffId, location.pathname)
      }

      // 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 => <ModalStore>{children}</ModalStore>,
    // links: [
    //   <div className="ant-menu-title-content">
    //     <AddressBook theme="outline" className="anticon" />
    //     <span className="ant-pro-menu-item-title">通讯录</span>
    //   </div>
    // ],
    // menuHeaderRender: false,
    ...initialState?.settings,
    breakpoint: false,
    onCollapse
  }
}

const errorHandler = error => {
  const { response } = error

  if (response && response.status) {
    const errorText = codeMessage[response.status] || response.statusText
    const { status, url } = response
    notification.error({
      message: `请求错误 ${status}: ${url}`,
      description: errorText
    })
  } else if (!response) {
    notification.error({
      description: '您的网络发生异常，无法连接服务器',
      message: '网络异常'
    })
  }

  return response
}

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 }
}

const refreshTokenIfNeed = async (response, config) => {
  const res = await response.clone().json()
  if (
    res &&
    res.code !== consts.RET_CODE.SUCCESS &&
    !consts.TOKEN_INVALID_CODE.includes(res.code) &&
    config.url !== '/api/login'
  ) {
    message.error((res && res.msg) || '请求错误')
    // return Promise.reject(response)
    return response
  }
  if (res && res.code && consts.TOKEN_INVALID_CODE.includes(res.code)) {
    history.replace(consts.LOGIN_PATH)
  }
  return response
}

/**
 * 配置request请求时的默认参数
 */

export const request: RequestConfig = {
  errorHandler,
  prefix: '/api',
  // 默认错误处理
  credentials: 'include', // 默认请求是否带上cookie
  prefix: consts.PREFIX_URL,
  cache: 'no-cache',
  responseInterceptors: [(response, options) => refreshTokenIfNeed(response, options)],
  requestInterceptors: [authHeaderInterceptor]
}
