import { useState, useEffect } from 'react'
import { ScrollView } from '@tarojs/components'
import { fetch } from '@/utils/request'
import { API_FOLLOW_LIST } from '@/constants/api'
import { formatDate } from "@/utils/chatDate";
import './index.scss'

export default function UserDetailFollowRecord (props) {
  const { CustomerId = null, AddFollow = () => {}, AddFollowCounts = 0 } = props
  const [PageList, setPageList] = useState([])
  const [IsPull, setPull] = useState(false)
  const [pageNumber, setPageNumber] = useState(1)
  const [HasNextPage, setHasNextPage] = useState(true)

  useEffect(() => {
    GetPageList()
  }, [pageNumber])

  useEffect(() => {
    if(AddFollowCounts) {
      if(pageNumber === 1) {
        GetPageList()
      } else {
        setPageNumber(1)
      }
    }
  }, [AddFollowCounts])

  const GetPageList = () => {
    setHasNextPage(false)
    fetch({ url: API_FOLLOW_LIST, method: 'get', payload: { pageNumber, pageSize: 10, customerId: CustomerId, recordType: '跟进' } }).then((res) => {
      setPageList(pageNumber === 1 ? res.records || [] : PageList.concat(res.records || []))
      setHasNextPage(res.current < res.pages)
      setPull(false)
    })
  }

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

  const PageLoadMore = () => { // 页面上拉加载更多
    if(HasNextPage) {
      setPageNumber(pageNumber + 1)
    }
  }

  useEffect(() => { // 下拉刷新触发
    if (IsPull) {
      if (pageNumber === 1) {
        GetPageList()
      } else {
        setPageNumber(1)
      }
    }
  }, [IsPull])

  return (
    <view className='components UserDetailFollowRecord'>
      <ScrollView scroll-y refresher-enabled refresher-triggered={IsPull} onrefresherrefresh={PageRefresh} onscrolltolower={PageLoadMore} refresher-background='#fff'>
        <view className='PageContent'>

          <view className='Content'>
            {
              PageList.map((item, index) => (
                <view className='flex-h' key={`Item-${index}`}>
                  <view className='flex-item'>
                    <text>{formatDate(item.createDate, 'yyyy年MM月dd日 hh:mm:ss')}</text>
                  </view>
                  <view className='Line'>
                    <view></view>
                  </view>
                  <view className='flex-item'>
                    <text className='active' style={{textAlign: 'left'}}>{item.recordType}</text>
                    <text style={{textAlign: 'left'}}>{item.recordContent}</text>
                  </view>
                </view>
              ))
            }
          </view>

          <view className='Btn'>
            <text className='active' onClick={AddFollow}>添加跟进</text>
          </view>

        </view>
      </ScrollView>
    </view>
  )
}
