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

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

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

import api, { Device } from './api';
import { Box } from './styled';
// 此函数在构建时被调用
export async function getStaticProps() {
  // 获取筛选数据，进行静态渲染
  return {
    props: {},
  };
}

type Props = {};

export default function EquipmentLeasing(props: Props) {
  const { userInfo } = useContext(UserContext);
  const router = useRouter();
  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.images} alt='error' fill />
          </div>
        </div>
        <div className='item-bottom'>
          <div className='item-bottom-title' title={item.goodsName}>
            {item.goodsName}
          </div>
        </div>
      </div>
    );
  };

  const rightDom = (item: { id: number; bannerImg: string }) => {
    return (
      <div key={item.id} className='right-box-item right-item'>
        <AntdImage src={item.bannerImg} width={180} preview={false} />
      </div>
    );
  };

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

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

  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
      .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]);

  // eslint-disable-next-line
  const onFilterChange = (filterResult: FilterResult, adapterFilterResult: AdapterResult) => {
    setPageParams({
      ...pageParams,
      pageNo: 1,
    });
    adapterFilterResult.categoryId = adapterFilterResult.categoryId?.map((item) => item.id);
    setFilterResult(adapterFilterResult);
  };
  const getPropagandaCenter = () => {
    commonApi.listBannerImg('DEVICE_RENT').then((res) => {
      setRightProductList(
        (res.result || []).map((item) => {
          return { element: rightDom(item) };
        }),
      );
    });
  };

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