import type { ProColumns } from '@ant-design/pro-table';
import { Typography } from 'antd';
import _ from 'lodash';
import { useCallback, useMemo } from 'react';
import { FormattedMessage, useIntl } from 'umi';
import CustomTable from '../../CustomTable';
import ExpandIcon from '../../ExpandIcon';
import { traverseAndAddAttribute } from '../../utils';
import style from '../index.less';

const { Text } = Typography;

export interface PermissionTableProps {
  data: {
    featureTree: any;
    optionTree: any;
    policyNames: any;
    roleNames: any;
    cityNames: any;
  };
}

const PermissionTable = (props: PermissionTableProps) => {
  const { data } = props;

  const { formatMessage } = useIntl();

  const permission = useMemo(() => {
    const { optionTree } = data;
    const option = Array.isArray(optionTree) ? _.cloneDeep(optionTree) : [];
    traverseAndAddAttribute(option);
    const optionMap = option.reduce((pre, cur) => {
      pre.push(...cur.children);
      return pre;
    }, []);
    return { optionMap, ..._.pick(data, 'cityNames', 'featureTree', 'policyNames', 'roleNames') };
  }, [data]);

  const nameDataSource = useCallback((record: Record<string, any>) => {
    const { name, data: permissionData } = record;
    if (['policy', 'role', 'city'].includes(name)) {
      return permissionData.map((n: any) => ({ name: n }));
    } else if (['option', 'feature'].includes(name)) {
      return permissionData.map((i: any) => {
        const v = _.cloneDeep(i);
        if (v.hasOwnProperty('optionTree')) {
          v.children = v.optionTree;
        }
        return v;
      });
    }
    return [];
  }, []);

  const childColumns = useMemo<ProColumns<Record<string, any>>[]>(() => {
    const permissionMap = {
      feature: formatMessage({ id: 'base.common.feature.permission' }),
      option: formatMessage({ id: 'base.common.flag.permission' }),
      policy: formatMessage({ id: 'base.common.policy.permission' }),
      role: formatMessage({ id: 'base.common.role.permission' }),
      city: formatMessage({ id: 'base.common.city.permission' }),
    };
    return [
      {
        title: <FormattedMessage id="base.permissipn.type" defaultMessage="权限类型" />,
        dataIndex: 'name',
        ellipsis: true,
        search: false,
        width: 150,
        render: (__, record) => {
          return <Text ellipsis={{ tooltip: true }}>{permissionMap[record?.name]}</Text>;
        },
      },
      {
        title: <FormattedMessage id="public.const.BlockType.3.label" defaultMessage="权限名称" />,
        dataIndex: 'name',
        ellipsis: true,
        search: false,
        width: 300,
        render: (__, record) => {
          return (
            <CustomTable
              overflow={true}
              className={`${style.icon} ${style.nameColumn}`}
              pagination={false}
              headerTitle={false}
              search={false}
              options={false}
              showHeader={false}
              style={{ width: 300 }}
              expandable={{ expandIcon: ExpandIcon }}
              columns={[
                {
                  title: <FormattedMessage id="base.permissipn.type" defaultMessage="功能权限" />,
                  dataIndex: 'name',
                  ellipsis: true,
                  search: false,
                  width: 250,
                  className: style['ant-table-overflow-row'],
                },
              ]}
              dataSource={nameDataSource(record)}
            />
          );
        },
      },
    ];
  }, [formatMessage, nameDataSource]);

  const dataSource = useCallback(
    (key: string) => {
      const permissionData = permission[key];
      if (['policyNames', 'roleNames', 'cityNames'].includes(key)) {
        return [{ name: key.split('Names')[0], data: permissionData?.split(',') }];
      } else if (key === 'featureTree') {
        return [{ name: 'feature', data: permissionData }];
      } else if (key === 'optionMap') {
        return [{ name: 'option', data: permissionData }];
      }
      return [];
    },
    [permission],
  );

  return (
    <>
      {Object.keys(permission)
        .filter((key) => permission[key]?.length)
        .map((key) => {
          return (
            <CustomTable
              key={key}
              overflow={true}
              className={style.permissionTable}
              pagination={false}
              search={false}
              options={false}
              showHeader={false}
              columns={childColumns}
              dataSource={dataSource(key)}
            />
          );
        })}
    </>
  );
};

export default PermissionTable;
