import React, { useEffect, useState, useRef } from 'react'
import { Box } from './styled'
import { Pagination } from 'antd'
import Layout from '~/components/layout'
import ContentBox from '~/components/contentBox'
import { useRouter } from 'next/router'
import Filter, { FilterResult, AdapterResult } from '~/components/filter'
import api, { Job } from './api'
import Image from 'next/image'
// 此函数在构建时被调用
export async function getServerSideProps() {
  return {
    props: {},
  }
}

interface ImageListType {}

export default function JobServices() {
  const router = useRouter()
  const [list, setList] = useState([
    'https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/file/540X844-2(1).jpg',
    // "https://pad-video-x.oss-cn-shenzhen.aliyuncs.com/file/665512fd-12e6-49a9-93c1-f9dcd0e82083.jpg",
  ])
  const [productList, setProductList] = useState(
    Array<{ element: JSX.Element }>
  )
  const [rightDomList, setRightDomList] = useState(
    Array<{ element: JSX.Element }>
  )
  const leftDom = (item: Job) => {
    return (
      <div
        key={item.id}
        className="item"
        onClick={() => router.push(`/jobServices/detail/${item.id}`)}
      >
        <div className="item-top">
          <div className="value">
            <div className="value-left">
              <div className="label">{item.serviceName}</div>
              {/* <div className="com">{item.teamName}</div> */}
            </div>
            <div className="value-right">
              {/* <span className="money">¥{item.price}</span> */}
              {/* <span className="unit">/平</span> */}
              <span className="money">获取报价</span>
            </div>
          </div>
        </div>
        <div className="item-bottom">
          <div className="bottom-left">
            {Math.round(Math.random() * (150 - 100) + 100)}条评价
          </div>
          {/* <div className="bottom-right">专业飞手团队，精通巡航业务</div> */}
          <div className="com">{item.teamName}</div>
        </div>
      </div>
    )
  }

  const rightDom = (item: string) => {
    return (
      <div className="right-box-item advertisement" key={item}>
        <Image src={item} alt="error" width={260} height={420} />
      </div>
    )
  }

  const [filterResult, setFilterResult] = useState<AdapterResult>({}) //筛选结果

  const [pageParams, setPageParams] = useState({
    pageNo: 1,
    pageSize: 14,
  }) //分页器对象

  const [count, setCount] = useState(0) //商品总数
  const [abort, setAbort] = useState<AbortController | null>(null) //请求中断

  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))
    let rs
    if (Object.keys(queryVal).length) {
      rs = { categoryId: [Number(queryVal['categoryId'])] }
    }
    api
      .listPageJobServicesInfo(
        {
          ...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)
    adapterFilterResult.categoryId = adapterFilterResult.categoryId?.map(
      (item) => item.id
    )
    setFilterResult(adapterFilterResult)
  }

  useEffect(() => {
    setRightDomList(
      list.map((item) => {
        return { element: rightDom(item) }
      })
    )
  }, [])

  useEffect(() => {
    let queryVal = JSON.parse(JSON.stringify(router.query))
    if (Object.keys(router.query).length) {
      setFilterResult({ categoryId: [Number(queryVal['categoryId'])] })
    }
  }, [router])

  return (
    <Layout>
      <Box>
        <Filter
          types={['地域', '行业', '应用']}
          showResultItem
          onChange={onFilterChange}
        ></Filter>
        <div style={{ marginTop: 10 }}>
          <ContentBox
            boxIndex={2}
            leftRenderDom={{
              columns: productList,
              pagination: (
                <div className="pagination-page">
                  <Pagination
                    current={pageParams.pageNo}
                    pageSize={pageParams.pageSize}
                    showSizeChanger={false}
                    showQuickJumper
                    total={count}
                    onChange={onPageChange}
                    hideOnSinglePage={true}
                  />
                </div>
              ),
            }}
            rightRenderDom={{ columns: rightDomList }}
            leftcontentstyle={{
              width: '924px',
              margin: { top: 0, right: '10px', bottom: '10px', left: 0 },
            }}
          />
        </div>
      </Box>
    </Layout>
  )
}
