import { Button, Popconfirm, Space, Table, Typography } from 'antd';
import type { ColumnsType } from 'antd/lib/table';
import type { Dispatch, SetStateAction } from 'react';
import { useMemo } from 'react';
import { FormattedMessage, useIntl } from 'umi';
import AuditCountersign from '../AuditCountersign';
import AuditPassOn from '../AuditPassOn';
import AuditProgress from '../AuditProgress';
import ExpandIcon from '../ExpandIcon';
import { AduitStatus } from './const';
import type { RowType } from './hooks';
import lessStyle from './index.less';
import PermissionTable from './PermissionTable';
import { flatAuditList, isFlatAuditList } from './util';

const { Text } = Typography;

export interface BpmTableProps {
  auditDetail: any;
  chainId: string;
  pageReadOnly?: boolean;
  rowSelectionKeys?: RowType;
  setSelectionKeys?: Dispatch<SetStateAction<RowType>>;
  approvalHandler: (id: any[], state: number, type: string) => Promise<void>;
  requestDetail?: () => Promise<void>;
}

const BpmTable = (props: BpmTableProps) => {
  const {
    auditDetail,
    chainId,
    pageReadOnly,
    rowSelectionKeys,
    setSelectionKeys,
    approvalHandler,
    requestDetail,
  } = props;
  const { formatMessage } = useIntl();

  const columns = useMemo<ColumnsType<any>>(() => {
    return [
      {
        title: <FormattedMessage id="component.AuditList.approvalNo" defaultMessage="审批编号" />,
        dataIndex: 'bpmAuditId',
        search: false,
        ellipsis: true,
      },
      {
        title: <FormattedMessage id="pages.process.approval.status" defaultMessage="审批状态" />,
        dataIndex: 'bpmAuditNode',
        search: false,
        render: (__: any, record: any) => {
          const { bpmAuditNode } = record;
          return (
            Array.isArray(bpmAuditNode) &&
            bpmAuditNode.length > 0 && (
              <Text ellipsis={{ tooltip: true }}>
                {formatMessage({ id: AduitStatus[bpmAuditNode[bpmAuditNode.length - 1]?.state] })}
              </Text>
            )
          );
        },
      },
      {
        title: <FormattedMessage id="component.audit.detail.title" defaultMessage="审批流" />,
        dataIndex: 'bpmAuditNode',
        search: false,
        render: (__: any, record: any) => {
          const { bpmAuditNode } = record;
          return (
            <AuditProgress bpmAuditNode={bpmAuditNode} detailData={auditDetail}>
              <Button type={'primary'} size={'small'} ghost>
                {formatMessage({ id: 'base.button.view' })}
              </Button>
            </AuditProgress>
          );
        },
      },
      {
        title: <FormattedMessage id="base.common.operation" defaultMessage="操作" />,
        dataIndex: 'permissionOption',
        valueType: 'option',
        fixed: 'right',
        align: 'center',
        search: false,
        hideInTable: pageReadOnly,
        render: (__: any, record: any) => {
          const { bpmCanAudit, bpmAuditId } = record;
          return (
            Boolean(chainId && bpmCanAudit) && (
              <Space>
                <Popconfirm
                  title={formatMessage({ id: 'component.AuditList.view.agree.tips' })}
                  placement={'topRight'}
                  onConfirm={() => {
                    approvalHandler([bpmAuditId], 1, 'bpm');
                  }}
                >
                  <Button size={'small'} type={'primary'} ghost>
                    {formatMessage({ id: 'base.button.agree' })}
                  </Button>
                </Popconfirm>

                <Popconfirm
                  title={formatMessage({ id: 'component.AuditList.view.reject.tips' })}
                  placement={'topRight'}
                  onConfirm={() => {
                    approvalHandler([bpmAuditId], 3, 'bpm');
                  }}
                >
                  <Button size={'small'} danger>
                    {formatMessage({ id: 'base.button.reject' })}
                  </Button>
                </Popconfirm>

                <AuditCountersign
                  chainId={chainId}
                  auditId={bpmAuditId}
                  type={'bpm'}
                  onComplete={requestDetail}
                />

                <AuditPassOn
                  chainId={chainId}
                  auditId={bpmAuditId}
                  type={'bpm'}
                  onComplete={requestDetail}
                  auditDetail={auditDetail}
                />
              </Space>
            )
          );
        },
      },
    ];
  }, [pageReadOnly, formatMessage, auditDetail, chainId, requestDetail, approvalHandler]);

  const { auditList } = auditDetail || {};

  // 是否以扁平化的形式展示
  const flatShow = useMemo(() => isFlatAuditList(auditList), [auditList]);

  return (
    <>
      {Array.isArray(auditList) &&
        Boolean(auditList.length) &&
        (flatShow ? (
          <PermissionTable
            auditDetail={auditDetail}
            data={flatAuditList(auditList)}
            approvalHandler={approvalHandler}
            chainId={chainId}
            pageReadOnly={pageReadOnly}
            rowSelectionKeys={rowSelectionKeys}
            setSelectionKeys={setSelectionKeys}
            requestDetail={requestDetail}
          />
        ) : (
          <Table
            rowKey={'bpmAuditId'}
            className={lessStyle.parentTable}
            pagination={false}
            columns={columns}
            expandable={{
              rowExpandable: () => true,
              defaultExpandAllRows: true,
              expandIcon: (p) => <ExpandIcon {...p} useSenior dataControl={false} />,
              expandedRowRender: (record: any) => {
                return <PermissionTable auditDetail={auditDetail} data={record} />;
              },
            }}
            dataSource={auditList}
          />
        ))}
    </>
  );
};

export default BpmTable;
