import React, { useState, useEffect, useMemo } from 'react'
import { connect } from 'dva'
import { withRouter } from 'dva/router'
import { Layout, Menu, Icon, Tabs, Dropdown } from 'antd'
import { Scrollbars } from 'react-custom-scrollbars'
import { CrumbsNav } from '@woowalker/feui'
import FormPage from '../components/FormPage'
import { usePrevious } from '../utils/hooks'
import { uuid, digTreeData } from '../utils/common'
import './backend.less'

const CustomTabMenu = (props) => {
  const { data } = props
  return (
    <Dropdown
      overlay={(
        <Menu onClick={(item) => props.onSelect(item, data)}>
          <Menu.Item key='refresh'>刷新</Menu.Item>
          <Menu.Item key='closeOther'>关闭其他</Menu.Item>
        </Menu>
      )}
      trigger={['contextMenu']}
    >
      <span>{data.title}</span>
    </Dropdown>
  )
}
const BackendTabs = (props) => {
  const [panes, setPanes] = useState([])
  const [activeKey, setActiveKey] = useState(undefined)

  const prevPane = usePrevious(props.pane)

  useEffect(() => {
    const { key } = props.pane
    if (key && key !== prevPane?.key) {
      const find = panes.find(item => item.key === key)
      !find && setPanes(panes.concat(props.pane))
      setActiveKey(key)
    }
  }, [props.pane, panes])

  const removePane = (targetKey) => {
    const currPanes = panes.filter(item => item.key !== targetKey)
    if (activeKey === targetKey) {
      let findIndex = panes.findIndex(item => item.key === targetKey)
      findIndex === 0 ? (findIndex++) : (findIndex--)
      setActiveKey(panes[findIndex].key)
    }
    setPanes(currPanes)
  }

  const handleMenuSelect = (data, pane) => {
    switch (data.key) {
      case 'refresh':
        const currPane = panes.find(item => item.key === activeKey)
        currPane.refreshKey = uuid()
        setPanes([...panes])
        break
      case 'closeOther':
        setPanes(panes.filter(item => item.key === pane.key))
        break
      default:
        break
    }
  }

  return (
    <Tabs
      hideAdd
      type='editable-card'
      activeKey={activeKey}
      onChange={setActiveKey}
      onEdit={removePane}
      tabBarExtraContent={<div className='backend__tab-nav'><CrumbsNav /></div>}
      className='backend__tab'
    >
      {
        panes.map((item) => {
          return (
            <Tabs.TabPane
              key={item.key}
              tab={<CustomTabMenu data={item} onSelect={handleMenuSelect} />}
              closable={panes.length !== 1}
            >
              <div key={item.refreshKey || item.key} className='backend__tab-content'>{item.content}</div>
            </Tabs.TabPane>
          )
        })
      }
    </Tabs>
  )
}

const MenuItem = ({ icon = 'setting', name }) => {
  return <div><Icon type={icon} /><span>{name}</span></div>
}
const Menus = (props) => {
  const [activeMenu, setActiveMenu] = useState(null)

  const menus = useMemo(() => {
    const { Menus } = props.login.loginInfo
    if (Menus && Array.isArray(Menus)) {
      const { menuId } = props.match.params
      const data = digTreeData(Menus, menuId)
      return data.Children
    }
    return []
  }, [props.login.loginInfo])

  const handleMenuSelect = (menu) => {
    const { ID, NAME, MENU_FORM_PARAMS, Nav_MenuForm, ICON } = menu

    const formCode = Nav_MenuForm ? Nav_MenuForm.CODE : ''
    const formParam = {}
    if (MENU_FORM_PARAMS) {
      const params = MENU_FORM_PARAMS.split('|')
      params.forEach(param => {
        const keyValues = param.split('=')
        if (keyValues.length >= 2) {
          formParam[keyValues[0]] = keyValues[1]
        } else {
          formParam[keyValues[0]] = null
        }
      })
    }

    props.onMenuSelect instanceof Function && props.onMenuSelect({
      key: ID,
      title: <span><Icon type={ICON} className='custom-dropdown-icon' />{NAME}[{formCode}]</span>,
      content: <FormPage formCode={formCode} formParam={formParam} />
    })

    setActiveMenu(menu)
  }

  useEffect(() => {
    const firstSubMenu = menus[0]?.Children[0]?.Menu
    firstSubMenu && handleMenuSelect(firstSubMenu)
  }, [menus])

  useEffect(() => {
    activeMenu && props.dispatch({
      type: 'app/updateActivatedMenu',
      payload: {
        currActivatedTab: activeMenu.ID,
        currActivatedMenu: activeMenu
      }
    })
  }, [activeMenu])

  return (
    <Menu mode='inline' selectedKeys={[activeMenu?.ID]}>
      {
        menus.map(item => {
          const { ChildMenus } = item
          if (ChildMenus.length) {
            return (
              <Menu.SubMenu
                key={item.Menu.ID}
                title={<MenuItem icon={item.Menu.ICON} name={item.Menu.NAME} />}
              >
                {
                  ChildMenus.map(childMenu => {
                    return (
                      <Menu.Item
                        key={childMenu.Menu.ID}
                        onClick={() => handleMenuSelect(childMenu.Menu)}
                      >
                        <MenuItem icon={childMenu.Menu.ICON} name={childMenu.Menu.NAME} />
                      </Menu.Item>
                    )
                  })
                }
              </Menu.SubMenu>
            )
          }
          return (
            <Menu.Item
              key={item.Menu.ID}
              onClick={() => handleMenuSelect(item.Menu)}
            >
              <MenuItem icon={item.Menu.ICON} name={item.Menu.NAME} />
            </Menu.Item>
          )
        })
      }
    </Menu>
  )
}
const BackendMenus = withRouter(connect(({ login }) => ({ login }))(Menus))

const Backend = (props) => {
  const [pane, setPane] = useState({})
  const [collapsed, setCollapsed] = useState(false)

  const navToHome = () => {
    props.history.push({ pathname: '/home' })
  }

  return (
    <Layout className='backend'>
      <Layout.Sider
        collapsible
        trigger={null}
        collapsed={collapsed}
        className='backend__sider'
      >
        <div className='backend__sider-collapsed'>
          <Icon
            title='返回首页'
            type='home'
            onClick={navToHome}
            className='backend__sider-collapsed--icon'
          />
          <Icon
            title={collapsed ? '展开' : '收起'}
            type={collapsed ? 'menu-unfold' : 'menu-fold'}
            onClick={() => setCollapsed(!collapsed)}
            className='backend__sider-collapsed--icon'
          />
        </div>
        <Scrollbars
          autoHide
          autoHideTimeout={1000}
          autoHideDuration={200}
          className='backend__sider-scrollbar'
        >
          <BackendMenus onMenuSelect={setPane} />
        </Scrollbars>
      </Layout.Sider>
      <Layout.Content className='backend__content'>
        <BackendTabs pane={pane} />
      </Layout.Content>
    </Layout>
  )
}

export default Backend