import { filterData } from 'utils/convert';

export function getContainerWithUsedComponents({ id: containerId, componentsById = {} }) {
  const components: any[] = [];

  Object.keys(componentsById).forEach((id) => {
    const component = componentsById[id];
    const { parent, name, dataContainers = [] } = component;
    const componentInfo = {
      id: +id,
      name,
      parent,
    };
    if (dataContainers.map((d) => d.id).includes(containerId)) {
      components.push(componentInfo);
    }
  });
  return components;
}

export function containersFilterResult({ container, currentFilters, callbackValues = {} }) {
  if (typeof container === 'object' && Object.keys(container).length) {
    const { dataConfigs, dataType, useFilter } = container;
    const { data } = dataConfigs[dataType] || {};
    return useFilter
      ? filterData({
          data,
          filters: currentFilters,
          callbackValues,
          id: container?.id,
          name: container?.name,
        })
      : data;
  }
  return [];
}

export function getContainersFilterResult({ id, dataList, filterList, callbackValues = {} }) {
  if (Array.isArray(dataList) && +id) {
    const result = dataList.find((d) => d.id === +id);
    if (!result) {
      return;
    }
    const { filters } = result;

    const currentFilters = filters
      .filter((d) => d.enable)
      .map((d) => filterList.find((o) => o.id === d.id))
      .filter((d) => d);

    return containersFilterResult({
      container: result,
      currentFilters,
      callbackValues,
    });
  }

  return;
}

// 如果array 长度1 ，移除数组，反之原样扔出去
export function filterContainersResult(datas) {
  if (datas && Array.isArray(datas) && datas.length === 1) {
    return datas[0];
  }
  return datas;
}
