import React, { useState, useEffect, useRef } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import { Icon, Badge } from 'antd'
import { Scrollbars } from 'react-custom-scrollbars'
import IFComponent from '../common/IFComponent'
import Socket from '../utils/socket'
import { isEqual } from 'lodash'

function AlarmNotice (props) {
  const [visible, setVisible] = useState(false)
  const [msg, setMsg] = useState({
    AlarmId: null,
    TotalCount: 0,
    Message: ''
  })
  useEffect(() => {
    let timer = -1
    if (msg && !msg.TotalCount && !msg.Message && visible) {
      timer = setTimeout(() => {
        setVisible(false)
      }, 5000)
    }

    return () => { clearTimeout(timer) }
  }, [msg, visible])

  const refOfMsg = useRef(msg)
  useEffect(() => {
    refOfMsg.current = msg
  })

  const socket = useRef()
  useEffect(() => {
    const { userId: UserId, OrgId } = props.login
    if (UserId && OrgId) {
      const socketIns = new Socket({
        url: props.webSocketHost,
        onopen: handleSocketOpened,
        onmessage: handleSocketOnMsg
      })
      socket.current = socketIns
    }

    return () => {
      socket.current && socket.current.close()
    }
  }, [props.login.userId, props.login.OrgId, props.login.Tenant])

  const handleSocketOpened = (socketIns) => {
    const { user, userId: UserId, OrgId, Tenant } = props.login
    const openedPayload = {
      TypeCode: 'P0001',
      Tenant,
      Data: JSON.stringify({
        UserId,
        UserName: user.NAME,
        OrgId,
        ClientType: 0
      })
    }
    socketIns.send(JSON.stringify(openedPayload))
    handleSocketSendMsg({}, socketIns)
  }

  const handleSocketOnMsg = (data) => {
    if (data) {
      const { TypeCode, Data } = JSON.parse(data)
      if (TypeCode === 'M0003' && Data) {
        Data.Message && !isEqual(Data.Message, refOfMsg.current.Message) && !visible && setVisible(true)
        setMsg(Data)
      }
    }
  }

  const handleSocketSendMsg = (Data, socketIns) => {
    const { userId: UserId, OrgId, Tenant } = props.login
    // 这里 Data 需要 JSON.stringify(Data) 是因为后端限制
    const payload = { TypeCode: 'M0003', Tenant, Data: JSON.stringify({ UserId, OrgId, ...Data }) }
    socketIns = socketIns || socket.current
    socketIns && socketIns.send(JSON.stringify(payload))
  }

  const handleNext = () => {
    if (!msg.TotalCount) return
    handleSocketSendMsg({ AlarmId: msg.AlarmId })
  }

  const handleItemClick = (id) => {
    props.onItemClick instanceof Function && props.onItemClick(id)
  }

  return (
    <div className={`alarm-notice ${visible ? 'visible' : ''}`}>
      <div onClick={() => { setVisible(!visible) }} className='alarm-notice__toogle'>
        <Icon type='caret-up' />
        <div className='alarm-notice__toogle-badge'>
          <Badge count={msg.TotalCount} />
        </div>
      </div>
      <div className='alarm-notice__content'>
        <Scrollbars autoHide autoHideTimeout={1000} autoHideDuration={200}>
          <IFComponent IF={!!msg.Message} ELSE={<span>暂无报警信息</span>}>
            <p onClick={() => handleItemClick(msg.AlarmId)}>{msg.Message}</p>
          </IFComponent>
        </Scrollbars>
        <div
          title='下一条'
          onClick={handleNext}
          className={`alarm-notice__content-next ${!msg.TotalCount ? 'disabled' : ''}`}
        >
          <Icon type='arrow-right' />
        </div>
      </div>
    </div>
  )
}

AlarmNotice.propTypes = {
  webSocketHost: PropTypes.string.isRequired,
  onItemClick: PropTypes.func
}

export default connect(({ login }) => ({ login }))(AlarmNotice)
