import React, { memo } from 'react';
import EasyvEmpty from '@/components/EasyvEmpty';
import { Switch } from '@easyv/antd';
import { Select } from '@easyv/react-gui';
import styles from './filter.less';
import {
  addComponentFilter,
  triggerComponentFilter,
  updateComponentDataConfig,
} from '@/models/component';
import FilterList from './FilterList';
import { connect } from 'react-redux';
import { ComponentItem } from '@/models/component.types';
import isEqual from 'lodash/isEqual';
import { getFilterScreenId } from '@/models/create-app';
import { isAppPage } from '@/utils/utils';
import { getTopScreenId } from '@/utils/screen';

const { Option } = Select;

const Filter = ({
  useFilter,
  usedFilters,
  addFilter,
  componentId,
  onClick,
  addComponentFilter,
  updateComponentDataConfig,
  triggerComponentFilter,
  filters,
}) => {
  const isAppEdit = isAppPage();
  const topScreenId = getTopScreenId();
  const leaveFilterOptions = filters
    .filter((d) => !usedFilters.find((o) => o.id === d.id))
    .filter((d) => d && d.screenId === (isAppEdit ? getFilterScreenId() : topScreenId));
  
  const activeFilterOptions = usedFilters
    .reduce((pre, cur) => {
      const findItem = filters.find((f) => f.id === cur.id);
      if (findItem) {
        return [...pre, { ...findItem, enable: cur.enable }];
      }
      return pre;
    }, [])
    .filter((d) => (isAppEdit ? true : d.screenId === topScreenId));

  return (
    <div className={styles.dataSourceContainer}>
      <div className={styles.filter}>
        <span>
          <span style={{ marginRight: 8 }}>数据过滤器</span>
          <Switch
            size="small"
            checked={useFilter}
            onChange={(e) => updateComponentDataConfig({ useFilter: e, id: componentId })}
          />
        </span>
        {usedFilters.length > 0 ? (
          <span className={styles.tip}>
            已添加
            <i
              style={{
                fontStyle: 'normal',
                color: '#2491F7',
              }}>
              {usedFilters.length}
            </i>
            个过滤器
          </span>
        ) : (
          <span>当前未添加过滤器</span>
        )}
      </div>
      <div className={styles.filterSelect}>
        <Select
          showSearch
          notFoundContent={
            <div style={{ margin: '40px 0' }}>
              <EasyvEmpty />
            </div>
          }
          value="请选择过滤器"
          optionFilterProp="title"
          onChange={(value) => {
            addComponentFilter({ id: componentId, filterId: value });
          }}
          placeholder="请选择过滤器">
          {leaveFilterOptions.map((e: any) => {
            return (
              <Option key={e.id} title={e.name} value={e.id}>
                {e.name}
              </Option>
            );
          })}
        </Select>
        <div className={styles.addIcon} onClick={addFilter}>
          <i className="icon iconfont icon-icon_add"></i>
        </div>
      </div>
      <FilterList
        data={activeFilterOptions || []}
        onClick={onClick}
        onChange={(event, cur) => {
          triggerComponentFilter({
            id: componentId,
            filterId: cur.id,
            enable: event.target.checked,
          });
        }}
      />
    </div>
  );
};

const mapStateToProps = ({ componentsById, createApp, filters }) => {
  const { componentsChildSelected, layersSelected } = createApp;
  const componentId = componentsChildSelected || layersSelected[0];
  const current = componentsById[componentId] as ComponentItem;

  return {
    useFilter: current.useFilter, // TODO过滤器开关
    usedFilters: current.filters || [],
    componentId: componentId,
    filters: filters.list || [],
  };
};

const mapDispatchToProps = {
  addComponentFilter,
  updateComponentDataConfig,
  triggerComponentFilter,
};

function areEqual(props, nextProps) {
  return (
    isEqual(props.useFilter, nextProps.useFilter) &&
    isEqual(props.usedFilters, nextProps.usedFilters) &&
    isEqual(props.componentId, nextProps.componentId) &&
    isEqual(props.filters, nextProps.filters)
  );
}
export default connect(mapStateToProps, mapDispatchToProps)(memo(Filter, areEqual));
