import type { TypeResult } from '@/pages/ApplyList/hooks';
import { Table } from 'antd';
import type { ColumnType } from 'antd/lib/table';
import { useMemo } from 'react';
import { FormattedMessage, useIntl } from 'umi';
import style from '../index.less';
import ApprovalSteps from './approvalSteps';
import PermissionTable from './permissionTable';

export interface PreviewTableProps {
  type?: 'single' | 'multiple';
  packageData?: TypeResult;
  dataSource: Record<string, any>[];
}

const PreviewTable = (props: PreviewTableProps) => {
  const { dataSource, type = 'single', packageData } = props;

  const { formatMessage } = useIntl();

  const list = useMemo(() => {
    if (type === 'single') return dataSource;
    // 权限包
    const index = dataSource?.[0]?.data?.[0];
    return [
      {
        name: packageData?.name,
        uacStep: index?.uacStep,
        workflow: index?.workflow,
      },
    ];
  }, [dataSource, packageData?.name, type]);

  const columns = useMemo<ColumnType<Record<string, any>>[]>(() => {
    const res: ColumnType<Record<string, any>>[] = [
      {
        title: <FormattedMessage id="pages.process.approval" defaultMessage="审批流" />,
        dataIndex: 'uacStep',
        ellipsis: true,
        render: (__, record) => {
          const { uacStep, workflow } = record || {};
          const data = uacStep || workflow;
          return <ApprovalSteps record={data} type={uacStep ? 'uac' : 'bpm'} />;
        },
      },
    ];

    if (type === 'multiple') {
      res.unshift(
        {
          title: formatMessage({ id: 'base.permissipn.type' }),
          dataIndex: 'type',
          ellipsis: true,
          width: 250,
          render: () => formatMessage({ id: 'base.common.multiple.app.apply' }),
        },
        {
          title: formatMessage({ id: 'base.permissipn.name' }),
          dataIndex: 'name',
          ellipsis: true,
          width: 250,
        },
      );
    } else {
      // 单应用申请
      res.unshift({
        title: (
          <div style={{ width: 500 }}>
            <div className={style.headTitle} style={{ width: 150, display: 'inline-block' }}>
              {formatMessage({ id: 'base.permissipn.type' })}
            </div>
            <div style={{ padding: '0  8px', width: 334, display: 'inline-block' }}>
              {formatMessage({ id: 'page.process.permission.name' })}
            </div>
          </div>
        ),
        fixed: 'left',
        dataIndex: 'name',
        className: style.permissionColumn,
        ellipsis: true,
        width: 500,
        render: (__, record) => {
          return <PermissionTable data={record.params} />;
        },
      });
    }
    return res;
  }, [formatMessage, type]);

  return (
    <Table
      className={`${style.typename} ${style.previewTable}`}
      pagination={false}
      columns={columns}
      dataSource={list}
    />
  );
};

export default PreviewTable;
