import { Button, Empty, Pagination, Spin } from 'antd';
import { useRouter } from 'next/router';
import { useState, useEffect } from 'react';
import api, { Item } from './api';
import styles from './index.module.scss';
import WxCodeModal from '~/components/wxCodeModal';

type Props = {
  params?: {
    cityCode: number; //市编码
    date: string; //时间 2023-05-19
    districtCode: number; //区编码
    provinceCode: number; //省编码
  };
  showWxCodeModalEvent: () => void;
};

export default function Cases(props: Props) {
  const [list, setList] = useState<Array<Item>>([]);
  const [pageParams, setPageParams] = useState({
    pageNo: 1,
    pageSize: 12,
  });
  const [count, setCount] = useState(0);
  const [abort, setAbort] = useState<AbortController | null>(null);
  const [loading, setLoading] = useState(false);
  const Router = useRouter();

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

  useEffect(() => {
    if (!abort) {
      return;
    }
    setLoading(true);
    api
      .listCasePage(
        {
          ...pageParams,
          ...props.params,
        },
        {
          signal: abort?.signal,
        },
      )
      .then((res) => {
        setList(res.result?.list || []);
        setCount(res.result?.totalCount || 0);
        setLoading(false);
      });
  }, [abort]);

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

  return (
    <>
      <Spin spinning={loading} delay={500}>
        <div className={styles.casas} style={{ height: 612 }}>
          {list.map((item) => {
            return (
              <div className={styles.item} key={item.id}>
                <div className={styles.info}>
                  <div
                    className={styles.title}
                    onClick={() => Router.push('/projectInfo/caseArticle/' + item.id)}
                  >
                    {item.caseTitle}
                  </div>
                </div>
                <Button
                  type='primary'
                  className={styles.btn}
                  onClick={() => props.showWxCodeModalEvent()}
                >
                  品牌合作
                </Button>
              </div>
            );
          })}
          {list.length === 0 && <Empty></Empty>}
        </div>
        <Pagination
          current={pageParams.pageNo}
          defaultPageSize={pageParams.pageSize}
          showSizeChanger={false}
          showQuickJumper
          total={count}
          onChange={onPageChange}
          hideOnSinglePage={true}
          style={{ marginTop: 20 }}
        />
      </Spin>
    </>
  );
}
