import { useState, useRef, useEffect } from 'react'
import { View, MovableArea, MovableView, Image, Text, ScrollView } from '@tarojs/components'
import { createSelectorQuery, chooseImage, showToast } from '@tarojs/taro'
import './message.scss'
import { followUser, getMessages } from '@/services/friend'
import { MainColorType } from '@/context/themes/color'
import { jumpPage } from '@/features/trackTimeDuration/hooks/Common'
import dayjs from 'dayjs'
import { rpxToPx } from '@/utils/tools'
import NewButton, { NewButtonType } from '@/_health/base/new_button'
import Taro from '@tarojs/taro'
import NoRecord from '@/_health/components/no_record'


export default function Message() {
  const [list, setList] = useState<any>([])
  const [loaded, setLoaded] = useState(false)
  const [page, setPage] = useState(1)
  const [isPulling, setIsPulling] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [total, setTotal] = useState(-1)
  useEffect(() => {
    Taro.setNavigationBarTitle({
      title: '消息'
    })
    setPage(1)
    getMessageData(1)

    Taro.eventCenter.on('followUser', listenFollowUser)
    Taro.eventCenter.on('unfollowUser', listenUnfollowUser)
  }, [])

  function listenFollowUser(e) {
    getMessageData(1)
  }

  function listenUnfollowUser(e) {
    getMessageData(1)
  }

  function onRefresh() {
    setIsPulling(true)
    getMessageData(1)
  }

  function more() {
    if (isLoading) return
    if (total == list.length) return
    var index = page + 1
    getMessageData(index)
  }

  function onScroll() {

  }

  function getMessageData(index) {
    setPage(index)
    setIsLoading(true)
    getMessages({ page: index, limit: 20 }).then(res => {
      if (index == 1) {
        setList((res as any).data)
        setTotal((res as any).total)
      }
      else {
        setList([...list, ...(res as any).data])
      }
      setLoaded(true)
      setIsPulling(false)
      setIsLoading(false)
    }).catch(e => {
      setIsPulling(false)
      setIsLoading(false)
    })
  }

  function tapFollow(item) {
    var params: any = {
      follow_origin: 'WECHAT_PRIVATE_CHAT',
      user_id: item.user.id,
    }
    followUser(params).then(res => {
      item.relation = 'FRIEND'
      setList(JSON.parse(JSON.stringify(list)))
      Taro.eventCenter.trigger('followUser', item.user.id)

    })
  }

  function messageItem(item, index) {
    return <View key={index} className='message_item' >
      <Image className='message_item_avatar' src={item.user.avatar} />
      <View style={{ display: 'flex', flexDirection: 'column', flex: 1 }}>
        <Text className='h28 g02'>
          <Text onClick={() => {
            jumpPage('./home?uid=' + item.user.id)
          }} className='h28 bold link' style={{ color: MainColorType.link }}>{item.user.nickname} </Text>
          关注了我
        </Text>
        <Text className='h22 g02' style={{ marginTop: rpxToPx(12) }}>{dayjs(item.timestamp).format('MM-DD HH:mm')}</Text>

      </View>
      {
        item.relation == 'FOLLOWER' ? <NewButton
          type={NewButtonType.fill}
          height={rpxToPx(72)}
          color={MainColorType.blue}
          title='Follow back'
          onClick={() => tapFollow(item)}
        /> :
          item.relation == 'FRIEND' ? <Text className="h30 g02">Friend</Text> :
            item.relation == 'FOLLOWING' ? <Text className="h30 g02">Following</Text> : null
      }
    </View>
  }

  if (loaded && list.length == 0)
    return <NoRecord />

  return <ScrollView style='height:100vh'
    enableBackToTop
    scrollY={true}
    refresherEnabled={true}
    upperThreshold={70}
    lowerThreshold={140}
    refresherBackground={MainColorType.g05}
    onRefresherRefresh={onRefresh}
    refresherTriggered={isPulling}
    onScroll={onScroll}
    onScrollToUpper={() => {

    }}
    onScrollToLower={more}
  ><View>
      {
        list.map((item, index) => {
          return messageItem(item, index)
        })
      }
    </View>
  </ScrollView>
}

