import { Pagination } from 'antd'
import Image from 'next/image'
import { useRouter } from 'next/router'
import { useEffect, useRef, useState } from 'react'
import ContentBox from '~/components/contentBox'
import Filter, { AdapterResult, FilterResult } from '~/components/filter'
import Layout from '~/components/layout'
import api, { Advertisement, Device } from './api'
import { Box } from './styled'
// 此函数在构建时被调用
export async function getStaticProps() {
  //获取筛选数据，进行静态渲染
  return {
    props: {}
  }
}

type Props = {}

export default function EquipmentLeasing(props: Props) {
  const router = useRouter()
  const filter = useRef<any>()
  const [productList, setProductList] = useState(Array<{ element: JSX.Element }>)
  const [rightProductList, setRightProductList] = useState(Array<{ element: JSX.Element }>)

  const leftDom = (item: Device) => {
    return (
      <div key={item.id} className="item" onClick={() => router.push(`/equipmentLeasing/detail/${item.id}`)}>
        <div className="item-top">
          <div className="item-top-image">
            <Image src={item.wareImgs[0].imgUrl} alt="error" fill />
          </div>
        </div>
        <div className="item-bottom">
          <div className="item-bottom-title" title={item.wareTitle}>
            {item.wareTitle}
          </div>
          <div className="item-bottom-price">
            <span className="money">¥{item.minRent}</span>
            <span className="unit">/天起</span>
          </div>
        </div>
      </div>
    )
  }

  const rightDom = (item: Advertisement) => {
    return (
      <div key={item.id} className="right-box-item right-item">
        <Image src={item.imageUrl} alt="error" fill />
      </div>
    )
  }

  const [filterResult, setFilterResult] = useState<AdapterResult>({}) //筛选结果
  const [count, setCount] = useState(0) //商品总数
  const [abort, setAbort] = useState<AbortController | null>(null) //请求中断
  const [pageParams, setPageParams] = useState({
    pageNo: 1,
    pageSize: 15
  }) //分页器对象

  const onPageChange = (page: number, pageSize: number) => {
    setPageParams({
      ...pageParams,
      pageNo: page
    })
  }

  useEffect(() => {
    //中断前一次列表请求
    abort?.abort()
    setAbort(new AbortController())
  }, [filterResult, pageParams])

  //端口列表请求
  useEffect(() => {
    let queryVal = JSON.parse(JSON.stringify(router.query))
    const idArr = filter.current.idArr
    let rs
    for (const key in queryVal) {
      if (idArr.includes(key)) {
        rs = { [key]: router.query[key] }
      }
    }
    api
      .listPageDeviceInfo(
        {
          ...filterResult,
          ...pageParams,
          ...rs
        },
        {
          signal: abort?.signal
        }
      )
      .then(res => {
        setProductList(
          res.result?.list?.map(item => {
            return { element: leftDom(item) }
          }) || []
        )
        setCount(res.result?.totalCount || 0)
      })
  }, [abort])

  const onFilterChange = (filterResult: FilterResult, adapterFilterResult: AdapterResult) => {
    console.log('filterResult', filterResult, adapterFilterResult)
    setFilterResult(adapterFilterResult)
  }

  useEffect(() => {
    api.listAdvertisementInfo().then(res => {
      setRightProductList(
        res.result?.map(item => {
          return { element: rightDom(item) }
        }) || []
      )
    })
  }, [])

  useEffect(() => {
    let queryVal = JSON.parse(JSON.stringify(router.query))
    if (router.query) {
      const idArr = filter.current.idArr
      for (const key in queryVal) {
        if (idArr.includes(key)) {
          setFilterResult({ [key]: router.query[key] })
        }
      }
    }
  }, [router])

  return (
    <Layout>
      <Box>
        <Filter types={['地域', '设备品牌', '设备型号']} showResultItem onChange={onFilterChange} ref={filter}></Filter>
        <div style={{ paddingTop: 13 }}>
          <ContentBox
            boxIndex={5}
            leftcontentstyle={{
              width: '1010px',
              margin: { top: 0, right: '12px', bottom: '12px', left: 0 }
            }}
            leftRenderDom={{
              columns: productList,
              pagination: (
                <div className="pagination-page">
                  <Pagination current={pageParams.pageNo} pageSize={pageParams.pageSize} showSizeChanger={false} showQuickJumper total={count} onChange={onPageChange} hideOnSinglePage={true} style={{ marginTop: 20 }} />
                </div>
              )
            }}
            rightRenderDom={{ columns: rightProductList }}
          />
        </div>
      </Box>
    </Layout>
  )
}
