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

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

import errImg from '~/assets/errImg';
import Filter, { AdapterResult, FilterResult } from '~/components/filter';
import Layout from '~/components/layout';

import api, { Ad, Goods } from './api';
import styles from './index.module.scss';

// 此函数在构建时被调用
export async function getServerSideProps() {
  return {
    props: {},
  };
}

type Props = {};

export default function Mall(props: Props) {
  const router = useRouter();
  const [productList, setProductList] = useState<Array<Goods>>([]); // 商品列表
  const [filterResult, setFilterResult] = useState<AdapterResult>({}); // 筛选结果
  const [pageParams, setPageParams] = useState<{
    pageNo: number;
    pageSize: number;
  }>({
    pageNo: 1,
    pageSize: 15,
  }); // 分页器对象
  const [count, setCount] = useState(0); // 商品总数
  const [abort, setAbort] = useState<AbortController | null>(null); // 请求中断对象
  const [adList, setAdList] = useState<Array<Ad>>([]); // 广告列表
  const [loading, setLoading] = useState(false);

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

  // 商品列表请求
  useEffect(() => {
    if (!abort) {
      return;
    }
    setLoading(true);
    api
      .deviceList(
        {
          type: 0,
          ...pageParams,
          ...filterResult,
        },
        {
          signal: abort?.signal,
        },
      )
      .then((res) => {
        setProductList(res.result?.list || []);
        setCount(res.result?.totalCount || 0);
        setLoading(false);
      });
  }, [abort]);

  // 广告请求
  useEffect(() => {
    api.listBannerImg().then((res) => {
      setAdList(res.result || []);
    });
  }, []);
  // eslint-disable-next-line
  const onFilterChange = (filterResult: FilterResult, adapterFilterResult: AdapterResult) => {
    setPageParams({
      ...pageParams,
      pageNo: 1,
    });
    adapterFilterResult.categoryId = adapterFilterResult.categoryId?.map((item) =>
      item.children ? item.children[0].id : item.id,
    );
    setFilterResult(adapterFilterResult);
  };

  const onPageChange = (page: number, pageSize: number) => {
    setPageParams({
      ...pageParams,
      pageNo: page,
    });
  };
  return (
    <Layout>
      <div className='page' style={{ paddingTop: '18px' }}>
        <Filter types={[]} showResultItem onChange={onFilterChange}></Filter>

        <div className={styles.productList}>
          <div className={styles.main}>
            <div className={styles.listContent}>
              <Spin spinning={loading} delay={500}>
                <ul className={styles.listWrap}>
                  {productList.map((item, i) => {
                    return (
                      // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions
                      <li
                        key={i}
                        className={styles.item}
                        onClick={() => router.push(`/mall/detail/${item.id}`)}
                      >
                        <div className={styles.imgBox}>
                          <Image
                            alt=''
                            src={item.images}
                            className={styles.img}
                            preview={false}
                          ></Image>
                        </div>
                        <div className={styles.title}>{item.goodsName}</div>
                        <div className={styles.info}>
                          <div className={styles.desc}>{item.description}</div>
                          <div className={styles.sellCount}>
                            已售
                            {(Math.floor(Math.random() * 901) + 100).toFixed(0)}
                          </div>
                        </div>
                      </li>
                    );
                  })}
                  {productList.length === 0 && (
                    <Empty
                      style={{
                        paddingTop: 20,
                        width: '100%',
                        textAlign: 'center',
                      }}
                    ></Empty>
                  )}
                </ul>
              </Spin>

              <div className={styles.paginationPage}>
                <Pagination
                  current={pageParams.pageNo}
                  showSizeChanger={false}
                  showQuickJumper
                  total={count}
                  pageSize={pageParams.pageSize}
                  onChange={onPageChange}
                  hideOnSinglePage={true}
                  style={{ marginTop: 20 }}
                />
              </div>
            </div>

            <div className={styles.adList}>
              {adList.map((item) => {
                return (
                  <Image
                    key={item.id}
                    className={styles.ad}
                    src={item.bannerImg}
                    width={189}
                    // height={364}
                    preview={false}
                    fallback={errImg}
                  ></Image>
                );
              })}
            </div>
          </div>
        </div>
      </div>
    </Layout>
  );
}
