import React, { useMemo, Fragment } from 'react';
import { connect } from 'react-redux';
import FilterItem from './Item';
import { getTopScreenId } from 'utils/screen';
import { updateFilter, deleteFilter } from 'models/filter';
import { getFiltersWithUsedComponents } from 'utils/filter';
import EasyvEmpty from 'components/EasyvEmpty';
import { isAppPage } from 'utils/utils';
import { getFilterScreenId } from 'models/create-app';
import styles from './List.less';

function FilterList({ filters, componentsById, updateFilter, deleteFilter, search = '' }) {
  const isAppEdit = isAppPage();
  const filterScreenId = isAppEdit ? getFilterScreenId() : getTopScreenId();

  const filtersWithComponents = useMemo(() => {
    return getFiltersWithUsedComponents({
      filters: filters.filter((d) => d.screenId === filterScreenId),
      componentsById,
    });
  }, [filterScreenId, filters, componentsById]);

  const filterList = filtersWithComponents.filter((d) => d.name.includes(search));

  return (
    <Fragment>
      {filtersWithComponents.length ? (
        filterList.length ? (
          filterList.map((d) => (
            <FilterItem
              key={d.id}
              id={d.id}
              name={d.name}
              content={d.content}
              callbackKeys={d.callbackKeys}
              usedComponents={d.usedComponents || []}
              onSubmit={updateFilter}
              onDelete={deleteFilter}
            />
          ))
        ) : (
          <EasyvEmpty className={styles.empty} description="无关键词匹配" />
        )
      ) : (
        <EasyvEmpty className={styles.empty} description="暂无过滤器" />
      )}
    </Fragment>
  );
}

const mapStateToProps = ({ filters, componentsById }) => {
  return {
    filters: filters.list,
    componentsById,
  };
};

const mapDispatchToProps = {
  updateFilter,
  deleteFilter,
};

export default connect(mapStateToProps, mapDispatchToProps)(FilterList);
