import { useEffect, useState } from 'react'
import classNames from 'classnames'
import Taro from '@tarojs/taro'
import { MovableArea, MovableView } from '@tarojs/components'
import { showSubscribeMessage, MESSAGE_TYPE } from '@/utils/subscribeMessage'
import { API_CHAT_UNREADED } from '@/constants/api'
import { fetch } from '@/utils/request'
import useInterval from '@/utils/hooks/useInterval'
import './style.scss'

export default function ChatIcon(props) {

  const [unReadNum, setUnReadNum] = useState(0)
  const [PageX] = useState(Taro.getSystemInfoSync().windowWidth - 60)
  const [PageY] = useState(Taro.getSystemInfoSync().windowHeight - 160)

  const handleClick = () => {
    showSubscribeMessage(MESSAGE_TYPE.NOTICE).then(() => {
      Taro.switchTab({ url: '/pages/chat/index' })
    })
  }

  useInterval(() =>{
    fetch({url: API_CHAT_UNREADED, showToast: false}).then(x => setUnReadNum(x || 0))
  }, 30000, true)

  return (
    <MovableArea className='components ChatIcon' onClick={handleClick}>
      <MovableView className='MoveItem' x={PageX} y={PageY} direction='all'>
        <text className={classNames('iconfont icon-xiaoxi centerLabel', { active: unReadNum > 0 })}></text>
      </MovableView>
    </MovableArea>
  )
}
