import { Checkbox, Input, Popconfirm, Space, Typography } from 'antd';
import { ConfigProvider, Table } from 'antd5';
import { cloneDeep } from 'lodash';
import { memo, useMemo } from 'react';
import { FormattedMessage } from 'umi';
import CityModal from '../../CityModal';
import ExpandIcon from '../../ExpandIcon';
import PermissionParentShow from '../../PermissionParentShow';
import { leafBuildTree, tree2FlatArray } from '../../utils/array';
import { requestBatchUnbind } from '../api';
import style from './index.less';

const { Text } = Typography;

export interface Feature {
  isOptShow?: boolean;
  DataSensitiveMap?: any;
  DataSensitiveLevelMap?: any;
  setOpenObj?: any;
  params?: any;
  setParams?: any;
  setExpandedAll?: any;
  expandedAll?: any;
  formatMessage?: any;
  moment?: any;
  appId?: any;
  setRenewalParams?: any;
  currentUser?: any;
  batchParams?: any;
  setBatchParams?: any;
  data?: any;
  permission?: any;
  run?: any;
  showSelected?: boolean;
}

const FeatureTable = (props: Feature) => {
  const {
    isOptShow,
    DataSensitiveMap,
    DataSensitiveLevelMap,
    setOpenObj,
    params,
    setParams,
    setExpandedAll,
    expandedAll,
    formatMessage,
    moment,
    appId,
    setRenewalParams,
    currentUser,
    batchParams,
    setBatchParams,
    data,
    permission,
    run,
    showSelected,
  } = props;

  const { featureTree, featureCityIds } = data || {};
  const { featureTree: filterFeatureTree } = permission || {};

  const featureTreeColumn = [
    {
      title: <FormattedMessage id="base.common.feature.permission" defaultMessage="功能权限" />,
      dataIndex: 'name',
      width: 300,
      // ellipsis: true,
      render: (__: any, record: any) => {
        const { id, isAllowApply, isBind, name, isReport, type } = record;
        const { cityIds } = featureCityIds?.find((v: any) => v.featureId === id) ?? {};
        return (
          <>
            <PermissionParentShow type="feature" id={id} appId={appId} data={record}>
              <Typography.Text ellipsis={{ tooltip: { placement: 'right' } }}>
                {isAllowApply == 0 && isBind == false
                  ? formatMessage({ id: 'component.PermissionParentShow.unapprovalapply' })
                  : name}
              </Typography.Text>
            </PermissionParentShow>
            &nbsp;&nbsp;
            {isReport === 1 && type === 3 && Array.isArray(cityIds) && Boolean(cityIds.length) && (
              <CityModal cityIds={cityIds?.map((k) => String(k))} view />
            )}
          </>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.funcList.sensitiveLevel" defaultMessage="敏感等级" />,
      dataIndex: 'dataSensitive',
      ellipsis: true,
      render: (__: any, record: any) => {
        return (
          <Text ellipsis={{ tooltip: true }}>
            {DataSensitiveLevelMap[record?.dataSensitive]?.text}
          </Text>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.funcList.sensitivity" defaultMessage="敏感度" />,
      dataIndex: 'sensitiveLevel',
      ellipsis: true,
      render: (__: any, record: any) => {
        return (
          <Text ellipsis={{ tooltip: true }}>{DataSensitiveMap[record.sensitiveLevel]?.text}</Text>
        );
      },
    },
    {
      title: <FormattedMessage id="pages.process.expiration" defaultMessage="有效期" />,
      dataIndex: 'expiredAt',
      ellipsis: true,
      render: (__: any, record: any) => {
        return record.hasOwnProperty('expiredAt') ? (
          <Text ellipsis={{ tooltip: true }}>
            {record.expiredAt == 0
              ? formatMessage({ id: 'pages.setting.base.defaultExpirationTime.forever' })
              : record.expiredAt < 0
              ? '-'
              : moment().valueOf() < record.expiredAt * 1000
              ? moment(record.expiredAt * 1000).format('YYYY-MM-DD HH:mm:ss')
              : `${moment(record.expiredAt * 1000).format('YYYY-MM-DD HH:mm:ss')}(${formatMessage({
                  id: 'base.expiredAted',
                })})`}
          </Text>
        ) : null;
      },
    },
    {
      title: (
        <div style={{ textAlign: 'center' }}>
          <FormattedMessage id="base.permission.operation" defaultMessage="操作" />
        </div>
      ),
      dataIndex: 'permissionOption',
      fixed: 'right',
      hidden: !isOptShow,
      render: (__: any, record: any) => [
        <>
          <Space>
            {record?.isBind ? (
              <Popconfirm
                key={`del${record.id}`}
                title={formatMessage({ id: 'pages.unbind.confirm' })}
                onConfirm={async () => {
                  try {
                    const allSettledPromise = requestBatchUnbind(
                      { featureTree: [record.id] },
                      currentUser,
                      appId,
                      formatMessage,
                    );
                    if (allSettledPromise) {
                      allSettledPromise.then(() => {
                        run();
                      });
                    }
                  } catch (error) {}
                }}
              >
                <a>
                  <FormattedMessage id="pages.unbind" />
                </a>
              </Popconfirm>
            ) : null}
            {record?.expiredAt < 0 || record?.isAllowApply === 0 || !record?.isBind ? null : (
              <a
                key={`renewal${record.id}`}
                onClick={() => {
                  setRenewalParams({ featureTree: [record.id] });
                  setOpenObj({ open: true, reload: false });
                }}
              >
                <FormattedMessage id="base.renewal" />
              </a>
            )}
          </Space>
        </>,
      ],
    },
  ];

  const dataSource = useMemo(() => {
    const list = filterFeatureTree ?? featureTree ?? [];
    if (!showSelected) return list;
    const leaf = tree2FlatArray(list)
      ?.filter((v: any) => v.isBind)
      .map((v: any) => v.id);
    return leafBuildTree(leaf, list);
  }, [featureTree, filterFeatureTree, showSelected]);

  if (!data?.featureTree?.length) return null;

  return (
    <div>
      {Boolean(isOptShow) && (
        <Space className={style.permission_name}>
          <label style={{ whiteSpace: 'nowrap' }}>
            {formatMessage({ id: 'page.process.permission.name' })}
          </label>
          <Input
            placeholder=""
            value={params?.featureTree}
            onChange={(val) => {
              setParams({ ...params, featureTree: val.target.value });
            }}
            style={{ width: 200 }}
          />
          <a
            style={{ whiteSpace: 'nowrap' }}
            onClick={() => {
              setExpandedAll({ ...expandedAll, featureTreeKey: true });
            }}
          >
            {formatMessage({ id: 'base.expandedall.true' })}
          </a>
          <a
            style={{ whiteSpace: 'nowrap' }}
            onClick={() => {
              setExpandedAll({ ...expandedAll, featureTreeKey: false });
            }}
          >
            {formatMessage({ id: 'base.expandedall.false' })}
          </a>
        </Space>
      )}

      <ConfigProvider
        theme={{
          token: {
            colorPrimary: '#F16622',
            colorLink: '#F16622',
          },
        }}
      >
        <Table
          rowKey={'id'}
          virtual
          scroll={{ y: 400 }}
          rowSelection={
            isOptShow
              ? {
                  columnWidth: 50,
                  selectedRowKeys: batchParams?.featureTree,
                  onChange: (rowKey) => {
                    setBatchParams((key) => {
                      return { ...key, featureTree: rowKey };
                    });
                  },
                  getCheckboxProps: (record: any) => ({
                    disabled:
                      record?.expiredAt < 0 || record?.isAllowApply === 0 || !record?.isBind,
                  }),
                }
              : {
                  columnWidth: 50,
                  hideSelectAll: true,
                  renderCell: (checked, record: any) => {
                    return <Checkbox disabled checked={record.isBind} />;
                  },
                }
          }
          columns={featureTreeColumn as any}
          pagination={false}
          expandable={{
            expandIcon: (p) => <ExpandIcon {...p} style={{ marginLeft: -14 }} />,
            expandedRowKeys: expandedAll?.featureTree ?? [],
            onExpand: (expanded, record) => {
              const temp = cloneDeep(expandedAll?.featureTree) ?? [];
              if (!expanded) {
                const arr = temp?.filter((key) => record.id !== key);
                setExpandedAll({ ...expandedAll, featureTree: arr });
              } else {
                temp?.push(record.id);
                setExpandedAll({ ...expandedAll, featureTree: temp });
              }
            },
          }}
          dataSource={dataSource}
        />
      </ConfigProvider>
    </div>
  );
};
export default memo(FeatureTable);
