import { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import withLayout from '@/layout'
import { ScrollView, Image } from '@tarojs/components'
import Disclaimer from '@/components/Disclaimer'
import { getImgURL } from '@/utils/image'
import { formateLeftTime } from '@/utils/tools'
import { fetch } from '@/utils/request'
import { API_SPECIAL_ROOM_LIST } from '@/constants/api'
import '@/assets/css/iconfont.css'
import './index.scss'

const defaultRuleImage = 'https://yz-websit.oss-cn-hangzhou.aliyuncs.com/xlk/index-icon19.jpg'

export default withLayout((props) => {
  const { city } = props

  const [PageList, setPageList] = useState([])
  const [IsPull, setPull] = useState(false)
  const [pageNumber, setPageNumber] = useState(1)
  const [HasNextPage, setHasNextPage] = useState(true)

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

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

  const GetPageList = () => {
    setHasNextPage(false)
    fetch({ url: API_SPECIAL_ROOM_LIST, method: 'get', payload: { pageNumber, pageSize: 10, cityId: city?.id } }).then((res) => {
      console.log(pageNumber === 1 ? res.records || [] : PageList.concat(res.records || []))
      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 goto = (it) => {
    Taro.navigateTo({
      url: `/pages/index/buildingDetail/index?id=${it.buildingId}`
    })
  }

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

          {/* 主图 */}
          <view className='MainPicture'>
            <Image mode='widthFix' src={defaultRuleImage}></Image>
          </view>

          {/* 列表 */}
          <view className='List'>
            {
              PageList.map((item, index) => {
                const mainImg = getImgURL((item?.buildingListImg || []).length ? item.buildingListImg[0].url : null)
                const price = item.price || '价格待定'
                const shareNum = item.shareList?.total || 0
                const uvNum = (item?.uvList || []).length || 0

                // 最多6个
                const tags = (item.buildingTag || []).map(x => x.tagName).slice(0, 6)

                //
                const specialRoomList = item.specialRoomList || []

                return (
                  <view key={item.buildingId}>
                    <view className='Title'>
                      <view>
                        <text className='iconfont icon-shoucang'></text>
                        <text>{index + 1 > 9 ? index + 1 : `0${index + 1}`}</text>
                        <text className='iconfont icon-shoucang'></text>
                      </view>
                    </view>

                    <view className='InfoContent'>
                      <view className='Img' onClick={() => goto(item)}>
                        <Image mode='scaleToFill' src={mainImg} className='centerLabel'></Image>
                        {
                          (item?.panoramaList || []).length > 0 &&
                          <Image mode='heightFix' className='Tips Vr' src={require('@/assets/index-icon18.png')} />
                        }
                        {
                          item.videoUrl !== null &&
                          <Image mode='heightFix' className='Tips Video' src={require('@/assets/index-icon19.png')} />
                        }
                      </view>
                      <view className='Name flex-h' onClick={() => goto(item)}>
                        <view className='flex-item'>
                          <text>{item.buildingName}</text>
                        </view>
                        <text></text>
                        <text>{price}</text>
                      </view>
                      <text className='Address' onClick={() => goto(item)}>{item.address}</text>
                      <view className='Tag' onClick={() => goto(item)}>
                        {
                          tags.map((x) => (<text key={x}>{x}</text>))
                        }
                      </view>
                      <view className='Views flex-h' onClick={() => goto(item)}>
                        <view className='flex-item'>
                          <text className='iconfont icon-fenxiang'></text>
                          <text>{`${199 + (shareNum || 0)} 次分享`}</text>
                        </view>
                        {
                          uvNum > 0 && (
                            <view className='Icons'>
                              {
                                item.uvList.map((x) => (
                                  <view key={x.uvId}>
                                    <Image mode='scaleToFill' src={getImgURL(x.photoOravatar)} className='centerLabel'></Image>
                                  </view>
                                ))
                              }
                            </view>
                          )
                        }
                        <text>{`...${199 + (uvNum || 0)}人围观`}</text>
                      </view>
                      <view className='SpecialList'>
                        <ScrollView scrollX>
                          {
                            specialRoomList.map((it) => {
                              const unitPrice = it.area ? it.currentPrice / it.area : undefined
                              const unitW = unitPrice ? `${Number(unitPrice).toFixed(0)}元/㎡` : '单价待定'
                              const currentW = it.currentPrice ? `${Number(it.currentPrice / 10000).toFixed(1)}` : '待定'
                              const originalW = it.originalPrice ? `${Number(it.originalPrice / 10000).toFixed(1)}` : '待定'
                              const thriftW = it.thriftPrice ? `省${Number(it.thriftPrice / 10000).toFixed(1)}` : '待定'
                              const leftTime = formateLeftTime(new Date(it.endTime) - new Date(), 'min');

                              return (
                                <view className='ListItem' key={it.specialRoomId}>
                                  <text className='Tips'>{thriftW}</text>
                                  <view className='Price'>
                                    <text>{currentW}</text>
                                    <text>万</text>
                                    <text>{originalW}万</text>
                                  </view>
                                  <text className='Time'>{`距结束 ${leftTime}`}</text>
                                  <text className='HouseType'>{`${it.unitType} ${unitW}`}</text>
                                  <text className='DoorNumber'>{it.roomName}</text>
                                </view>
                              )
                            })
                          }
                        </ScrollView>
                      </view>
                    </view>

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

          {/* <view className='Bottom'>
            <view>
              <view>
                <text className='iconfont icon-shengming'></text>
                <text>免责声明</text>
              </view>
              <view>
                <text>&emsp;&emsp;以上价格仅供参考,具体一房一价的信息以售楼处展示为准。房屋位置交通、医疗、教育、商业等配套信息，来源于第三方不作为要约,仅供参考,双方具体权利义务应以法律规定及买卖合同约定为准。本平台对项目周边文化教育的介绍旨在提供相关信息1 意味着信息发布方对就学安排作出承诺。相关教育资首页信息存在调整的可能,应以政府教育主管部门门及办学颁布的政策规定为准。详情请仔细阅读</text>
                <text className='active'>《新联家使用免责条款》</text>
              </view>
            </view>
          </view> */}

          <Disclaimer />

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