import { Modal, Space, Spin, Steps, Tag, Tooltip } from 'antd';
import Link from 'antd/lib/typography/Link';
import _ from 'lodash';
import moment from 'moment';
import { useEffect, useMemo, useState } from 'react';
import { useIntl, useRequest } from 'umi';
import UserLink from '../UserInfo/link';
import Countersign from './countersign';
import PassOn from './passOn';
import { bpmAuditNodeFormat, getProgressIndex, uacAuditNodeFormat } from './util';

const { Step } = Steps;

export interface AuditProgressProps {
  /**
   * @description 是否展示弹窗
   */
  isModal?: boolean;
  /**
   * @description 审批流程的chainId 必填
   */
  chainId?: string;
  /**
   * @description 如果是uac审批流，uac审批流程的id 必填
   */
  uacAuditId?: string;
  /**
   * @description 审批流程显示内容
   */
  children?: React.ReactNode;
  bpmAuditNode?: any[];
  detailData?: any;
}

/**
 * @description 审批流详情, 当总流程大于四个，就纵向排列显示。当总流程小于四个，就横向排列显示。
 */
const AuditProgress = (props: AuditProgressProps) => {
  const { isModal = true, chainId, uacAuditId, children, bpmAuditNode, detailData } = props;
  const { formatMessage } = useIntl();
  const [open, setOpen] = useState(false);
  const [list, setList] = useState<API.AuditProgress[]>([]);
  const [auditDetail, setAuditDetail] = useState<{ initiator: API.User }>();

  const { loading: uacLoading, run: uacRun } = useRequest(
    () => ({
      url: '/goapi/audit/progress',
      method: 'POST',
      data: { chainId, uacAuditId },
    }),
    {
      manual: true,
      onSuccess: (result) => {
        setList(uacAuditNodeFormat(result));
      },
    },
  );

  const { loading: bpmLoading, run: bpmRun } = useRequest(
    () => ({
      url: '/goapi/audit/detail',
      method: 'POST',
      data: { chainId },
    }),
    {
      manual: true,
      onSuccess: (result) => {
        setList(bpmAuditNodeFormat(result?.auditList?.[0]?.bpmAuditNode));
        setAuditDetail(result);
      },
    },
  );

  useEffect(() => {
    if (open || !isModal) {
      if (chainId && uacAuditId) {
        uacRun();
      } else if (chainId) {
        bpmRun();
      } else if (bpmAuditNode?.length) {
        setList(bpmAuditNodeFormat(bpmAuditNode));
        if (detailData) setAuditDetail(detailData);
      }
    }
  }, [bpmAuditNode, bpmRun, chainId, detailData, isModal, open, uacAuditId, uacRun]);

  const titleMap = useMemo(
    () => ({
      '-1': formatMessage({ id: 'component.AuditProgress.status.begin' }),
      '1': formatMessage({ id: 'component.AuditProgress.status.pass' }),
      '2': formatMessage({ id: 'component.AuditProgress.status.wait' }),
      '3': formatMessage({ id: 'component.AuditProgress.status.reject' }),
      '4': formatMessage({ id: 'component.AuditProgress.status.cancel' }),
      '5': formatMessage({ id: 'component.AuditProgress.status.delete' }),
    }),
    [formatMessage],
  );

  const userRender = (user: API.User, showInitiator?: boolean) => {
    const { id: userId, nameZh, proxyUser, isAdminAudit, isAutoPass, autoMessage } = user;

    const { initiator } = auditDetail || {};

    return (
      <Space key={userId} size={0} wrap>
        {/* 审批人 */}
        {userId ? <UserLink user={user} /> : nameZh} &nbsp;
        {/* 代发起用户 */}
        {Boolean(initiator?.id && showInitiator) && (
          <>
            (<UserLink user={initiator} />
            &nbsp;
            {formatMessage({ id: 'component.AuditProgress.instead' })}) &nbsp;
          </>
        )}
        {/* 自动通过 */}
        {Boolean(isAutoPass) && (
          <Tooltip title={autoMessage}>
            <Tag color={'error'}>{formatMessage({ id: 'component.AuditProgress.auto' })}</Tag>
          </Tooltip>
        )}
        {/* 管理员审批 */}
        {Boolean(isAdminAudit) && (
          <Tag color={'error'}>{formatMessage({ id: 'component.AuditProgress.management' })}</Tag>
        )}
        {/* 代理人 */}
        {Array.isArray(proxyUser) && proxyUser.length > 0 && (
          <Tooltip
            title={proxyUser.map((pu) => (
              <UserLink key={pu.id} user={pu} />
            ))}
          >
            <Tag color={'error'}>{formatMessage({ id: 'component.AuditProgress.proxy' })}</Tag>
          </Tooltip>
        )}
      </Space>
    );
  };

  const content = (
    <Steps direction={'vertical'} progressDot current={getProgressIndex(list)} size={'small'}>
      {list?.map((item) => {
        const {
          id: pId,
          state: pState,
          time,
          users,
          isCountersignNode,
          countersign,
          passOnUser,
          isCcNode,
        } = item;
        const showInitiator = pState === -1 || pId === -1;
        return (
          <Step
            key={pId}
            title={
              <>
                {isCcNode
                  ? formatMessage({ id: 'component.AduitPreview.steps.noticeNode' })
                  : titleMap[pId === -1 ? '-1' : pState]}

                {/* 加签记录 */}
                {Boolean(isCountersignNode) && (
                  <Tooltip
                    title={<Countersign users={countersign} />}
                    overlayInnerStyle={{ display: 'inline-flex' }}
                  >
                    <Tag color={'error'} style={{ marginLeft: 6 }}>
                      {formatMessage({ id: 'component.AuditCountersign.node' })}
                    </Tag>
                  </Tooltip>
                )}

                {/* 转交记录 */}
                {Array.isArray(passOnUser) && passOnUser.length > 0 && (
                  <Tooltip
                    title={<PassOn users={passOnUser} />}
                    overlayInnerStyle={{ display: 'inline-flex' }}
                  >
                    <Tag color={'error'}>
                      {formatMessage({ id: 'component.AuditPassOn.title' })}
                    </Tag>
                  </Tooltip>
                )}
              </>
            }
            description={
              <>
                {/* 显示需要操作的用户 */}
                <Space size={0} wrap direction={'vertical'}>
                  {users.map((user) => userRender(user, showInitiator))}
                </Space>

                {/* 如果有操作时间，那么就显示操作时间 */}
                {_.isNumber(time) && time > 0 && (
                  <div style={{ fontSize: 12 }}>
                    {moment(time * 1000).format('YYYY-MM-DD HH:mm:ss')}
                  </div>
                )}
              </>
            }
          />
        );
      })}
    </Steps>
  );

  if (!isModal) return content;

  return (
    <>
      <Modal
        title={formatMessage({ id: 'component.audit.detail.title' })}
        open={open}
        destroyOnClose
        footer={null}
        onCancel={() => setOpen(false)}
      >
        {content}
      </Modal>

      <Link onClick={() => setOpen(true)}>{children}</Link>

      <Spin spinning={uacLoading || bpmLoading} />
    </>
  );
};

export default AuditProgress;
