import { useState, useEffect, useCallback, useRef } from 'react'
import withLayout from '@/layout'
import { ScrollView, Input } from '@tarojs/components'
import '@/assets/css/iconfont.css'
import { useSelector } from 'react-redux'
import { fetch } from '@/utils/request'
import { API_MANAGE_CUSTOMER_LIST, API_MY_BUILDINGIDS } from '@/constants/api'
import './index.scss'
import ResidentListItem from '../components/ResidentListItem/index'

export default withLayout((props) => {
  const { person } = props
  
  const [BuildingIds, setBuildingIds] = useState([])
  const [PageList, setPageList] = useState([])
  const [IsPull, setPull] = useState(false)
  const [HasNextPage, setHasNextPage] = useState(true)
  const [CurrentBuildingId, setCurrentBuildingId] = useState(null)
  const [CurrentBuildingName, setCurrentBuildingName] = useState(null)
  const [page, setPage] = useState({ pageNumber: 1 })
  const queryParamsRef = useRef({})
  const getListRef = useRef()

  const GetMyBuildingIds = () => {
    fetch({ url: API_MY_BUILDINGIDS, method: 'get' }).then((res) => {
      setBuildingIds(res || [])
    })
  }

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

  getListRef.current = (params) => {
    if (!CurrentBuildingId) return;

    setHasNextPage(false)
    fetch({
      url: API_MANAGE_CUSTOMER_LIST,
      payload: {
        pageSize: 10,
        ...params,
        ...queryParamsRef.current,
        buildingId: CurrentBuildingId
      },
    }).then((res) => {
      setPageList(res.current === 1 ? res.records || [] : PageList.concat(res.records || []))
      setHasNextPage(res.current < res.pages)
      setPull(false)
    })
  }

  const PickerChange = (e) => {
    setCurrentBuildingId(BuildingIds[e.detail.value - 0].buildingId)
    setCurrentBuildingName(BuildingIds[e.detail.value - 0].name)
  }

  const SearchConfirm = (e) => {
    queryParamsRef.current = {
      ...queryParamsRef.current,
      keywords: e.detail.value,
    }
    setPage({ pageNumber: 1 })
  }

  const ListChange = (index) => {
    return () => {
      let List = [...PageList]
      List.splice(index, 1)
      setPageList(List)
    }
  }

  // 页面上拉加载更多
  const PageLoadMore = () => {
    if (HasNextPage) {
      setPage({ pageNumber: page.pageNumber + 1 })
    }
  }
  
  useEffect(() => {
    GetMyBuildingIds()
  }, [])

  useEffect(() => {
    if (BuildingIds.length) {
      setCurrentBuildingId(BuildingIds[0].buildingId)
      setCurrentBuildingName(BuildingIds[0].name)
    }
  }, [BuildingIds])

  // 选择楼盘
  useEffect(() => {
    if (CurrentBuildingId) {
      setPage({ pageNumber: 1 })
    }
  }, [CurrentBuildingId])

  // 下拉刷新
  useEffect(() => {
    if (IsPull) {
      setPage({ pageNumber: 1 })
    }
  }, [IsPull])

  useEffect(() => {
    getListRef.current(page)
  }, [page])

  return (
    <view className='Page residentManager flex-v'>

      <view className='Search flex-h'>
        <view className='flex-item'>
          <text className='iconfont icon-sousuo'></text>
          <Input confirm-type='search' placeholder='请输入关键字搜索' onConfirm={SearchConfirm} onscrolltolower={PageLoadMore}></Input>
        </view>
        <text>{CurrentBuildingName}</text>
        <picker value={0} range-key='name' onChange={PickerChange} range={BuildingIds}>
          <view class='picker'>更换</view>
        </picker>
      </view>

      <view className='flex-item'>
        <view>
          <ScrollView scroll-y refresher-enabled refresher-triggered={IsPull} onrefresherrefresh={PageRefresh} refresher-background='#fff'>
            <view className='PageContent'>

              {/* <view className='Filter'>
                <text>筛选条件</text>
                <view>
                  {
                    FilterMenu.map((item, index) => (
                      <view key={`FilterItem-${index}`} onClick={CutFilter(item)}>
                        <text>{item.name}</text>
                        {
                          CurrentFilterMenuId === item.id &&
                          <Image mode='widthFix' src={require('@/assets/findHouse-icon1.png')}></Image>
                        }
                      </view>
                    ))
                  }
                </view>
              </view> */}

              <view className='List'>
                {
                  PageList.map((item, index) => (
                    <ResidentListItem data={item} key={`ResidentListItem-${index}`} change={ListChange(index)}></ResidentListItem>
                  ))
                }
              </view>

              {/* bottom */}
              <view className='PageBottom'>
                <text>已经到底了~</text>
              </view>

            </view>
          </ScrollView>
        </view>
      </view>

    </view>
  )
})
