import { DownOutlined } from '@ant-design/icons';
import { Descriptions, Spin, Tooltip, Tree, Typography } from 'antd';
import _, { isUndefined } from 'lodash';
import type { ReactNode } from 'react';
import React, { useEffect, useMemo, useState } from 'react';
import { FormattedMessage, useIntl, useRequest } from 'umi';
import { formatUserRender } from '../utils';
import publicConst from '../utils/const';
import './index.less';

const { Text } = Typography;

const formartTreeData = (data: any[], showApply: any) => {
  let result: any;
  let child: any;

  data?.forEach((item, i) => {
    if (!item) return;
    const { id, name, isAllowApply } = item;
    if (!result) {
      result = {
        title:
          showApply || isAllowApply ? (
            <Text ellipsis style={{ color: 'white', width: 398 - i * 24 }}>
              {name}
            </Text>
          ) : (
            <Text className="not-allow-apply" ellipsis style={{ width: 398 - i * 24 }}>
              <FormattedMessage id="component.PermissionParentShow.unapprovalapply" />
            </Text>
          ),
        key: id,
        children: [],
      };
      child = result;
    } else {
      const children = {
        title:
          showApply || isAllowApply ? (
            <Text ellipsis style={{ color: 'white', width: 398 - i * 24 }}>
              {name}
            </Text>
          ) : (
            <Text className="not-allow-apply" ellipsis style={{ width: 398 - i * 24 }}>
              <FormattedMessage id="component.PermissionParentShow.unapprovalapply" />
            </Text>
          ),
        key: id,
        children: [],
      };
      child.children = [children];
      child = children;
    }
  });

  return result ? [result] : [];
};

export type PermissionParentDataType = {
  name?: string;
  uniqueKey?: string;
  id?: number;
  nameZh?: string;
  nameEn?: string;
  ownerName?: string;
  ownerId?: number;
  ownerAccount?: string;
  ownerState?: number;
  userState?: number;
  remark?: string;
  dataSensitive?: number;
  sensitiveLevel?: number;
  isAllowApply?: any;
};

export type PermissionParentShowProps = {
  type?: 'feature' | 'option';
  id?: number;
  name?: string | ReactNode;
  appId?: number;
  uniqueKey?: string;
  showApply?: boolean;
  children: React.ReactNode;
  data?: PermissionParentDataType;
};

const PermissionParentShow = (props: PermissionParentShowProps) => {
  const { type, id, name, showApply = false, appId, uniqueKey, children, data: itemData } = props;

  const [open, setOpen] = useState(false);
  const { formatMessage } = useIntl();

  const { DataSensitive, DataSensitiveLevel } = publicConst(formatMessage);

  const { loading, data, run } = useRequest(
    (pId, pAppId, pUniqueKey) => ({
      url: `/goapi/${type}/path`,
      method: 'POST',
      data: { id: pId, appId: pAppId, uniqueKey: pUniqueKey },
    }),
    {
      manual: true,
    },
  );

  const detailRender = (node: ReactNode, item?: PermissionParentDataType) => (
    <Descriptions className="permission-parent-show" column={1}>
      {Boolean(id) && (
        <Descriptions.Item label={<FormattedMessage id="component.PermissionParentShow.parent" />}>
          {node}
        </Descriptions.Item>
      )}
      <Descriptions.Item label={<FormattedMessage id="component.PermissionParentShow.creator" />}>
        {formatUserRender({
          name: item?.ownerName || item?.nameZh,
          id: item?.ownerId,
          account: item?.ownerAccount || item?.nameEn,
          state: !_.isUndefined(item?.ownerState) ? item?.ownerState : item?.userState,
        })}
      </Descriptions.Item>
      {item?.uniqueKey && (
        <Descriptions.Item
          label={<FormattedMessage id="component.PermissionParentShow.uniqueKey" />}
        >
          {item?.uniqueKey}
        </Descriptions.Item>
      )}
      {!isUndefined(item?.sensitiveLevel) && (
        <Descriptions.Item
          label={<FormattedMessage id="component.PermissionParentShow.sensitivityLevel" />}
        >
          {DataSensitiveLevel.find((v) => v.value === item?.dataSensitive)?.label}
        </Descriptions.Item>
      )}
      {!isUndefined(item?.dataSensitive) && (
        <Descriptions.Item
          label={<FormattedMessage id="component.PermissionParentShow.sensitivity" />}
        >
          {DataSensitive.find((v) => v.value === item?.sensitiveLevel)?.label}
        </Descriptions.Item>
      )}
      <Descriptions.Item label={<FormattedMessage id="component.PermissionParentShow.remark" />}>
        {item?.remark}
      </Descriptions.Item>
    </Descriptions>
  );

  const treeData = useMemo(() => _.reverse(data || []), [data]);

  useEffect(() => {
    if (open && id) {
      run(id, appId, uniqueKey);
    }
  }, [id, appId, uniqueKey, run, open]);

  return (
    <Tooltip
      overlayStyle={{ maxWidth: 500 }}
      onOpenChange={(val) => setOpen(val)}
      title={detailRender(
        loading ? (
          <Spin size="small" />
        ) : (
          <Tree
            className="permission-parent-show"
            showLine
            switcherIcon={<DownOutlined />}
            disabled
            blockNode
            selectable={false}
            treeData={formartTreeData(
              [
                ...treeData,
                {
                  id,
                  name: name || uniqueKey || itemData?.name || itemData?.uniqueKey,
                  isAllowApply:
                    itemData?.isAllowApply === '' || _.isUndefined(itemData?.isAllowApply)
                      ? 1
                      : itemData?.isAllowApply,
                },
              ],
              showApply,
            )}
            expandedKeys={data?.map((item: any) => item.id)}
          />
        ),
        itemData,
      )}
    >
      {children}
    </Tooltip>
  );
};

export default PermissionParentShow;
