import React, { useCallback, useState } from 'react'
import { Layout, Menu, Icon } from 'antd';
import { useActions, useData, useCommit } from '@ttk/app-loader'
import { Link } from "@ttk/router"
// import {useHistory} from '@common/router/hook'
const { SubMenu } = Menu;

export default React.memo(TTKSider)
function TTKSider(props) {
  const commit = useCommit()
  const functionNav = useData('app-root/functionNav').toJS()
  // const [openKeys, setOpenKeys] = useState(['layout-0'])
  const { openKeys, selectedKeys } = useData('app-root/tempState').toJS()
  // const history = useHistory() 
  const onClick = useCallback(({ item, key, keyPath }) => {
    // setCurrentTab(keyPath[0])
    props.history.push(`${item.props.url}`)
    // actions.openTab(keyPath[0])
  }, []
  )
  const onOpenChange = useCallback((_openKeys) => {
    // const latestOpenKey = _openKeys.find(key => openKeys.indexOf(key) === -1);
    // setOpenKeys([latestOpenKey])
    commit([{ appName: 'app-root' }, 'tempState'], { type: "setOpenKeys", data: _openKeys})
  }, [openKeys])
  return (
    <div className="app-portal-sidebar">
      <Menu
        mode="inline"
        openKeys={openKeys}
        selectedKeys={selectedKeys}
        style={{ height: '100%', borderRight: 0 }}
        onClick={onClick}
        onOpenChange={onOpenChange}
      >
        <SubMenu
          key="sub1"
          title={<span><Icon type="user" />app-demo</span>}
        >
          <Menu.Item  url={"app-demo-update-title"} key="app-demo-update-title">update title</Menu.Item>
          {/* <Menu.Item key="app-demo-table">table</Menu.Item> */}
          <Menu.Item url={"app-registry"} key="app-registry">registry</Menu.Item>
          <Menu.Item url={"app-login"} key="app-login"><Link to="/app-root/app-login">login</Link></Menu.Item>
          <Menu.Item url={"app-demo-getstate"} key="app-demo-getstate">Get State</Menu.Item>
          <Menu.Item url={"router-example-url?name=admin&age=10"} key="router-example-url?name=admin&age=10">Router Example</Menu.Item>
        </SubMenu>
        {renderRoutes(props, functionNav, 1)}

      </Menu>
    </div>
  )
}

function renderRoutes(props, routes, level) {
  if (Array.isArray(routes)) {
    const result = routes.map((route, index) => {
      return renderRoute(props, route, level)
    })
    return result
  }
}
// functionType: "desk" 首页
function renderRoute(props, route, level) {
  if (route.subNodeFlag === '0') {
    // 没有子级
    return (<Menu.Item url={route.url} key={route.functioinId}>{route.imageUrl && <Icon type={route.imageUrl} />}{route.name}</Menu.Item>)
  } else {
    // 还有子级
    return (
      <SubMenu
        key={route.functioinId}
        title={<span><Icon type={route.imageUrl} />{route.name}</span>}
        className={level == 1 ? "" : "inner-sub-menu"}
      >
        {renderRoutes(props, route.childSecFunctioinDTOs)}
      </SubMenu>
    )
  }
}