import { Badge, Button, Drawer, Row, Col } from 'antd'
import { BellOutlined, MenuUnfoldOutlined } from '@ant-design/icons'
import { getMessageList, getMessageCount, setMessageRead, setMessageAllRead } from '@/api/message'
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'

function Message() {
  const [open, setOpen] = useState(false)
  const [dot, setDot] = useState(false)

  const getMessageNum = async () => {
    const {
      data: { num = 0 }
    } = await getMessageCount()
    setDot(num !== 0)
  }
  useEffect(() => {
    getMessageNum()
  }, [])

  const handleRead = () => {
    getMessageNum()
    setOpen(false)
  }
  return (
    <>
      <Button onClick={() => setOpen(true)} style={{ border: 'none', background: '#f6f6f6' }}>
        <Badge dot={dot}>
          <BellOutlined />
        </Badge>
      </Button>
      <MessageDraw open={open} onClose={() => setOpen(false)} onRead={handleRead} />
    </>
  )
}

function MessageDraw({ onRead, ...rest }) {
  const handleReadAll = async () => {
    await setMessageAllRead()
    onRead()
  }
  return (
    <Drawer
      {...rest}
      destroyOnClose
      closeIcon={<MenuUnfoldOutlined />}
      extra={
        <span style={{ fontSize: '14px', color: '#999', cursor: 'pointer' }} onClick={handleReadAll}>
          全部已读
        </span>
      }>
      <MessageList onRead={onRead} />
    </Drawer>
  )
}

function MessageList({ onRead }) {
  const navigator = useNavigate()
  const [messageList, setMessageList] = useState([])

  const getMessage = async () => {
    const {
      data: { list = [] }
    } = await getMessageList({ page: 1, page_size: 10 })
    setMessageList(list)
  }
  const handleRead = async item => {
    await setMessageRead({ id: item.id })
    if (item.type === 1) {
      navigator('/books/audit/dataset')
    } else if (item.type === 2) {
      navigator('/books/sale/dataset')
    }
    onRead(item)
  }

  useEffect(() => {
    getMessage()
  }, [])
  return (
    <>
      {messageList.map(item => {
        return <MessageListItem item={item} key={item.id} onRead={() => handleRead(item)} />
      })}
    </>
  )
}

function MessageListItem({ item, onRead }) {
  return (
    <Row key={item.id} style={{ borderRadius: 4, border: '1px solid #e4e4e4', padding: 15, marginBottom: 20, cursor: 'pointer' }} onClick={onRead}>
      <Col span={1} style={{ marginRight: 15 }}>
        <Badge dot={item.status == 0}>
          <BellOutlined />
        </Badge>
      </Col>
      <Col span={22} className="process">
        <div className="head" style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 10 }}>
          <strong>审核通知</strong>
          <span className="date" style={{ color: '#999999', fontSize: 12 }}>
            {item.create_time}
          </span>
        </div>
        <div className="content">{item.content}</div>
      </Col>
    </Row>
  )
}

export default Message
