import { useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { ScrollView, Image } from '@tarojs/components'
import withLayout from '@/layout'
import { queryChatFriends } from '@/services/chat'
import { formatDate } from '@/utils/chatDate'
import './index.scss'

const defaultRuleImage = 'https://yz-websit.oss-cn-hangzhou.aliyuncs.com/xlk/index-icon18.jpg'

export default withLayout((props) => {

  // const [PageProps] = useState(props)
  const [IsPull, setPull] = useState(false)
  const [PullTimer, setPullTimer] = useState(null)
  const [PageList, setPageList] = useState([])

  const getList = (params) => {
    Taro.showLoading()
    queryChatFriends({
      pageSize: 20,
      ...params || {},
    }).then((res) => {
      Taro.hideLoading()
      const { records } = res
      setPageList(records || [])
    }).catch((err) => {
      console.error(err)
      Taro.hideLoading()
    })
  }

  const handleChat = (item) => {
    Taro.navigateTo({
      url: `/pages/chat/chatDetail/index?friend=${item.friendId}`
    })
  }

  useEffect(() => {
    getList({ pageNumber: 1 })
  }, [])

  const PageRefresh = () => { // 页面下拉刷新回调
    setPull(true)
  }

  useEffect(() => { // 下拉刷新触发
    if (IsPull) {
      clearTimeout(PullTimer)
      setPullTimer(setTimeout(() => {
        setPull(false)
      }, 2000))
    }
  }, [IsPull])

  return (
    <view className='Page Chat'>

      <ScrollView scrollY refresherEnabled refresherTriggered={IsPull} onRefresherrefresh={PageRefresh} refresherBackground='#fff'>
        <view className='PageContent'>
          {
            PageList.map((item) => (
              <view className='ListItem flex-h' key={item.friendId} onClick={() => handleChat(item)}>
                <view className='Icon'>
                  <view>
                    <Image mode='aspectFill' className='centerLabel' src={item.avatar || defaultRuleImage} />
                  </view>
                  {!!item.unReadNum && <text className='Num'>{item.unReadNum}</text>}
                </view>
                <view className='flex-item'>
                  <view className='flex-h'>
                    <text className='flex-item'>{item.name}</text>
                    <text>{formatDate(item.createDate, 'yyyy/M/d')}</text>
                  </view>
                  <view className='Msg'>
                    <text>{item.messageType === 'text' ? item.message : '[图片]'}</text>
                  </view>
                </view>
              </view>
            ))
          }
          {
            PageList.length === 0 &&
            <view className='NoData centerLabel'>
              <text className='iconfont icon-nodata'></text>
              <text>没有更多聊天信息了~</text>
            </view>
          }
        </view>
      </ScrollView>

    </view>
  )
})
