import { getMonitorInfoTree } from '@/api/ems/base/baseMonitorInfo';
import type { VibrationBoardQuery } from '@/api/ems/types';
import { createDefaultTimeRange } from './vibrationBoardShared';

export function useVibrationBoardQueryState(defaultMetric = 'vibrationSpeed') {
  const state = reactive({
    loading: false,
    treeLoading: false,
    monitorTreeOptions: [] as any[],
    treeProps: { label: 'label', children: 'children' },
    deviceDisplayMap: {} as Record<string, string>,
    daterangeRecordTime: createDefaultTimeRange() as string[],
    queryForm: {
      compareScope: 'all',
      monitorId: '',
      monitorIds: [] as string[],
      selectionLabel: '全部振动设备',
      samplingInterval: 5,
      vibrationParam: defaultMetric,
      highThreshold: undefined as number | undefined,
      warningThreshold: undefined as number | undefined,
      minContinuousSamples: undefined as number | undefined,
      rapidRiseThreshold: undefined as number | undefined,
      stddevThreshold: undefined as number | undefined
    }
  });

  const { loading, treeLoading, monitorTreeOptions, treeProps, deviceDisplayMap, daterangeRecordTime, queryForm } = toRefs(state);
  const deviceCount = computed(() => queryForm.value.monitorIds?.length || (queryForm.value.monitorId ? 1 : 0));
  const hasMultiDevice = computed(() => deviceCount.value > 1 || ['group', 'all'].includes(queryForm.value.compareScope));

  const buildDeviceDisplayMap = (nodes: any[]): Record<string, string> =>
    (nodes || []).reduce(
      (acc, item) => {
        if (item.code && !item.children?.length) acc[item.code] = item.label;
        if (item.children?.length) Object.assign(acc, buildDeviceDisplayMap(item.children));
        return acc;
      },
      {} as Record<string, string>
    );

  const getLeafNodes = (nodes: any[]): any[] =>
    (nodes || []).flatMap((item) => (item.children?.length ? getLeafNodes(item.children) : item.code ? [item] : []));

  const buildSelection = (nodes: any[], selectionLabel: string, compareScope?: string) => {
    const monitorIds = nodes.map((item) => item.code);
    return {
      compareScope: compareScope || (monitorIds.length > 1 ? 'group' : 'single'),
      monitorId: monitorIds.length === 1 ? monitorIds[0] : '',
      monitorIds,
      selectionLabel
    };
  };

  const applySelection = (selection: any) => {
    Object.assign(queryForm.value, selection);
  };

  const setTimeRange = (value: string[]) => {
    daterangeRecordTime.value = value;
  };

  const setSamplingInterval = (value: number) => {
    queryForm.value.samplingInterval = value;
  };

  const setVibrationParam = (value: string) => {
    queryForm.value.vibrationParam = value;
  };

  const loadTree = async () => {
    treeLoading.value = true;
    try {
      const response = await getMonitorInfoTree({ monitorType: 10 });
      monitorTreeOptions.value = response.data || [];
      deviceDisplayMap.value = buildDeviceDisplayMap(monitorTreeOptions.value);
      if (!queryForm.value.monitorIds.length && !queryForm.value.monitorId) {
        applySelection(buildSelection(getLeafNodes(monitorTreeOptions.value), '全部振动设备', 'all'));
      }
    } finally {
      treeLoading.value = false;
    }
  };

  const handleTreeNodeClick = (data: any) => {
    if (!data) return;
    if (data.children?.length) {
      applySelection(buildSelection(getLeafNodes(data.children), `${data.label}设备组`, 'group'));
      return;
    }
    applySelection(buildSelection([data], data.label, 'single'));
  };

  const buildQuery = (): VibrationBoardQuery => ({
    samplingInterval: queryForm.value.samplingInterval,
    vibrationParam: queryForm.value.vibrationParam,
    beginRecordTime: daterangeRecordTime.value[0],
    endRecordTime: daterangeRecordTime.value[1],
    highThreshold: queryForm.value.highThreshold,
    warningThreshold: queryForm.value.warningThreshold,
    minContinuousSamples: queryForm.value.minContinuousSamples,
    rapidRiseThreshold: queryForm.value.rapidRiseThreshold,
    stddevThreshold: queryForm.value.stddevThreshold,
    monitorId: queryForm.value.monitorIds?.length > 1 ? undefined : queryForm.value.monitorIds?.[0] || queryForm.value.monitorId,
    monitorIds: queryForm.value.monitorIds?.length > 1 ? queryForm.value.monitorIds : undefined,
    params: {
      beginRecordTime: daterangeRecordTime.value[0],
      endRecordTime: daterangeRecordTime.value[1]
    }
  });

  const getMonitorDisplayName = (monitorId?: string) => (monitorId ? deviceDisplayMap.value[monitorId] || monitorId : '--');

  return {
    loading,
    treeLoading,
    monitorTreeOptions,
    treeProps,
    daterangeRecordTime,
    queryForm,
    deviceCount,
    hasMultiDevice,
    loadTree,
    handleTreeNodeClick,
    setTimeRange,
    setSamplingInterval,
    setVibrationParam,
    buildQuery,
    getMonitorDisplayName
  };
}
