import * as React from 'react';
import { getCubePlatformMeta } from '../../../cn-ai-table/cube-platform/open-platform/get-cube-platform-meta';
import { fetchViewsFromCube } from '../../../cn-ai-table/view/services';
/** 无 tableId 或接口异常时的占位，与 `ViewsData` 空结构一致 */
const EMPTY_VIEWS = { views: {}, viewOrder: [] };
/**
 * 视图配置数据源（低码与源码同一套分支）：
 * - 通过 `cubePlatform` 配置覆盖 URL（业务侧）或走默认魔方地址
 * - 统一走 `fetchViewsFromCube`（与 {@link getCubePlatformMeta} 可解析时一致）
 *
 * @returns effectiveViewsConfigs — 交给 `DataModel.setAllViews` 的静态包；未就绪时为 `null`
 * @returns isLoadingViews — 首次请求未回时为 true，用于全屏 Loading
 */
export function useViewsConfigs(tableId, bizRequestConfig) {
    const bizRequestConfigRef = React.useRef(bizRequestConfig);
    bizRequestConfigRef.current = bizRequestConfig;
    const [cubeViews, setCubeViews] = React.useState(null);
    React.useEffect(() => {
        if (!tableId) {
            setCubeViews({ type: 'static', data: EMPTY_VIEWS });
            return;
        }
        const biz = bizRequestConfigRef.current;
        if (!getCubePlatformMeta(tableId, biz)) {
            setCubeViews({ type: 'static', data: EMPTY_VIEWS });
            return;
        }
        let cancelled = false;
        (async () => {
            const data = await fetchViewsFromCube(tableId, bizRequestConfigRef.current);
            if (!cancelled) {
                setCubeViews({ type: 'static', data: data.views });
            }
        })();
        return () => {
            cancelled = true;
        };
    }, [tableId, bizRequestConfig]);
    const isLoadingViews = cubeViews === null;
    return {
        effectiveViewsConfigs: cubeViews,
        isLoadingViews,
    };
}
