import { useState, useEffect } from 'react';
import { apiGet } from '../utils/request';

interface RefreshConfigItem {
  id: number;
  code: string;
  name: string;
  value: string;
  type: string;
  defaultFlag: boolean;
  sort: number;
  createUser: string | null;
  createTime: string | null;
  updateUser: string | null;
  updateTime: string;
  deleteUser: string | null;
  deleteTime: string | null;
  delFlag: boolean;
}

export const useRefreshConfig = (moduleCode: string) => {
  const [refreshConfig, setRefreshConfig] = useState<RefreshConfigItem[]>([]);
  const [defaultFlag, setDefaultFlag] = useState<boolean | undefined>(undefined); // 初始值为undefined，避免过早请求
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchRefreshConfig = async () => {
      try {
        setLoading(true);
        
        // 测试模式：如果URL包含测试参数，直接返回测试值
        const urlParams = new URLSearchParams(window.location.search);
        const testFlag = urlParams.get(`test_${moduleCode}`);
        
        if (testFlag !== null) {
          const testValue = testFlag === 'true';
          setDefaultFlag(testValue);
          setLoading(false);
          return;
        }
        
        const response = await apiGet('/getDict', { params: { dictCode: 'refresh_rate' } });
        
        if (response.data && response.data.data && Array.isArray(response.data.data)) {
          setRefreshConfig(response.data.data);
          
          // 根据moduleCode查找对应的defaultFlag
          const targetConfig = response.data.data.find((item: RefreshConfigItem) => item.code === moduleCode);
          if (targetConfig) {
            setDefaultFlag(targetConfig.defaultFlag);
          } else {
            console.warn(`未找到模块 ${moduleCode} 的配置，使用默认值 true`);
            setDefaultFlag(true);
          }
        } else {
          console.warn('刷新配置接口返回格式不符合预期:', response.data);
          setDefaultFlag(true);
        }
      } catch (error) {
        console.error('获取刷新配置失败:', error);
        setDefaultFlag(true);
      } finally {
        setLoading(false);
      }
    };

    fetchRefreshConfig();
  }, [moduleCode]);

  return { defaultFlag, refreshConfig, loading };
}; 