import React, { useEffect, useMemo, useState } from "react";
import { Modal } from 'antd';
import JsonView from 'react-json-view';

interface IProps {
  info: any;
  onCancel: () => void;
}
export const getColumnProperty = (columns: any[], columnName: string) => {
  const column = columns.filter((item) => item.name === columnName)[0];
  return column ?? {};
}
const PropertyModal: React.FC<IProps> = (props: IProps) => {
  const { info, onCancel } = props;
  const [visible, setVisible] = useState(false);
  useEffect(() => {
    const hasInfo = info && Object.keys(info)?.length;
    setVisible(hasInfo);
  }, [info]);

  const handleLoopGetData: (item: any) => any[] = (item) => {
    const treeData = [];
    for (const key in item) {
      const value = item[key];
      const type = typeof value;
      if (type === 'object' && value !== null) {
        treeData.push({
          title: key,
          key: key + '_' + Math.random(),
          children: handleLoopGetData(value)
        });
      } else {
        treeData.push({
          key: key + '_' + Math.random(),
          title: <span>{key}: <span style={{ backgroundColor: '#f1f1f1' }}>{type === 'function' ? 'function' : JSON.stringify(value)}</span></span>
        });
      }
    }
    return treeData;
  }

  const parsedJSON = useMemo(() => {
    try {
      return JSON.parse(info);
    } catch (e) {
      return info;
    }
  }, [info]);
  return (
    visible ? <Modal
      title={'当前字段：' + (info?.label || '属性')}
      style={{
        top: 10
      }}
      visible={visible}
      onCancel={onCancel}
      footer={null}
    >
      <div style={{ maxHeight: '80vh', overflow: 'auto' }}>
        <JsonView
          name={false}
          src={parsedJSON}
          theme='rjv-default'
          enableClipboard={false}
          iconStyle="square"
        />
      </div>
    </Modal> : null
  )
}

export default PropertyModal;
