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

import { Button, Empty, Pagination, Popconfirm, Spin, Tooltip } from 'antd';

import { CommonContext } from '~/lib/commonProvider';
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; // 省编码
  };
};

export default function Requirements(props: Props) {
  const [loading, setLoading] = useState(false);
  const [list, setList] = useState<Array<Item>>([]);
  const [pageParams, setPageParams] = useState({
    pageNo: 1,
    pageSize: 8,
  });
  const [count, setCount] = useState(0);
  const [abort, setAbort] = useState<AbortController | null>(null);
  const [reload, setReload] = useState(false);
  const { userInfo } = useContext(UserContext);
  const { reloadRequirements } = useContext(CommonContext);

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

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

  /**
   * 确认解决
   * @param e
   */
  const confirmSolved = (item: Item) => {
    api
      .solveRequire({
        requirementsInfoId: item.id,
      })
      .then((res) => {
        if (res.code === '200') {
          window.messageApi.success('提交完成');
          setReload(!reload);
        }
      });
  };

  return (
    <Spin spinning={loading} delay={500}>
      <div className={styles.requirements} style={{ height: 635 }}>
        {list.map((item) => {
          return (
            <div className={`${styles.item} ${!item.solved && styles.noResolve}`} key={item.id}>
              <div className={styles.logo}></div>
              <div className={styles.info}>
                <div className={styles.title}>项目需求：{item.requirementTypeName}</div>

                <Tooltip placement='top' title={item.requireDescription}>
                  <div className={styles.desc}>具体需求：{item.requireDescription}</div>
                </Tooltip>
              </div>
              {userInfo && item.userAccountId === userInfo.id ? (
                <Popconfirm
                  title='提示'
                  description='确认该需求已经解决了吗？'
                  onConfirm={() => confirmSolved(item)}
                  okText='是'
                  cancelText='否'
                  disabled={!!item.solved}
                >
                  <Button
                    type='primary'
                    style={{ width: 120, height: 40, flexShrink: 0 }}
                    disabled={!!item.solved}
                  >
                    已解决
                  </Button>
                </Popconfirm>
              ) : (
                <div style={{ width: 120, flexShrink: 0 }}></div>
              )}
            </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>
  );
}
