import { Modal, Spin, Typography } from 'antd';
import Link from 'antd/lib/typography/Link';
import { useEffect, useState } from 'react';
import { useIntl, useRequest } from 'umi';
import { fetchAuditDetail } from '../server';
import { useGetAppId } from '../utils/hooks';
import DetailStep from './DetailStep';
import { list as tempList } from './services';

export interface AuditTemplateDetailProps {
  /**
   * @description 审批流程的id
   */
  id: number;
  /**
   * @description appId
   */
  appId?: number;
  /**
   * @description 审批流程显示内容
   */
  name?: React.ReactNode | string;
  /**
   * @description 是否展示弹窗
   */
  isModal?: boolean;
}

/**
 * @description 审批流详情, 当总流程大于四个，就纵向排列显示。当总流程小于四个，就横向排列显示。
 */
const AuditTemplateDetail = (props: AuditTemplateDetailProps) => {
  const { id, name = '', isModal = true, appId: customAppId } = props;

  const { formatMessage } = useIntl();
  const appId = useGetAppId();
  const [open, setOpen] = useState(false);
  const [isNew, setIsNew] = useState(false);
  const [list, setList] = useState<API.User[][]>([]);
  const [newStep, setNewStep] = useState<any[]>([]);

  const { loading, run } = useRequest(fetchAuditDetail(), {
    manual: true,
    onSuccess: (result) => {
      setNewStep(result?.newStep ?? []);
      setList([
        [{ nameZh: formatMessage({ id: 'component.audit.detail.start' }) }],
        ...result?.users,
        [{ nameZh: formatMessage({ id: 'component.audit.detail.end' }) }],
      ]);
    },
  });

  useEffect(() => {
    if (open || !isModal) {
      run(id);
      if (appId || customAppId) {
        const newRequest = tempList(true);
        newRequest({
          appId: appId || customAppId,
          state: '1',
          current: 0,
          pageSize: 0,
        }).then((data) => {
          if (data?.total && data?.total > 0) {
            setIsNew(true);
          }
        });
      }
    }
  }, [open, id, appId, customAppId, isModal, run]);

  if (isModal)
    return (
      <>
        <Modal
          title={formatMessage({ id: 'component.audit.detail.title' })}
          open={open}
          destroyOnClose
          footer={null}
          onCancel={() => setOpen(false)}
        >
          {open && <DetailStep list={list} newStep={newStep} />}

          {isNew && (
            <Typography.Text type={'danger'}>
              {formatMessage({ id: 'component.audit.detail.newAudit' })}
            </Typography.Text>
          )}
        </Modal>

        <Typography.Text ellipsis={{ tooltip: name }}>
          <Link onClick={() => setOpen(true)}>{name}</Link>
        </Typography.Text>

        <Spin spinning={loading} />
      </>
    );

  return <DetailStep list={list} newStep={newStep} />;
};

export default AuditTemplateDetail;
