import React, { useEffect, useState } from 'react';
import { Empty, Pagination, Image, Spin } from 'antd';
import Layout from '~/components/layout';
import styles from './index.module.scss';
import { useRouter } from 'next/router';
import Filter, { AdapterResult, FilterResult } from '~/components/filter';
import api, { Ad, Goods } from './api';
import errImg from '~/assets/errImg';

// 此函数在构建时被调用
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 || []);
    });
  }, []);

  const onFilterChange = (filterResult: FilterResult, adapterFilterResult: AdapterResult) => {
    setPageParams({
      ...pageParams,
      pageNo: 1,
    });
    adapterFilterResult.categoryId = adapterFilterResult.categoryId?.map((item) => 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 (
                      <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.sellCount}>
                          半年售
                          {(Math.floor(Math.random() * 901) + 100).toFixed(0)}
                        </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>
  );
}
