import { Pagination } from 'antd';
import Image from 'next/image';
import { useRouter } from 'next/router';
import { useContext, 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';
import { UserContext } from '~/lib/userProvider';
// 此函数在构建时被调用
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>
          {userInfo?.cooperationTagId ? (
            <div className='item-bottom-price'>
              <span className='money'>¥{item.price}</span>
              <span className='unit'>/天起</span>
            </div>
          ) : (
            <div className='unit'>暂无报价</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({
    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(() => {
    let 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]);

  const onFilterChange = (filterResult: FilterResult, adapterFilterResult: AdapterResult) => {
    setPageParams({
      ...pageParams,
      pageNo: 1,
    });
    adapterFilterResult.categoryId = adapterFilterResult.categoryId?.map((item) => item.id);
    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 (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>
  );
}
