import * as React from 'react';
import { getCubePlatformMeta } from '../../../cn-ai-table/cube-platform/open-platform/get-cube-platform-meta';
import { fetchViewsFromCube, queryTableViews } from '../../../cn-ai-table/view/services';
/** 无 tableId 或接口异常时的占位，与 `ViewsData` 空结构一致 */
const EMPTY_VIEWS = { views: {}, viewOrder: [] };
/**
 * 视图配置数据源（低码与源码同一套分支）：
 * - 配 `viewConfig.queryViewsUrl`：`queryTableViews`
 * - 否则：`fetchViewsFromCube`（与 {@link getCubePlatformMeta} 可解析时一致，含低码侧传入 `cubePlatform`）
 *
 * @returns effectiveViewsConfigs — 交给 `DataModel.setAllViews` 的静态包；未就绪时为 `null`
 * @returns isLoadingViews — 已配业务 query URL 且首次请求未回时为 true，用于全屏 Loading
 */
export function useViewsConfigs(tableId, bizRequestConfig) {
    var _a;
    const bizRequestConfigRef = React.useRef(bizRequestConfig);
    bizRequestConfigRef.current = bizRequestConfig;
    const [bizUrlViews, setBizUrlViews] = React.useState(null);
    const [directCubeViews, setDirectCubeViews] = React.useState(null);
    const queryViewsUrl = (_a = bizRequestConfig === null || bizRequestConfig === void 0 ? void 0 : bizRequestConfig.viewConfig) === null || _a === void 0 ? void 0 : _a.queryViewsUrl;
    const effectiveViewsConfigs = queryViewsUrl ? bizUrlViews : directCubeViews;
    React.useEffect(() => {
        if (!queryViewsUrl) {
            return;
        }
        if (!tableId) {
            setBizUrlViews({ type: 'static', data: EMPTY_VIEWS });
            return;
        }
        let cancelled = false;
        (async () => {
            const data = await queryTableViews(tableId, bizRequestConfigRef.current);
            if (!cancelled) {
                setBizUrlViews({ type: 'static', data });
            }
        })();
        return () => {
            cancelled = true;
        };
    }, [queryViewsUrl, tableId]);
    React.useEffect(() => {
        if (queryViewsUrl) {
            return;
        }
        if (!tableId) {
            setDirectCubeViews({ type: 'static', data: EMPTY_VIEWS });
            return;
        }
        const biz = bizRequestConfigRef.current;
        if (!getCubePlatformMeta(tableId, biz)) {
            setDirectCubeViews({ type: 'static', data: EMPTY_VIEWS });
            return;
        }
        let cancelled = false;
        (async () => {
            const data = await fetchViewsFromCube(tableId, bizRequestConfigRef.current);
            if (!cancelled) {
                setDirectCubeViews({ type: 'static', data: data.views });
            }
        })();
        return () => {
            cancelled = true;
        };
        /** 须依赖完整 `bizRequestConfig`：`JSON.stringify(cubePlatform)` 会丢掉 `service` 等函数 */
    }, [queryViewsUrl, tableId, bizRequestConfig]);
    const isLoadingViews = Boolean(queryViewsUrl && bizUrlViews === null);
    return {
        effectiveViewsConfigs,
        isLoadingViews,
    };
}
