import React, { useEffect } from 'react';
import { embedDashboard } from '@superset-ui/embedded-sdk';
import './style.less';

function MyEmbeddedDashboard() {
  // 从 URL 中获取仪表板 ID
  const paths = window.location.pathname.split('/').filter((item) => item);
  const dashboardId = paths[paths.length - 1];
  const host = window.location.hostname;

  // 封装获取 Guest Token 的异步函数
  const getGuestToken = async () => {
    try {
      // 1. 登录，获取 access_token
      const loginResponse = await fetch(`http://${host}:8088/api/v1/security/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: 'kcim',
          password: 'kcim123456',
          provider: 'db', 
          refresh: true,
        }),
      });

      const loginData = await loginResponse.json();
      const accessToken = loginData?.access_token;
      if (!accessToken) {
        throw new Error('登录失败，未获取到 access_token');
      }

      // 2. 使用 access_token 调用 /api/v1/security/guest_token/ 获取 Guest Token
      const guestTokenResponse = await fetch(`http://${host}:8088/api/v1/security/guest_token/`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          // 将 access_token 作为 Bearer Token
          Authorization: `Bearer ${accessToken}`,
        },
        body: JSON.stringify({
          user: {
            username: 'guest_user',
            first_name: 'Guest',
            last_name: 'User',
            email: 'guest@example.com',
          },
          resources: [
            {
              type: 'dashboard',
              id: dashboardId, // 使用从地址栏获取到的 dashboardId
            },
          ],
          rls: [],
        }),
      });

      const guestTokenData = await guestTokenResponse.json();
      const guestToken = guestTokenData?.token;
      if (!guestToken) {
        throw new Error('获取 Guest Token 失败');
      }

      // 返回最终需要的 Guest Token
      return guestToken;
    } catch (error) {
      console.error(error);
      // 如果获取失败，可根据需求返回一个空字符串或抛出异常
      return '';
    }
  };

  useEffect(() => {
    // 当 dashboardId 存在时，嵌入仪表板
    if (dashboardId) {
      embedDashboard({
        id: dashboardId,
        supersetDomain: `http://${host}:8088`, 
        mountPoint: document.getElementById('dashboard-container') as HTMLElement,
        dashboardUiConfig: {
          hideTitle: true,
          filters: {
            expanded: true,
          },
        },
        // 调用上面封装的 getGuestToken 函数
        fetchGuestToken: async () => {
          const token = await getGuestToken();
          return token;
        },
        iframeSandboxExtras: ['allow-top-navigation', 'allow-popups-to-escape-sandbox'],
      });
    }
  }, [dashboardId]);

  return (
    <div className="my-embedded-dashboard">
      <div className="dashboard" id="dashboard-container"  />
    </div>
  );
}

export default MyEmbeddedDashboard;
