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

import { Button, Col, Empty, Pagination, Row, Spin } from 'antd';
import Image from 'next/image';
import Router, { useRouter } from 'next/router';

import { UserContext } from '~/lib/userProvider';

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

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

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

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

  useEffect(() => {
    if (!abort) {
      return;
    }
    setLoading(true);
    api
      .listNewsPage(
        {
          ...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,
    });
  };

  // 获取产品信息事件
  const onGetInfo = () => {
    if (userInfo) {
      if (!userInfo.companyAuthStatus) {
        Router.push('/certification?type=back');
      }
    } else {
      setNeedLogin(true);
    }
  };
  // 新闻点击
  const newsClick = (item: Item) => {
    router.push(`/projectInfo/newsArticle/${item.id}`);
  };
  return (
    <Spin spinning={loading} delay={500}>
      <Row justify='space-between' style={{ height: 606 }}>
        <Col className={styles.new}>
          {list.map((item) => {
            return (
              <div className={styles.item} key={item.id} onClick={() => newsClick(item)}>
                <Image
                  className={styles.logo}
                  src={item.surfaceImg}
                  alt=''
                  width={120}
                  height={80}
                ></Image>
                <div className={styles.info}>
                  <div className={styles.title}>{item.newsTitle}</div>
                  <div
                    className={styles.desc}
                    dangerouslySetInnerHTML={{
                      __html: item.newsContents.replace(/<img(?:(?!\/>).|\n)*?\/>/gm, '') || '',
                    }}
                  ></div>
                  <div className={styles.date}>
                    {item.createTime} · 作者:{item.newsAuthor}
                  </div>
                </div>
                <Button
                  type='primary'
                  style={{ width: 120, height: 40, flexShrink: 0 }}
                  onClick={(e) => {
                    props.showWxCodeModalEvent();
                    e.stopPropagation();
                  }}
                >
                  商务合作
                </Button>
              </div>
            );
          })}
        </Col>
        {list.length === 0 && <Empty style={{ margin: '0 auto' }}></Empty>}
      </Row>

      <Pagination
        current={pageParams.pageNo}
        defaultPageSize={pageParams.pageSize}
        showSizeChanger={false}
        showQuickJumper
        total={count}
        onChange={onPageChange}
        hideOnSinglePage={true}
        style={{ marginTop: 20 }}
      />
    </Spin>
  );
}
