import { useState, useEffect } 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(() => {
  // const [FilterMenu] = useState([
  //   { name: '报备', id: 1 },
  //   { name: '到访', id: 2 },
  //   { name: '认筹', id: 3 },
  //   { name: '认购', id: 4 },
  //   { name: '签约', id: 5 },
  //   { name: '报备无效', id: 6 },
  //   { name: '报备过期', id: 7 }
  // ])
  // const [CurrentFilterMenuId, setCurrentFilterMenuId] = useState(null)

  // const CutFilter = (item) => {
  //   return () => {
  //     setCurrentFilterMenuId(item.id === CurrentFilterMenuId ? null : item.id)
  //   }
  // }

  const user = useSelector(state => state.user)
  const [BuildingIds, setBuildingIds] = useState([])
  const [PageList, setPageList] = useState([])
  const [IsPull, setPull] = useState(false)
  const [PersonId, setPersonId] = useState(null)
  const [pageNumber, setPageNumber] = useState(1)
  const [HasNextPage, setHasNextPage] = useState(true)
  const [CurrentBuildingId, setCurrentBuildingId] = useState(null)
  const [CurrentBuildingName, setCurrentBuildingName] = useState(null)
  const [FilterData, setFilterData] = useState({})

  useEffect(() => {
    if (user?.userInfo?.person?.personId) {
      setPersonId(user.userInfo.person.personId)
    }
  }, [user])

  useEffect(() => {
    if (PersonId) {
      GetMyBuildingIds()
    }
  }, [PersonId])

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

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

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

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

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

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

  const GetPageList = () => {
    setHasNextPage(false)
    fetch({ url: API_MANAGE_CUSTOMER_LIST, method: 'get', payload: { pageNumber, pageSize: 10, ...FilterData, buildingId: CurrentBuildingId } }).then((res) => {
      setPageList(pageNumber === 1 ? res.records || [] : PageList.concat(res.records || []))
      setHasNextPage(res.current < res.pages)
      setPull(false)
    })
  }

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

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

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

  const SearchConfirm = (e) => {
    setFilterData({ ...FilterData, keywords: e.detail.value })
  }

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

  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>
  )
})
