import consts from '@/consts'
import { queryNoticeList, queryUnreadNotice, updateNotice } from '@/services/login'
import { BellOutlined } from '@ant-design/icons'
import { Badge, Tabs, List, Typography, Popover } from 'antd'
import { useState, useCallback, useEffect } from 'react'
import styles from './index.less'

const DropdownContent = ({ noticeCount }) => {
  const [state, setState] = useState({
    noticesTotal: 0,
    notices: []
  })
  const getNotices = useCallback(async () => {
    const {
      code = -1,
      data: { message, total }
    } = await queryNoticeList()
    if (code === consts.RET_CODE.SUCCESS) {
      setState({ ...state, noticesTotal: total, notices: message })
    }
  }, [])
  useEffect(() => {
    getNotices()
  }, [])
  const toggleNotice = id => {
    const nNotices = state.notices.map(item => {
      if (item.id === id) {
        return { ...item, isRead: 1 }
      }
      return item
    })
    setState({ ...state, notices: nNotices })
  }

  const handleTitleClick = async item => {
    // 未读
    if (!item.isRead) {
      const { code = -1 } = await updateNotice({ id: item.id })
      if (code === consts.RET_CODE.SUCCESS) {
        toggleNotice(item.id)
      }
    }
  }
  return (
    <Tabs>
      <Tabs.TabPane
        key="1"
        tab={
          <div>
            通知
            {noticeCount ? <span> ({noticeCount}) </span> : null}
          </div>
        }
      >
        <List
          bordered
          dataSource={state.notices}
          renderItem={item => (
            <List.Item>
              <List.Item.Meta
                description={item.createTime}
                title={
                  <Typography.Paragraph
                    onClick={() => handleTitleClick(item)}
                    ellipsis={{ rows: 1, tooltip: true }}
                    delete={!!item.isRead}
                    style={{
                      cursor: !item.isRead ? 'pointer' : '',
                      width: '100%',
                      marginBottom: 0
                    }}
                  >
                    {item.content}
                  </Typography.Paragraph>
                }
              />
            </List.Item>
          )}
        />
      </Tabs.TabPane>
      <Tabs.TabPane tab="消息" key="2" />
      <Tabs.TabPane tab="代办" key="3" />
    </Tabs>
  )
}

const NotifyDropdown = () => {
  const [count, setCount] = useState(0)
  useEffect(() => {
    async function getCount() {
      const { code = -1, data = 0 } = await queryUnreadNotice()
      if (code === consts.RET_CODE.SUCCESS) {
        setCount(data)
      }
    }
    getCount()
  }, [])
  return (
    <Popover
      arrow
      trigger="click"
      overlayClassName="!min-w-360px"
      content={<DropdownContent noticeCount={count} />}
    >
      <span className={`${styles.action} ${styles.notice}`}>
        <Badge dot count={count}>
          <BellOutlined />
        </Badge>
      </span>
    </Popover>
  )
}

export default NotifyDropdown
