import { useEffect, useState } from 'react';
import Taro from '@tarojs/taro';
import { configWebsiteField } from '@/api/cms/cmsWebsiteField';
import { Config } from '@/api/cms/cmsWebsiteField/model';

/**
 * 自定义Hook用于获取和管理网站配置数据
 * @returns {Object} 包含配置数据和加载状态的对象
 */
export const useConfig = () => {
  const [config, setConfig] = useState<Config | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [error, setError] = useState<Error | null>(null);

  useEffect(() => {
    const fetchConfig = async () => {
      try {
        setLoading(true);
        const data = await configWebsiteField();
        setConfig(data);
        Taro.setStorageSync('config', data);

        // 设置主题
        if (data.theme && !Taro.getStorageSync('user_theme')) {
          Taro.setStorageSync('user_theme', data.theme);
        }
        // 自定义接口
        if(data.apiUrl && process.env.NODE_ENV !== 'development'){
          Taro.setStorageSync('ApiUrl', data.apiUrl)
        }
      } catch (err) {
        setError(err instanceof Error ? err : new Error('获取配置失败'));
        console.error('获取网站配置失败:', err);
      } finally {
        setLoading(false);
      }
    };

    fetchConfig();
  }, []);

  return { config, loading, error, refetch: () => {
    setLoading(true);
    setError(null);
    configWebsiteField().then(data => {
      setConfig(data);
      Taro.setStorageSync('config', data);

      setLoading(false);
    }).catch(err => {
      setError(err instanceof Error ? err : new Error('获取配置失败'));
      setLoading(false);
    });
  }};
};
