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_ITEMS_LIST, API_CITY_AREA, API_ITEMS_TYPE } from '@/constants/api'
import ProjectListItem from '@/components/ProjectListItem/index'
import Taro from '@tarojs/taro'
import './index.scss'
import FilterForCityArea from './components/FilterForCityArea/index'
import FilterForPrice from './components/FilterForPrice/index'
import FilterForHouseType from './components/FilterForHouseType/index'
import FilterForMore from './components/FilterForMore/index'
import FilterForHouseSort from './components/FilterForHouseSort/index'

export default withLayout((props) => {
  const { router } = props
  const { isRecentOpening, isCommerce } = router.params

  const city = useSelector(state => state.city)
  const [PageList, setPageList] = useState([])
  const [pageNumber, setPageNumber] = useState(1)
  const [pageSize] = useState(10)
  const [IsPull, setPull] = useState(false)
  const [HasNextPage, setHasNextPage] = useState(true)
  const [CityAreaList, setCityAreaList] = useState([])
  const [BuildingTypeList, setBuildingTypeList] = useState([])
  const [FilterMenus] = useState([
    { name: '区域', id: 1 },
    { name: '价格', id: 2 },
    { name: '户型', id: 3 },
    { name: '更多', id: 4 }
  ])
  const [CurrentFilter, setCurrentFilter] = useState(null)
  const [FilterData, setFilterData] = useState({
    buildingArea: [],
    area: [],
    price: '-',
    priceType: null,
    houseType: [],
    buildingType: [],
    orderBy: '-',
    marketStatus: [],
    name: '-'
  })

  useEffect(() => {
    if (city.curCity.name) {
      CityArea()
      GetBuildingTypeList()
    }
  }, [pageNumber, city])

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

  useEffect(() => {
    if (CityAreaList.length) {
      GetProjectList()
    }
  }, [CityAreaList])

  const CityArea = () => {
    fetch({ url: API_CITY_AREA, method: 'get', payload: { cityId: city.curCity.id, leveltype: 3 } }).then((res) => {
      setCityAreaList([{ id: '-', name: '不限' }].concat(res || []))
    })
  }

  const GetBuildingTypeList = () => {
    fetch({ url: API_ITEMS_TYPE, method: 'get' }).then((res) => {
      const ResData = res.records || []
      let Arr = ResData.map((item) => {
        return { name: item.buildingTypeName, id: item.buildingTypeId }
      })
      setBuildingTypeList([{ id: '-', name: '不限' }].concat(Arr))
    })
  }

  const GetProjectList = () => { // 获取项目列表
    Taro.showLoading({title: '加载中'})
    setHasNextPage(false)
    let Data = {}
    for (let key in FilterData) {
      if (FilterData[key] !== '-' && FilterData[key] !== null && key !== 'buildingArea' && key !== 'area' && key !== 'buildingType' && key !== 'marketStatus' && key !== 'houseType') {
        Data[key] = FilterData[key]
      }
    }
    if(FilterData.buildingArea.length) {
      Data.buildingArea = FilterData.buildingArea.join(',')
    }
    if(FilterData.area.length) {
      Data.area = FilterData.area.join(',')
    }
    if(FilterData.buildingType.length) {
      Data.buildingType = FilterData.buildingType.join(',')
    }
    if(FilterData.marketStatus.length) {
      Data.marketStatus = FilterData.marketStatus.join(',')
    }
    if(FilterData.houseType.length) {
      Data.houseType = FilterData.houseType.join(',')
    }
    fetch({ url: API_ITEMS_LIST, method: 'get', payload: { cityId: city.curCity.id, pageNumber, pageSize, isRecentOpening, isCommerce, ...Data } }).then((res) => {
      setPageList(pageNumber === 1 ? res.records || [] : PageList.concat(res.records || []))
      Taro.hideLoading()
      setHasNextPage(res.current < res.pages)
      setPull(false)
      setCurrentFilter(null)
    }).catch(() => {
    })
  }

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

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

  const CutFilter = (id) => {
    return () => {
      setCurrentFilter(id === CurrentFilter ? null : id)
    }
  }

  const FilterChange = (e) => {
    let Data = { ...FilterData }
    Data[e.name] = e.value
    setFilterData({...Data})
  }

  const FiltersChange = (e) => {
    setFilterData({...FilterData, ...e})
  }

  const PriceChange = (e) => {
    let Data = { ...FilterData }
    for (let key in e) {
      Data[key] = e[key]
    }
    setFilterData({...Data})
  }

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

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

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

      <view className='Search'>
        <view>
          <text className='iconfont icon-sousuo'></text>
          <Input confirm-type='search' placeholder='输入项目名称' onConfirm={SearchConfirm}></Input>
        </view>
      </view>

      <view className='Filter'>
        <view className='flex-h'>
          {
            FilterMenus.map((item, index) => (
              <view className='flex-item' key={`FilterMenusItem-${index}`} onClick={CutFilter(item.id)}>
                <text>{item.name}</text>
                <text className={CurrentFilter === item.id ? 'iconfont icon-sanjiaoxingup' : 'iconfont icon-sanjiaoxingdown'}></text>
              </view>
            ))
          }
          <text className='iconfont icon-paixu Sort' onClick={() => { setCurrentFilter(CurrentFilter === 5 ? null : 5) }}></text>
        </view>
      </view>

      <view className='flex-item'>
        <view className='FilterContainer' style={{ display: !!CurrentFilter ? 'block' : 'none' }}>

          {/* 区域 */}
          {
            CurrentFilter === 1 &&
            <FilterForCityArea change={FilterChange} defaultValue={FilterData.buildingArea} List={CityAreaList} Cancel={() => { setCurrentFilter(null) }}></FilterForCityArea>
          }

          {/* 价格 */}
          {
            CurrentFilter === 2 &&
            <FilterForPrice change={PriceChange} priceType={FilterData.priceType} price={FilterData.price}></FilterForPrice>
          }

          {/* 户型 */}
          {
            CurrentFilter === 3 &&
            <FilterForHouseType change={FiltersChange} defaultValue={FilterData.houseType} Cancel={() => { setCurrentFilter(null) }}></FilterForHouseType>
          }

          {/* 更多 */}
          {
            CurrentFilter === 4 &&
            <FilterForMore Cancel={() => { setCurrentFilter(null) }} change={FiltersChange} AreaDefault={FilterData.area} StatusDefault={FilterData.marketStatus} BuildingTypeDefault={FilterData.buildingType} BuildingTypeList={BuildingTypeList}></FilterForMore>
          }

          {/* 排序 */}
          {
            CurrentFilter === 5 &&
            <FilterForHouseSort Cancel={() => { setCurrentFilter(null) }} change={FilterChange} defaultValue={FilterData.orderBy}></FilterForHouseSort>
          }

        </view>
        <view className='ScrollContainer'>
          <ScrollView scroll-y refresher-enabled refresher-triggered={IsPull} onrefresherrefresh={PageRefresh} onscrolltolower={PageLoadMore} refresher-background='#fff'>
            <view className='PageContent'>
              <view className='ProjectList'>
                {
                  PageList.map((item, index) => (
                    <ProjectListItem Data={item} key={`ProjectListItem-${index}`}></ProjectListItem>
                  ))
                }
              </view>

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

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

    </view>
  )
})
