/**
 * 自定义 Hook：处理字段选项数据
 * 支持静态数据、动态API数据和预定义数据源
 */

import { useState, useEffect, useRef } from 'react';
import type { FieldConfig, FieldOption } from '../types';
import request from '../../../utils/request';
import { loadDataSource, DataSourceType as WorkflowDataSourceType } from '@/domain/dataSource';

/**
 * 从对象中根据路径提取数据
 * @param obj 对象
 * @param path 路径，如 'data' 或 'result.list'
 */
const getValueByPath = (obj: any, path?: string): any => {
  if (!path) return obj;
  
  const keys = path.split('.');
  let result = obj;
  
  for (const key of keys) {
    if (result && typeof result === 'object' && key in result) {
      result = result[key];
    } else {
      return undefined;
    }
  }
  
  return result;
};

export const useFieldOptions = (field: FieldConfig): FieldOption[] => {
  const [options, setOptions] = useState<FieldOption[]>([]);
  // 🔥 使用 useRef 存储加载状态，避免触发 useEffect
  const loadingStateRef = useRef<'idle' | 'loading' | 'success' | 'error'>('idle');
  const lastSourceKeyRef = useRef<string>('');

  useEffect(() => {
    const loadOptions = async () => {
      // 静态数据源
      if (field.dataSourceType === 'static' || !field.dataSourceType) {
        setOptions(field.options || []);
        loadingStateRef.current = 'success';
        return;
      }

      // 预定义数据源（使用 Workflow 中定义的数据源加载器）
      if (field.dataSourceType === 'predefined' && field.predefinedDataSource) {
        const { sourceType } = field.predefinedDataSource;
        
        if (!sourceType) {
          console.warn('⚠️ 预定义数据源配置不完整，缺少 sourceType');
          setOptions([]);
          loadingStateRef.current = 'error';
          return;
        }

        // 🔥 生成数据源唯一标识
        const sourceKey = `predefined_${sourceType}`;
        
        // 🔥 如果已经加载过这个数据源，不重复加载
        if (sourceKey === lastSourceKeyRef.current && (loadingStateRef.current === 'success' || loadingStateRef.current === 'error')) {
          return;
        }

        // 🔥 如果当前正在加载，不重复发起请求
        if (loadingStateRef.current === 'loading') {
          return;
        }

        loadingStateRef.current = 'loading';
        lastSourceKeyRef.current = sourceKey;

        try {
          // 调用 Workflow 的数据源加载器
          const dataSourceOptions = await loadDataSource(sourceType as WorkflowDataSourceType);
          
          // dataSourceLoader 已经转换为 { label, value } 格式
          setOptions(dataSourceOptions);
          loadingStateRef.current = 'success';
          console.log('✅ 预定义数据源加载成功', { sourceType, count: dataSourceOptions.length });
        } catch (error) {
          console.error('❌ 加载预定义数据源失败', { sourceType, error });
          setOptions([]);
          loadingStateRef.current = 'error'; // 🔥 标记为错误状态，不再重试
        }
        return;
      }

      // API 数据源
      if (field.dataSourceType === 'api' && field.apiDataSource) {
        const { url, method = 'GET', dataPath, labelField, valueField } = field.apiDataSource;

        // 验证必填字段（空字符串也视为缺失）
        if (!url || !url.trim() || !labelField || !labelField.trim() || !valueField || !valueField.trim()) {
          console.warn('⚠️ API 数据源配置不完整，缺少必填字段');
          setOptions([]);
          loadingStateRef.current = 'error';
          return;
        }

        // 🔥 生成 API 数据源唯一标识
        const sourceKey = `api_${url}_${method}_${labelField}_${valueField}`;
        
        // 🔥 如果已经加载过这个数据源，不重复加载
        if (sourceKey === lastSourceKeyRef.current && (loadingStateRef.current === 'success' || loadingStateRef.current === 'error')) {
          return;
        }

        // 🔥 如果当前正在加载，不重复发起请求
        if (loadingStateRef.current === 'loading') {
          return;
        }

        loadingStateRef.current = 'loading';
        lastSourceKeyRef.current = sourceKey;

        try {
          let response: any;
          
          // 根据请求方法调用接口
          if (method === 'POST') {
            response = await request.post(url, field.apiDataSource.params || {});
          } else {
            response = await request.get(url, { params: field.apiDataSource.params || {} });
          }

          // 根据 dataPath 提取数据数组
          let dataArray = dataPath ? getValueByPath(response, dataPath) : response;

          // 转换数据格式
          if (Array.isArray(dataArray)) {
            const transformedOptions: FieldOption[] = dataArray.map((item: any) => ({
              label: item[labelField],
              value: item[valueField],
            }));
            setOptions(transformedOptions);
            loadingStateRef.current = 'success';
            console.log('✅ API 数据加载成功', { url, count: transformedOptions.length });
          } else {
            console.error('❌ API 返回的数据格式不正确，期望数组');
            setOptions([]);
            loadingStateRef.current = 'error';
          }
        } catch (error) {
          console.error('❌ 加载 API 数据失败', { url, error });
          setOptions([]);
          loadingStateRef.current = 'error'; // 🔥 标记为错误状态，不再重试
        }
      }
    };

    loadOptions();
  }, [
    field.dataSourceType,
    field.options,
    field.predefinedDataSource?.sourceType, // 🔥 只依赖具体的值，而不是整个对象
    field.apiDataSource?.url,
    field.apiDataSource?.method,
    field.apiDataSource?.labelField,
    field.apiDataSource?.valueField,
  ]);

  return options;
};

