import { Menu, message } from 'antd';
import { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux'
import { add, active } from '@reducers/tabPanes'
import OrgManager from "../OrgManager";
import RoleManager from "../RoleManager";
import UserManager from "../UserManager";
import DataManager from "../DataManager";
import InpaManager from "../InpaManager"
import NullPage from "../NullPage";
import FuncManager from "../FuncManager";
import OperationLog from "../OperationLog";
import LoginLog from "../LoginLog";
import ExceptionLog from "../ExceptionLog";
import MyMessage from "../MyMessage";
import MsgManage from "../MsgManage";
import DiagManager from "../DiagManager"
import DrugManager from "../DrugManager"
import DocTemplate from "../DocTemplate";
import DutyRecord from "../DutyRecord";
import MedicalTeam from "../MedicalTeam";
import FieldRules from "../FieldRules";
import FieldProblem from "../FieldProblem";
import SurgeryManager from "../SurgeryManager";

import BlockLossManage from "../BlockLossManage";
import RegularManage from "../RegularManage";
// import SurgeryManager from "../SurgeryManager";
import apiObj from '@api/index';

const { post, api } = apiObj;
const { SubMenu } = Menu;
const propTypes = {};
const defaultProps = {};

const pageMap = {
    'QXGL-ZZGL': <OrgManager />,
    'QXGL-JSGL': <RoleManager />,
    'QXGL-YHGL': <UserManager />,
    'QXGL-SJQX': <DataManager />,
    'QXGL-BQGL': <InpaManager />,
    'XTSZ-GNGL': <FuncManager />,
    'RZGL-CZRZ': <OperationLog />,
    'RZGL-DLRZ': <LoginLog />,
    'RZGL-YCRZ': <ExceptionLog />,
    'ZNTZ-WDTZ': <MyMessage />,
    'ZNTZ-TZGL': <MsgManage />,
	'JCSJ-ZDXXWH': <DiagManager />,
  	'JCSJ-WSMBWH': <DocTemplate />,
    'JCSJ-ZWZCBGJL': <DutyRecord />,
    'QXGL-YLZGL': <MedicalTeam />,
    'SJZL-ZDJYGZWH': <FieldRules />,
    'SJZL-ZDJYWTMX': <FieldProblem />,
    'SJZL-BLSJDSMX': <BlockLossManage />,
    'SJZL-ZZSWH': <RegularManage />,
  	'JCSJ-SSXXWH': <SurgeryManager />,
    'JCSJ-YPXXWH':<DrugManager />,
}

let firstMenuPage = {};         //第一个菜单，自动激活时用
function AMenu() {
    const [menuList, setMenuList] = useState([]);        //菜单列表数据
    const [openKeys, setOpenKeys] = useState([]);       //当前展开的菜单key
    const [parentKeys,setParentKeys] = useState(null);      //一级菜单key,用于一次只展开一个菜单
    const dispatch = useDispatch();
    //当前选中的菜单
    const { activeTab, panes } = useSelector(state => {
        return state.tabPanes;
    });
    //console.log(44,activeTab)
    //切换菜单、增加tab
    function changeMenu(val) {
        const idName = val.key.split("&");
        const item = panes.find((it) => it.key === val.key);
        if (item) {   //已存在当前tab，则定位即可不增加
            dispatch(active({idName:val.key}));
            return;
        }
        dispatch(
            add({ title: idName[1], content: pageMap[idName[0]] || <NullPage />, key: val.key })
        )
    }
    //获取菜单数据
    function getUserMenus() {
        post(api.getUserShowMemuTree).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data;
                const menuData = data.showMenuInfo;
                setMenuList(menuData);
			    getParentKeys(menuData);
                firstMenuPage = findFirstPage(menuData);
                const {menuName,code}=firstMenuPage;
                dispatch(
                    add({ title: menuName, content: pageMap[code] || <NullPage />, key: code+"&"+menuName })
                );
            } else {
                message.error(res.data.message || '获取菜单失败');
            }
        })
    }
    function getParentKeys(menuData){
        //获取第一级菜单key，用于单项展开
	  const arr= menuData.map((it)=>{
	      return it.code+"&"+it.menuName;
      });
	  setOpenKeys([arr[0]]);
	  setParentKeys(arr);
    }
    function findFirstPage(menuData){
        //获取第一个菜单页面，默认选中
        if(!menuData) return null;
        let page1=null;
        menuData.find((it)=>{
            if(it.menuType==='1'){
                page1=it;
                return true;
            }else if(it.menuType==='0'&&it.children){
                page1=findFirstPage(it.children);
                if(page1) return true
            }
        });
        return page1;
    }

    function getSubMenu(data) {     //menuType=0目录，1页面，2按钮
        return data.map((it) => {
            if (it.menuType === '1') {
                return (
                    <Menu.Item key={it.code+"&"+it.menuName}>{it.menuName}</Menu.Item>
                )
            } else if (it.menuType === '0') {
                return (
                    <SubMenu key={it.code+"&"+it.menuName} title={it.menuName}>
                        {it.children ? getSubMenu(it.children) : ''}
                    </SubMenu>
                )
            } else {
                return ''
            }
        });
	}
    function onOpenChange(keys){
	  const latestOpenKey = keys.find(key => openKeys.indexOf(key) === -1);
	  if (parentKeys.indexOf(latestOpenKey) === -1) {
		setOpenKeys(keys);
	  } else {
		setOpenKeys(latestOpenKey ? [latestOpenKey] : []);
	  }
    }
    useEffect(() => {
        getUserMenus();
    }, []);
    return (
            <Menu
                selectedKeys={activeTab}
                mode="inline"
				openKeys={openKeys}
				onOpenChange={onOpenChange}
                onClick={changeMenu}
            >
                {
                    getSubMenu(menuList)
                }
            </Menu>
    )
}
AMenu.propTypes = propTypes;
AMenu.defaultProps = defaultProps;
export default AMenu;