import type { ProColumns } from '@ant-design/pro-table';
import { Button, Popconfirm, Space, Tooltip, Typography } from 'antd';
import _ from 'lodash';
import type { Dispatch, Key, SetStateAction } from 'react';
import { useCallback } from 'react';
import { FormattedMessage, useIntl } from 'umi';
import AuditCountersign from '../AuditCountersign';
import AuditPassOn from '../AuditPassOn';
import AuditProgress from '../AuditProgress';
import BindAllPermission from '../BindAllPermission';
import CustomTable from '../CustomTable';
import ExpandIcon from '../ExpandIcon';
import Tips from '../Tips';
import publicConst from '../utils/const';
import { AduitStatus } from './const';
import type { RowType } from './hooks';
import lessStyle from './index.less';

const { DataSensitiveLevelTips, DataSensitiveTips } = Tips;
const { Text } = Typography;

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

const UacTable = (props: UacTableProps) => {
  const {
    auditDetail,
    rowSelectionKeys,
    chainId,
    pageReadOnly,
    setSelectionKeys,
    approvalHandler,
    requestDetail,
  } = props;
  const { auditList, appInfo } = auditDetail || {};
  const { formatMessage } = useIntl();

  const columns = useCallback(
    (type: string): ProColumns<any>[] => {
      const { DataSensitiveMap, DataSensitiveLevelMap } = publicConst(formatMessage);
      return [
        {
          title: (
            <FormattedMessage id={`base.common.${type}.permission`} defaultMessage="权限名称" />
          ),
          dataIndex: 'name',
          search: false,
          hideInTable: false,
          className: lessStyle.nameColumn,
          render: (__, record: any) => {
            const { id, name } = record;
            return (
              <>
                <Tooltip title={name}>
                  <span className={lessStyle.text}>{name}</span>
                </Tooltip>

                {type === 'role' && (
                  <BindAllPermission
                    appId={appInfo?.id}
                    roleId={id}
                    roleName={name}
                    iconStyle={{ padding: '0 4px' }}
                  />
                )}
              </>
            );
          },
        },
        {
          title: <FormattedMessage id="pages.funcList.sensitiveLevel" defaultMessage="敏感等级" />,
          dataIndex: 'dataSensitive',
          search: false,
          tooltip: DataSensitiveLevelTips,
          valueType: 'select',
          valueEnum: DataSensitiveLevelMap,
        },
        {
          title: <FormattedMessage id="pages.funcList.sensitivity" defaultMessage="敏感度" />,
          dataIndex: 'sensitiveLevel',
          search: false,
          tooltip: DataSensitiveTips,
          valueType: 'select',
          valueEnum: DataSensitiveMap,
        },
        {
          title: <FormattedMessage id="pages.process.expiration" defaultMessage="有效期" />,
          dataIndex: 'expiredAt',
          search: false,
          ellipsis: true,
          render: (__: any, record: any) => {
            const expiredAt = type === 'city' ? 0 : record.expiredAt;
            return (
              _.isNumber(expiredAt) && (
                <Text ellipsis={{ tooltip: true }}>
                  {expiredAt === 0
                    ? formatMessage({ id: 'pages.setting.base.defaultExpirationTime.forever' })
                    : expiredAt / 86400}
                </Text>
              )
            );
          },
        },
        {
          title: <FormattedMessage id="pages.process.approval.status" defaultMessage="审批状态" />,
          dataIndex: 'uacAuditState',
          search: false,
          render: (__: any, record: any) => {
            const { uacAuditState } = record;
            return (
              _.isNumber(uacAuditState) &&
              uacAuditState !== 0 && (
                <Text ellipsis={{ tooltip: true }}>
                  {formatMessage({ id: AduitStatus[uacAuditState] })}
                </Text>
              )
            );
          },
        },
        {
          title: <FormattedMessage id="pages.process.approval" defaultMessage="审批流" />,
          dataIndex: 'uacAuditId',
          search: false,
          render: (__: any, record: any) => {
            const { uacAuditId } = record;
            return (
              Boolean(uacAuditId) && (
                <AuditProgress uacAuditId={uacAuditId} chainId={chainId}>
                  <Button size={'small'} type={'primary'} ghost>
                    {formatMessage({ id: 'base.button.view' })}
                  </Button>
                </AuditProgress>
              )
            );
          },
        },
        {
          title: <FormattedMessage id="base.common.operation" defaultMessage="操作" />,
          dataIndex: 'permissionOption',
          valueType: 'option',
          fixed: 'right',
          align: 'center',
          width: 240,
          search: false,
          hideInTable: pageReadOnly,
          render: (__: any, record: any) => {
            const { uacAuditId, uacCanAudit } = record;
            return (
              Boolean(uacAuditId && uacCanAudit) && (
                <Space>
                  <Popconfirm
                    title={formatMessage({ id: 'component.AuditList.view.agree.tips' })}
                    placement={'topRight'}
                    onConfirm={() => {
                      approvalHandler([uacAuditId], 1, 'uac');
                    }}
                  >
                    <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([uacAuditId], 3, 'uac');
                    }}
                  >
                    <Button size={'small'} danger>
                      {formatMessage({ id: 'base.button.reject' })}
                    </Button>
                  </Popconfirm>

                  <AuditCountersign
                    chainId={chainId}
                    auditId={uacAuditId}
                    type={'uac'}
                    onComplete={requestDetail}
                  />

                  <AuditPassOn
                    chainId={chainId}
                    auditId={uacAuditId}
                    type={'uac'}
                    onComplete={requestDetail}
                    auditDetail={auditDetail}
                  />
                </Space>
              )
            );
          },
        },
      ];
    },
    [
      formatMessage,
      pageReadOnly,
      appInfo?.id,
      chainId,
      requestDetail,
      auditDetail,
      approvalHandler,
    ],
  );

  const rowSelection = useCallback(
    (type: string) => {
      if (pageReadOnly) return false;
      return {
        getCheckboxProps: (record: any) => ({
          disabled: !record.uacCanAudit,
        }),
        selectedRowKeys: rowSelectionKeys?.[type],
        onChange: (rowKey: Key[]) => {
          setSelectionKeys((oldVal: RowType) => ({ ...oldVal, [type]: rowKey }));
        },
      };
    },
    [pageReadOnly, rowSelectionKeys, setSelectionKeys],
  );

  return (
    <>
      {Array.isArray(auditList) &&
        auditList.map((item, index) => {
          const { feature, option, policy, role, city } = item;
          const obj = {
            feature,
            option: option?.map((o: any) => ({ ...o, children: o?.optionTree })),
            policy,
            role,
            city,
          };
          return Object.keys(obj)
            .filter((key) => Array.isArray(obj[key]) && obj[key].length)
            .map((key) => {
              const dataSource = obj[key];
              return (
                <CustomTable
                  // eslint-disable-next-line react/no-array-index-key
                  key={`uacTable_${key}_${index}`}
                  overflow={true}
                  expandable={{
                    expandIcon: (p) => <ExpandIcon {...p} style={{ padding: '0 4px' }} />,
                  }}
                  pagination={false}
                  headerTitle={false}
                  search={false}
                  options={false}
                  rowKey={(record: any) => record.uacAuditId ?? record.uniqueKey}
                  rowSelection={rowSelection(key)}
                  columns={columns(key)}
                  dataSource={dataSource}
                />
              );
            });
        })}
    </>
  );
};

export default UacTable;
