/**
 * 业务组件容器
 */
import React, { useEffect, useState } from 'react';
import axios from 'axios';

const Container = (props: { component: any }) => {
  const [permissions, setPermissions] = useState<any>([]);
  const env = localStorage.getItem('env') || 'test';
  const token = localStorage.getItem('token');
  const apiDomain =
    (window as any).configs?.LOGTEXT?.[env]?.API_BASE_URL ||
    'https://test-gateway.ywwl.com';
  const headers = {
    'x-token': token,
  };

  useEffect(() => {
    getPermission();
  }, []);

  const getPermission = async () => {
    if (!window.location.pathname) return [];
    const res = await getCloudCategoryId();
    if (!res.success) return [];
    const { cloudCategoryId, moduleId } = res.data;
    const categoryData = await getCategoryData(cloudCategoryId);
    if (!res.success) return [];
    const currentModule = (categoryData?.data?.list || []).find(
      el => el.moduleId === moduleId,
    );
    const perm = (currentModule?.otherResourceList || []).map(el => el.url);
    setPermissions(perm);
  };

  const getCloudCategoryId = async () => {
    return fetchData(
      'get',
      `/ywwl-admin/desktop/module/info/query?resourceNameEn=${window.location.pathname}`,
    );
  };

  const getCategoryData = async cloudCategoryId => {
    return fetchData(
      'get',
      `/ywwl-admin/desktop/resource/list/cloud/modules?cloudCategoryId=${cloudCategoryId}`,
    );
  };

  const fetchData = async (
    type: 'get' | 'post',
    url: string,
    params?: any,
    config?: any,
  ) => {
    if (type === 'get') {
      try {
        const res = await axios.get(`${apiDomain}${url}`, { headers });
        if (res?.data?.success) {
          return res?.data;
        } else {
          throw res?.data;
        }
      } catch (e) {
        return { success: false };
      }
    } else if (type === 'post') {
      try {
        const res = await axios.post(`${apiDomain}${url}`, params);
        if (res?.data?.success) {
          return res?.data;
        } else {
          throw res?.data;
        }
      } catch (e) {
        return { success: false };
      }
    }
  };

  const defaultComponent = () => <div>Empty</div>;
  const Com = props.component || defaultComponent;
  return <Com state={{ permissions }} />;
};

export default Container;
