import { useEffect, memo } from 'react';
import isEqual from 'lodash/isEqual';
import { getContainerData, filterResultUpdate } from 'models/data-container';
import { connect } from 'react-redux';
import { containersFilterResult } from 'utils/containers';
import { Filters } from 'models/filter.types';
import { isCloseAutoUpdateOnEasyDebugPage } from '@/utils/debug-screen';

let dataContainersInterval = 0;
const MAX_DELAY = 2147483;

function DataContainer({
  autoUpdate,
  edit = false,
  getContainerData,
  container,
  filters,
  filterResultUpdate,
  currentCallbackFilter,
  currentCallbackDataValues,
  data,
}: {
  autoUpdate: {
    isAuto: boolean;
    interval: number;
  };
  edit?: boolean;
  getContainerData: (id: number) => any;
  container: any;
  filters: Filters;
  filterResultUpdate: ({ id, data }) => any;
  currentCallbackFilter?: {
    [x: string]: any;
  };
  currentCallbackDataValues?: string | number[];
  data: any;
}) {
  const { id } = container;
  useEffect(() => {
    const clearDataContainersInterval = () => {
      dataContainersInterval && window.clearInterval(dataContainersInterval);
    };
    const setIntervalUpdate = () => {
      // 有组件在使用
      const { isAuto, interval } = autoUpdate || {};
      if (isAuto && interval) {
        dataContainersInterval = window.setInterval(() => {
          if (isCloseAutoUpdateOnEasyDebugPage()) return;
          getContainerData?.(id);
        }, (interval >= MAX_DELAY ? MAX_DELAY : interval) * 1000);
      }
    };
    !edit && setIntervalUpdate();
    return () => {
      clearDataContainersInterval();
    };
  }, [id]);

  useEffect(() => {
    if (id) {
      // 处理数据容器的数据
      const reasult = containersFilterResult({
        container: container,
        currentFilters: filters,
        callbackValues: currentCallbackFilter,
      });
      filterResultUpdate?.({
        id,
        data: reasult,
      });
    }
  }, [id, JSON.stringify(filters), data, JSON.stringify(currentCallbackFilter)]);

  useEffect(() => {
    if (container.dataType !== 'static' && !edit) {
      getContainerData?.(id);
    }
  }, [JSON.stringify(currentCallbackDataValues)]);

  return null;
}
function areEqual(props, nextProps) {
  return (
    isEqual(props.currentCallbackFilter, nextProps.currentCallbackFilter) &&
    isEqual(props.currentCallbackDataValues, nextProps.currentCallbackDataValues) &&
    isEqual(props.filters, nextProps.filters) &&
    isEqual(props.data, nextProps.data)
  );
}
export default connect(undefined, {
  getContainerData,
  filterResultUpdate,
})(memo(DataContainer, areEqual));
