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 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 OptionList {
  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 OptionListTable = (props: OptionList) => {
  const {
    isOptShow,
    DataSensitiveMap,
    DataSensitiveLevelMap,
    setOpenObj,
    params,
    setParams,
    setExpandedAll,
    expandedAll,
    formatMessage,
    moment,
    appId,
    setRenewalParams,
    currentUser,
    batchParams,
    setBatchParams,
    data,
    permission,
    run,
    showSelected,
  } = props;

  const optionListColumn = [
    {
      title: <FormattedMessage id="base.common.flag.permission" defaultMessage="数据权限" />,
      dataIndex: 'name',
      ellipsis: true,
      render: (__: any, record: any) => {
        return (
          <>
            {record?.Id ? (
              <Typography.Text ellipsis={{ tooltip: { placement: 'right' } }}>
                {record?.isAllowApply == 0 && record?.isBind == false
                  ? formatMessage({ id: 'component.PermissionParentShow.unapprovalapply' })
                  : record.name}
              </Typography.Text>
            ) : (
              <PermissionParentShow type="option" id={record.id} appId={appId} data={record}>
                <Typography.Text ellipsis={{ tooltip: { placement: 'right' } }}>
                  {record?.isAllowApply == 0 && record?.isBind == false
                    ? formatMessage({ id: 'component.PermissionParentShow.unapprovalapply' })
                    : record.name}
                </Typography.Text>
              </PermissionParentShow>
            )}
          </>
        );
      },
    },
    {
      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(
                      { optionList: [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({ optionList: [record.id] });
                  setOpenObj({ open: true, reload: false });
                }}
              >
                <FormattedMessage id="base.renewal" />
              </a>
            )}
          </Space>
        </>,
      ],
    },
  ];

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

  if (!data?.optionList?.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?.optionList}
            onChange={(val) => {
              setParams({ ...params, optionList: val.target.value });
            }}
            style={{ width: 200 }}
          />
          <a
            style={{ whiteSpace: 'nowrap' }}
            onClick={() => {
              setExpandedAll({ ...expandedAll, optionListKey: true });
            }}
          >
            {formatMessage({ id: 'base.expandedall.true' })}
          </a>
          <a
            style={{ whiteSpace: 'nowrap' }}
            onClick={() => {
              setExpandedAll({ ...expandedAll, optionListKey: 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?.optionList,
                  onChange: (rowKey) => {
                    setBatchParams((key) => {
                      return { ...key, optionList: 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={optionListColumn as any}
          pagination={false}
          expandable={{
            expandIcon: (p) => <ExpandIcon {...p} style={{ marginLeft: -14 }} />,
            expandedRowKeys: expandedAll?.optionList ?? [],
            onExpand: (expanded, record) => {
              const temp = cloneDeep(expandedAll?.optionList) ?? [];
              if (!expanded) {
                const arr = temp?.filter((key) => record.id !== key);
                setExpandedAll({ ...expandedAll, optionList: arr });
              } else {
                temp?.push(record.id);
                setExpandedAll({ ...expandedAll, optionList: temp });
              }
            },
          }}
          dataSource={dataSource}
        />
      </ConfigProvider>
    </div>
  );
};
export default memo(OptionListTable);
