/*
 * @Author: your name
 * @Date: 2022-01-06 15:25:39
 * @LastEditTime: 2023-10-24 16:55:59
 * @LastEditors: code4eat awesomedema@gmail.com
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /KC-MiddlePlatform/src/pages/platform/_layout.tsx
 */

import { IRouteComponentProps, useModel, Helmet } from 'umi';
// import { CrownOutlined, UserOutlined, SmileOutlined } from '@ant-design/icons';
import ProLayout, { PageContainer } from '@ant-design/pro-layout';
import { getPlatformMenu, getSpecifyMenuDetail } from '@/service/menu';
import './index.less';
import { TreeItemType } from '@/utils';
import { SpacicalPageParamsType } from '@/typings';
import { Key, useEffect, useState } from 'react';

import Icon, { FileOutlined, FolderOutlined, createFromIconfontCN } from '@ant-design/icons';
import { getAllParams } from '@/service';

import '../../../public/zhongtaiC'

const IconFont = createFromIconfontCN({
  scriptUrl: '',
});

export default function Layout({ children, location, route, history, match, ...rest }: IRouteComponentProps) {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [openKeys, set_openKeys] = useState<string[]>([]);
  const [selectedKeys, set_selectedKeys] = useState<string[]>([]);
  const [emptyPageContent, set_emptyPageContent] = useState('');
  const [isShowPageMenu, set_isShowPageMenu] = useState(true);
  const [isEmpty, set_isEmpty] = useState(false);

  const [collapsed,set_collapsed] = useState(false);

  const [pageUrl, set_pageUrl] = useState<string | undefined>(undefined);
  
  const { pathname } = location;

  const setEmptyPageContent = async (menuId: Key) => {
    const menuItem = await getSpecifyMenuDetail(menuId);
    if (menuItem.isSetupMenu) {
      set_isShowPageMenu(false);
    }
    set_emptyPageContent(menuItem.description);
  }

  useEffect(() => {

    const isShowMenu = localStorage.getItem('isChildShowMenu');
    set_isShowPageMenu(isShowMenu == 'true')
  });

  useEffect(() => {

    if (location.query.menuId) {
      setEmptyPageContent(location.query.menuId as string);
    }
    set_isEmpty(location.query.isEmpty == 'true');
  }, [location]);

  useEffect(() => {
    const handleResize = () => {
      if (window.innerWidth <= 1280) {  // 自定义触发宽度为 800px
        set_collapsed(true);
      } else {
        set_collapsed(false);
      }
    };

    // 初始化
    handleResize();

    // 监听窗口大小变化
    window.addEventListener('resize', handleResize);

    // 清除监听器
    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);


  const adjustIframe = () => {
    // var ifm:any = document.getElementById("bi_iframe");
    // if(ifm){
    //   ifm.height=document.documentElement.clientHeight;
    //   ifm.width=document.documentElement.clientWidth;
    // }
  }



  if(initialState?.currentSelectedSys){
      const {type,url,contentType} = initialState.currentSelectedSys;
      if(type == 1&&contentType == 6){
        return (
          <iframe id={'bi_iframe'} style={{ width: '100%', height: '100%', border: 'none' }} src={url} onLoad={() => adjustIframe()} ></iframe>
        )
      }
  }

  //临时演示处理
  
  if (location.pathname == '/platform/costMana') {

    //临时解决未嵌入成本核算，而实现访问的效果

    const getToken = async () => {
      const resp = await getAllParams();

      if (resp) {
        const needItem = resp.filter((a: any) => a.code == '1647777324889935872');

        if (needItem.length > 0) {
          set_pageUrl(`http://47.96.149.190:8000/platformMana/roleManage?hospSign=dOBHdoPmJgPGnMSH&token=${needItem[0].value}`)
        }
      }
    }

    getToken();

    return (
      <>
        {pageUrl && <iframe id={'bi_iframe'} style={{ width: '100%', height: '100%', border: 'none' }} src={pageUrl} onLoad={() => adjustIframe()} ></iframe>};
      </>
    )
  }

  if (location.pathname == '/platform/Budget') {

    const pageUrl = `https://test.baokangyiguan.com/index/apiLogin?username=admin&url=budget/index`;

    return (
      <>
        {pageUrl && <iframe id={'bi_iframe'} style={{ width: '100%', height: '100%', border: 'none' }} src={pageUrl} onLoad={() => adjustIframe()} ></iframe>};
      </>
    )
  }

  if (location.pathname == '/platform/DRG') {

    const pageUrl = `https://test.baokangyiguan.com/index/apiLogin?username=admin&url=drgs/index`;

    return (
      <>
        {pageUrl && <iframe id={'bi_iframe'} style={{ width: '100%', height: '100%', border: 'none' }} src={pageUrl} onLoad={() => adjustIframe()} ></iframe>};
      </>
    )
  }

  if (location.pathname == '/platform/DIP') {

    const pageUrl = `https://test.baokangyiguan.com/index/apiLogin?username=admin&url=dips/index`;

    return (
      <>
        {pageUrl && <iframe id={'bi_iframe'} style={{ width: '100%', height: '100%', border: 'none' }} src={pageUrl} onLoad={() => adjustIframe()} ></iframe>};
      </>
    )
  }
  
  if (location.pathname == '/platform/baokangCostApp') {

    const pageUrl = `https://test.baokangyiguan.com/index/apiLogin?username=admin&url=cost/index `;

    return (
      <>
        {pageUrl && <iframe id={'bi_iframe'} style={{ width: '100%', height: '100%', border: 'none' }} src={pageUrl} onLoad={() => adjustIframe()} ></iframe>};
      </>
    )
  }



  return (
    <ProLayout
      style={{
        height: 'calc(100vh - 50px)',
      }}
      //iconfontUrl="//at.alicdn.com/t/font_8d5l8fzk5b87iudi.js"
      logoStyle={{
        display: 'none',
      }}
      location={{
           
      }}
      headerContentRender={false}
      headerRender={false}
      siderWidth={isShowPageMenu ? 200 : 0}
      breakpoint={false}
      pageTitleRender={false}
      disableContentMargin
      collapsed={collapsed}
      onCollapse={collapsed=>set_collapsed(collapsed)}
      collapsedButtonRender={() => {
        return (
          <div className='collapsedBtn' onClick={
            () => {
              set_collapsed(collapsed ? false : true)
            }
          }><IconFont style={{display:'inline-block'}} className='menuCollapseIcon' type={collapsed ? 'icon-celanzhankai' : 'icon-celanshouqi'} /></div>
        )
      }}
      menuItemRender={(item, dom) => {
        return (
          <a
            onClick={() => {
              history.push(`${item.path}${item.contentType == '4' ? `?isEmpty=true&menuId=${item.key}` : ''}` || '/');
            }}
          >
            {dom}
          </a>
        )
      }}
      menuProps={{
        openKeys: [...openKeys],
        selectedKeys: [...selectedKeys],
        onSelect: ({ key, keyPath, selectedKeys, domEvent }) => {
          set_selectedKeys(selectedKeys);
          localStorage.setItem('selectedKeys', JSON.stringify(selectedKeys));
        },
        onOpenChange: (keys: string[]) => {
          set_openKeys([...keys]);
          localStorage.setItem('openKeys', JSON.stringify(keys));
        },
      }}
      menu={{
        autoClose: false,
        params: {
          initialState
        },
        request: async () => {

          if (initialState && initialState.currentSelectedSys) {
            const { systemId, menuId, path } = initialState.currentSelectedSys;
            if (systemId || menuId) {
              //只有当存在systemId
              const menuData = await getPlatformMenu(systemId || menuId);
              let homePage: TreeItemType | undefined;

              const getVFromTree = (data: TreeItemType[], key: string) => {
                let result: SpacicalPageParamsType[] = [];
                function looper(data: TreeItemType[], key: string) {
                  data.forEach((t) => {
                    if (t.isHomepage) {
                      homePage = t;
                    }
                    if (t[key] == 1 || t[key] == 2 || t[key] == 3) {
                      //网易有数页面
                      result.push({
                        contentType: t[key],
                        path: t['path'],
                        reportId: t['reportId'],
                        url: t['youshuUrl'],
                      });
                    }
                    if (t[key] == 5) {
                      //蓝湖静态展示页面
                      result.push({
                        contentType: t[key],
                        path: t['path'],
                        reportId: t['reportId'],
                        url: t['softUrl'],
                      });
                    }
                    if (t.children && t.children.length > 0) {
                      looper(t.children, key);
                    }
                  });
                }
                looper(data, key);
                return result;
              };


              const _menu = getVFromTree(menuData, 'contentType');
              setInitialState((t) => ({ ...t, spacicalPageParamsType: _menu }));

              if (homePage) {
                // console.log({homePage});
                set_openKeys([homePage.key]);
                set_selectedKeys([homePage.key]);
                history.push(homePage.path);

              } else {

                if (path == '/platform') {

                  const selectedKeys = localStorage.getItem('selectedKeys');
                  const openKeys = localStorage.getItem('openKeys');

                  if (selectedKeys && openKeys) {
                    const _selectedKeys = JSON.parse(selectedKeys);
                    const _openKeys = JSON.parse(openKeys);
                    set_openKeys(_openKeys);
                    set_selectedKeys(_selectedKeys);
                  } else {
                    if (menuData[0].children && menuData[0].children.length > 0) {

                      const childs = menuData[0].children;
                      set_openKeys([menuData[0].key]);
                      set_selectedKeys([childs[0].key]);
                      localStorage.setItem('openKeys', JSON.stringify([menuData[0].key]));
                      localStorage.setItem('selectedKeys', JSON.stringify([childs[0].key]));
                      history.push(`${childs[0].path}`);

                    }else{
                      if(menuData[0]){
                        set_openKeys([menuData[0].key]);
                        set_selectedKeys([menuData[0].key]);
                        localStorage.setItem('openKeys', JSON.stringify([menuData[0].key]));
                        localStorage.setItem('selectedKeys', JSON.stringify([menuData[0].key]));
                        history.push(`${menuData[0].path}`);
                      }
                    }
                  }
                }

             
              }

              const addIcon = (arr: any) => arr.map((item: any) => (item.children ? {
                ...item,
                icon: <FolderOutlined />,
                children: addIcon(item.children)
              } : {
                ...item,
                icon: <FileOutlined />,
              }))

              const imgNode = (props: any) => {
                return <IconFont type='icon-pingtaiguanli'  />
              };

              const systemSet = (props: any) => {
                return <IconFont type='icon-xitongshezhi'  />
              };

              function addIconToPath(node: any) {
                if (node.name == '超管设置') {
                  node.icon = <Icon component={imgNode} />;
                }
                if (node.name == '系统设置') {
                  node.icon = <Icon component={systemSet} />;
                }
                if (node.children) {
                  node.children.forEach((child: any) => addIconToPath(child));
                }
              }
              

              const result = addIcon(menuData);


              result.forEach((item: any) => {
                addIconToPath(item);
              });

              return [...result];



            }
            return [];
          }
          return [];
        },
      }}
      onPageChange={(location) => { }}
      layout="side"
      navTheme="light"
      
    >
      {
        isEmpty && (
          <div className='emptyContainer' style={{ textAlign: 'center', paddingTop: 100 }}>
            <h1>{emptyPageContent}</h1>
          </div>
        )
      }
      {
        !isEmpty && (
          <PageContainer
            className="kcmpPageContainer"
            header={{
              title: false,
            }}
            style={{
              margin: 0,
            }}
          >

            <Helmet>
              <title>精益管理中台</title>
            </Helmet>

            <div className="page" style={{height: 'calc(100vh - 80px)', overflowY: 'scroll'}}>
              {children}
            </div>
          </PageContainer>
        )
      }
    </ProLayout>
  );
}
