/*
 * @Author: your name
 * @Date: 2021-11-10 09:33:30
 * @LastEditTime: 2021-12-21 11:04:18
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: /KC-MiddlePlatform/src/pages/index.tsx
 */

import { useState, useEffect } from 'react';
import TopBar from './components/topBar';
import IframePage from './components/iframePage';
import { useModel,history } from 'umi';
import './index.less';

const IndexPage = () => {
  const {
    systemLists, //当前医院可选子系统列表
    setInitialState,
    openedSysLists, //当前已打开的系统列表
    loading,
    currentSelectedSys, //当前选中的系统
    logout,
  } = useModel('@@initialState', (model) => {
    console.log({ model });
    return {
      systemLists: model.initialState?.systemLists,
      setInitialState: model.setInitialState,
      openedSysLists: model.initialState?.openedSysLists,
      loading: model.loading,
      currentSelectedSys: model.initialState?.currentSelectedSys,
      logout: model.initialState?.logout,
    };
  });

  const [selectableSysList, setSelectableSysList] = useState<SystemListItem[]>(
    [],
  ); //可选的子应用
  const [openedTabs, setOpenTabs] = useState<SystemListItem[]>(); //当前已开启的子应用集合
  const [currentOpenedTab, setCurrentOpenedTab] = useState<SystemListItem>(); //当前激活的应用

  const onCurrentSystemChanged = async (data: SystemListItem) => {
    console.log({ 当前选中tab: data });
    setCurrentOpenedTab(data);
    const index = openedSysLists?.findIndex((t) => t.id == data.id);
    if (index != -1) {
      //现在打开的tab里已经存在
      await setInitialState((s) => {
        return {
          ...s,
          currentSelectedSys: data,
        };
      });
    } else {
      //新打开的tab
      await setInitialState((s) => {
        return {
          ...s,
          currentSelectedSys: data,
          openedSysLists: openedSysLists?.concat(data),
        };
      });
    }
  };

  const userPannelTabClick = async (tag: string) => {
    if (tag == 'LOGOUT') {
      if (logout) {
        await logout();
      }
    }
  };

  useEffect(() => {
    if (systemLists) setSelectableSysList(systemLists);
  }, [systemLists]);

  useEffect(() => {
    if (openedSysLists) setOpenTabs(openedSysLists);
    // console.log({openedSysLists});
  }, [openedSysLists]);

  useEffect(() => {
    setCurrentOpenedTab(currentSelectedSys); //当前激活的tab
  }, [currentSelectedSys]);

  useEffect(() => {
    if (systemLists) setSelectableSysList(systemLists);
    if (openedSysLists) setOpenTabs(openedSysLists);


    window.addEventListener('message', function(event){
      if (event.origin === "http://localhost:8804"){
               console.log(event.data);
               if(event.data.type == 'LOGOUT'){
                     history.replace('/login') 
               }
      }
      
    }, false);

    return ()=>{
      window.removeEventListener('message',()=>{}); 
    }
  }, []);

  if (loading) return <h1>Loading...</h1>;

  

  return (
    <div className="indexPage">
      <TopBar
        openedTabs={openedTabs ? openedTabs : []}
        onTabChange={(data) => {
          onCurrentSystemChanged(data);
        }}
        sysList={selectableSysList}
        currentTab={currentOpenedTab}
        userPannelTabClick={(tag) => userPannelTabClick(tag)}
      />

      {/* <MicroApp name='MedicalWisdomCheckSys' /> */}

      {openedTabs && (
        <IframePage activedItem={currentOpenedTab} list={openedTabs} />
      )}
    </div>
  );
};

export default IndexPage;
