import React, { useEffect, useState } from 'react';

import { Pagination, Image } from 'antd';
import { useRouter } from 'next/router';

import commonApi from '~/api';
import ContentBox from '~/components/contentBox';
import Filter, { FilterResult, AdapterResult } from '~/components/filter';
import Layout from '~/components/layout';

import api, { Job } from './api';
import { Box } from './styled';
// 此函数在构建时被调用
export async function getServerSideProps() {
  return {
    props: {},
  };
}

interface ImageListType {}

export default function JobServices() {
  const router = useRouter();
  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>
        </div>
        <div className='item-bottom'>
          <div className='bottom-left'>{item.inspComtAmount}条评价</div>
          <div className='bottom-right'>{item.companyName}</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} width={260} preview={false} />
      </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,
    });
  };
  const getPropagandaCenter = () => {
    commonApi.listBannerImg('JOB_SERVICE').then((res) => {
      setRightDomList(
        (res.result || []).map((item) => {
          return { element: rightDom(item.bannerImg) };
        }),
      );
    });
  };
  useEffect(() => {
    // 中断前一次列表请求
    abort?.abort();
    setAbort(new AbortController());
  }, [filterResult, pageParams]);

  // 端口列表请求
  useEffect(() => {
    const 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]);

  // eslint-disable-next-line
  const onFilterChange = (filterResult: FilterResult, adapterFilterResult: AdapterResult) => {
    setPageParams({
      ...pageParams,
      pageNo: 1,
    });
    adapterFilterResult.categoryId = adapterFilterResult.categoryId?.map((item) => item.id);
    setFilterResult(adapterFilterResult);
  };

  useEffect(() => {
    getPropagandaCenter();
  }, []);

  useEffect(() => {
    const 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>
  );
}
