/*
 * @Author: your name
 * @Date: 2022-01-06 15:25:39
 * @LastEditTime: 2023-06-02 18:14:47
 * @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 { Iframe, SpacicalPageParamsType } from '@/typings';
import { Key, useEffect, useState } from 'react';
import IconFont from '@ant-design/icons/lib/components/IconFont';
import { FileOutlined, FolderOutlined, SmileOutlined } from '@ant-design/icons';
import { getParamsManaTableData } from './setting/paramsMana/service';
import { getAllParams } from '@/service';

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 [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]);


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

  //临时演示处理
  console.log('location.pathname',location.pathname);
  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/KcimDairlyLog') {

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

    // 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}`)
    //   //   }
    //   // }

    //   set_pageUrl(`http://www.baidu.com`)
    // }

    // getToken();

    const pageUrl = `http://118.31.50.255:8080/`;

    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 ? 220 : 0}
      pageTitleRender={false}
      disableContentMargin
      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}`);
                      }
                    }
                  }
                }

              }

              // console.log({homePage})
              // return [...menuData, {
              //   name: 'SQL编辑器',
              //   path: '/platform/sqlEditer'
              // }];

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

              const result = addIcon(menuData);


              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>
  );
}
