import React, { useEffect, useCallback, useState } from 'react'
import { Tabs, Radio } from 'antd'
import { useData, useActions } from '@ttk/app-loader'
import Content from './components/content'
import "./style.less"
const { TabPane } = Tabs

export default React.memo(Page)
function Page(props) {

  const actions = useActions(props)
  const panes = useData([props, 'panes']).toJS()
  const [activeKey, setActiveKey] = useState(panes[0].key)
  const [size, setSize] = useState('small')
  const [position, setPosition] = useState('top')

  // 添加或删除tab回调方法
  const onEdit = useCallback((targetKey, action) => {
    if (action === 'add') {
      let randomText = (Math.random() + '').slice(2)
      let content = <Content randomText={`新的tab---${randomText}`}/>
      actions.addTab({ title: `新标签-${randomText.slice(14)}`, content, key: randomText })
      setActiveKey(randomText)
    } else if (action === 'remove') {
      actions.removeTab({ key: targetKey })
      if (panes.length <= 1) {
        return 
      }
      let nextActiveKey = activeKey
      if (nextActiveKey === targetKey) {
        // 关闭当前tab时
        if (targetKey === panes[0].key) {
          nextActiveKey = panes[1].key
        } else {
          nextActiveKey = panes[0].key
        }
      }
      console.log(nextActiveKey);
      setActiveKey(nextActiveKey)
    }
  }, [activeKey, panes])

  // 切换tab
  const onChange = useCallback((key) => {
    setActiveKey(key)
  })

  // 变更tab展示方位
  const onChangePosition = useCallback((e) => {
    setPosition(e.target.value)
  })

  return (
    <div className="tabs-container">
      可变位置：
      <Radio.Group value={position} onChange={onChangePosition} style={{ marginBottom: 16 }}>
        <Radio.Button value="left">Left</Radio.Button>
        <Radio.Button value="top">Top</Radio.Button>
        <Radio.Button value="right">Right</Radio.Button>
        <Radio.Button value="bottom">Bottom</Radio.Button>
      </Radio.Group>
      <Tabs
        tabBarGutter={4}
        onChange={onChange}
        activeKey={activeKey}
        // size={size}
        tabPosition={position}
        type="editable-card"
        onEdit={onEdit}
      >
        {panes.map(pane => (
          <TabPane tab={pane.title} key={pane.key} closable={pane.closable}>
            {pane.content}
          </TabPane>
        ))}
      </Tabs>
    </div>
  )
}


