import { computed, ref } from 'vue';
import { getShopSpaceList, getCamerasByWorkShopId } from '@/api/scene/scene';
import { CompanyInfoItem } from '@/types/scene/type.ts';
type ElTreeItem = {
  value: any;
  label: string;
  children?: ElTreeItem[];
};

type TreeProps = {
  /** level：1-数据读取至公司 2-数据读取至工厂 3-数据读取至工位 */
  level: number;
  labelKey: string;
  valueKey: string;
  disabled?: boolean;
};

export function useSceneInfos() {
  const scenesInfos = ref<CompanyInfoItem[]>([]);
  const scenesTree = ref<ElTreeItem[]>([]);

  const flattenedWorkshops = computed(() => {
    return scenesInfos.value.reduce((total, next) => [...total, ...next.children], []);
  });

  const flattendWorkspaces = computed(() => {
    return scenesInfos.value.reduce((total, next) => {
      let newArr: any[] = [];
      if (next.children && next.children.length) {
        newArr = next.children.reduce(
          (subTotal, subNext) => [...subTotal, ...subNext.children],
          [],
        );
      }
      return [...total, ...newArr];
    }, []);
  });

  const calculateTreeData = (infos: any[], treeProps: TreeProps, level: number): ElTreeItem[] => {
    return infos.map((data) => {
      return {
        value: data[treeProps.valueKey],
        label: data[treeProps.labelKey],
        children:
          data.children && data.children.length && treeProps.level > level
            ? calculateTreeData(data.children, treeProps, level + 1)
            : [],
        disabled: treeProps.disabled && level < treeProps.level,
      };
    });
  };

  const getScenesTree = (treeProps: TreeProps) => {
    getShopSpaceList().then((res) => {
      scenesInfos.value = res;
      scenesTree.value = calculateTreeData(res, treeProps, 1);
    });
  };

  return {
    scenesInfos,
    scenesTree,
    flattenedWorkshops,
    flattendWorkspaces,
    getScenesTree,
    calculateTreeData,
  };
}

export default useSceneInfos;
