/* eslint-disable */
import React, { useCallback } from 'react'
import { InfoCircleFilled, LogoutOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons'
import { Avatar, Menu, Spin, Modal } from 'antd'
import { history, useModel } from 'umi'
import { stringify } from 'querystring'
import HeaderDropdown from '../HeaderDropdown'
import styles from './index.less'
import { clearAuthCache, removeToken } from '@/utils/auth'
import ws from '@/utils/ws'
import { isDevMode } from '@/utils/env'
import consts from '@/consts'

export type GlobalHeaderRightProps = {
  menu?: boolean
}

/**
 * 退出登录，并且将当前的 url 保存
 */
const loginOut = async () => {
  const { query = {}, pathname } = history.location
  const { redirect } = query
  // Note: There may be security issues, please note
  if (window.location.pathname !== '/user/login' && !redirect) {
    // 断开socket连接
    ws.disconnect()
    history.replace({
      pathname: '/user/login',
      search: stringify({
        redirect: pathname
      })
    })
  }
}

const AvatarDropdown: React.FC<GlobalHeaderRightProps> = ({ menu }) => {
  const { initialState, setInitialState } = useModel('@@initialState')

  const onMenuClick = useCallback(
    (event: {
      key: React.Key
      keyPath: React.Key[]
      item: React.ReactInstance
      domEvent: React.MouseEvent<HTMLElement>
    }) => {
      const { key } = event
      if (key === 'logout' && initialState) {
        return Modal.confirm({
          icon: <InfoCircleFilled />,
          title: '温馨提示',
          content: '是否确认退出系统？',
          onOk: () => {
            // 清除AuthCache
            removeToken()
            setInitialState({ ...initialState, currentUser: undefined, roles: [], permData: {} })
            loginOut()
            return
          }
        })
      }
      return history.push(`/account/${key}`)
    },
    [initialState, setInitialState]
  )

  const loading = (
    <span className={`${styles.action} ${styles.account}`}>
      <Spin
        size="small"
        style={{
          marginLeft: 8,
          marginRight: 8
        }}
      />
    </span>
  )

  if (!initialState) {
    return loading
  }

  const { currentUser } = initialState

  if (!currentUser || !currentUser.staffId) {
    return loading
  }

  const menuItems = [
    { icon: <SettingOutlined />, label: '个人设置', key: 'settings' },
    { icon: <LogoutOutlined />, label: '退出登录', key: 'logout' }
  ]
  const menuHeaderDropdown = (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick} items={menuItems} />
  )

  return (
    <HeaderDropdown overlay={menuHeaderDropdown}>
      <span className={`${styles.action} ${styles.account}`}>
        <Avatar
          size="small"
          className={styles.avatar}
          src={
            (isDevMode() ? 'http://cld2qa.com' : 'http://zhcld.com') +
            (currentUser?.avatar ?? consts.DEFAULT_AVATAR)
          }
          alt="avatar"
        />
        <span className={`${styles.name} anticon`}>{currentUser.username}</span>
      </span>
    </HeaderDropdown>
  )
}

export default AvatarDropdown
