import { useEffect, useCallback } from 'react'
import { Button, Flex, Dropdown } from 'antd'
import { UserOutlined } from '@ant-design/icons'
import { useDispatch, useSelector } from 'react-redux'
import { setUserInfo } from '@/store/modules/user'
import { getUser } from '@/api/base'
import { Link } from 'react-router-dom'

function User() {
  const dispatch = useDispatch()
  const { userInfo } = useSelector(state => state.user)

  const fetchUser = useCallback(async () => {
    const { data } = await getUser()
    dispatch(setUserInfo(data))
  }, [dispatch])

  useEffect(() => {
    fetchUser()
  }, [fetchUser])

  const menuItems = [
    {
      key: 'user',
      label: <Link to="/userinfo">个人中心</Link>
    }
  ]

  return (
    <Dropdown menu={{ items: menuItems }} arrow>
      <Button style={{ border: 'none', background: '#f6f6f6' }}>
        <Flex align="center" gap="small">
          {userInfo.pic ? <img src={userInfo.pic} style={{ width: '28px', height: '28px', borderRadius: '50%', objectFit: 'cover' }} /> : <UserOutlined />}
          {userInfo.real_name}
        </Flex>
      </Button>
    </Dropdown>
  )
}

export default User
