import React, { useMemo, Fragment, useEffect } from 'react';
import { connect } from 'react-redux';
import { Checkbox } from '@easyv/react-gui';
import { getTopScreenId } from 'utils/screen';
import { getFiltersWithUsedComponents } from 'utils/filter';
import { isAppPage } from 'utils/utils';
import { getFilterScreenId } from 'models/create-app';
import UsedCondition from './UsedCondition';
import EasyvEmpty from 'components/EasyvEmpty';
import styles from './SelectList.less';

function SelectFilterList({
  filters,
  componentsById,
  selectFilterList,
  search = '',
  setSelectFilterList,
  setFiltersWithComponents,
}) {
  const isAppEdit = isAppPage();
  const filterScreenId = isAppEdit ? getFilterScreenId() : getTopScreenId();
  const filtersWithComponents = useMemo(() => {
    return getFiltersWithUsedComponents({
      filters: filters.filter((d) => d.screenId === filterScreenId),
      componentsById,
    });
  }, [filterScreenId, filters, componentsById]);

  useEffect(() => {
    setFiltersWithComponents(filtersWithComponents);
  }, [filtersWithComponents]);

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

  const onChange = (checkedValues) => {
    setSelectFilterList(checkedValues);
  };
  return (
    <Fragment>
      <Checkbox.Group style={{ width: '100%' }} value={selectFilterList} onChange={onChange}>
        {filtersWithComponents.length ? (
          filterList.length ? (
            filterList.map((d) => (
              <div className={styles.list} key={d.id}>
                <Checkbox style={{ padding: '8px 12px' }} value={d.id}>
                  <span style={{ color: '#fff' }}>{d.name}</span>
                </Checkbox>
                <div style={{ paddingRight: '12px', cursor: 'pointer' }}>
                  <UsedCondition usedComponents={d.usedComponents} />
                </div>
              </div>
            ))
          ) : (
            <EasyvEmpty className={styles.empty} description="无关键词匹配" />
          )
        ) : (
          <EasyvEmpty className={styles.empty} description="暂无过滤器" />
        )}
        {}
      </Checkbox.Group>
    </Fragment>
  );
}

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

export default connect(mapStateToProps)(SelectFilterList);
