import { EasyTreeSelect, ConfigProvider } from '@easyv/react-gui';
import { RootState } from '@/models';
import { ComponentsById } from '@/models/component.types';
import { PanelsById } from '@/models/panel.types';
import { ScreensById } from '@/models/screen.types';
import { getAllFlattenedSubScreenIds, getTopScreenId } from '@/utils/screen';
import isEqual from 'lodash/isEqual';
import React, { memo, useMemo } from 'react';
import { connect } from 'react-redux';
import styles from './log-search-input.less';
import emptyImg from '../../../../images/icon_upload.svg';
import { Empty } from '@easyv/antd';

interface LogSearchInputProps {
  onSearch: (v: number[]) => void;
  screensById: ScreensById;
  panelsById: PanelsById;
  componentsById: ComponentsById;
}

const LogSearchInput = memo(
  (props: LogSearchInputProps) => {
    const { onSearch, screensById, panelsById, componentsById } = props;
    const ids = useMemo(() => {
      return getAllFlattenedSubScreenIds(
        getTopScreenId(),
        screensById,
        panelsById,
        Object.keys(screensById || {})
          .map((d) => Number(d))
          .filter((d) => d !== getTopScreenId()),
      );
    }, [screensById, panelsById]).concat(getTopScreenId());

    const curScreenAllComponents = useMemo(() => {
      return Object.values(componentsById || {})
        .filter((d) => ids.includes(d.screenId))
        .map((d) => ({ value: d.id, title: d.name, key: d.id }));
    }, [ids]);

    return (
      <div className={styles.contentSearch}>
        <ConfigProvider
          renderEmpty={() => (
            <Empty
              image={emptyImg}
              imageStyle={{ height: 40 }}
              description={<span style={{ color: '#757881' }}>未找到相关内容</span>}
            />
          )}>
          <EasyTreeSelect
            placeholder="请输入组件名称或ID筛选相关日志"
            treeCheckable={true}
            allowClear
            showSearch={true}
            style={{ width: '100%' }}
            treeData={curScreenAllComponents}
            onChange={(v) => {
              onSearch(v);
            }}
            filterTreeNode={(inputValue, treeNode) => {
              return (
                `${treeNode.title}`.indexOf(inputValue) > -1 ||
                `${treeNode.value}`.indexOf(inputValue) > -1
              );
            }}
          />
        </ConfigProvider>
      </div>
    );
  },
  (props, nextProps) => {
    return (
      isEqual(props.screensById, nextProps.screensById) &&
      isEqual(props.panelsById, nextProps.panelsById) &&
      isEqual(props.componentsById, nextProps.componentsById)
    );
  },
);

const mapStateToProps = ({ screensById, panelsById, componentsById }: RootState) => {
  return {
    screensById,
    panelsById,
    componentsById,
  };
};

export default connect(mapStateToProps)(LogSearchInput);
