import React, { useRef, useState } from 'react';
import { TreeTransfer } from '@zhst/biz';
import { TreeDataNode } from 'antd';
import { TreeProps } from 'antd/lib';
import { MapBox } from '@zhst/map'
import { boxDataSource } from './mock'

const App: React.FC = () => {
  const [targetItems, setTargetItems] = useState<TreeDataNode[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<string[]>([]);
  const [activeTabKey, setActiveTabKey] = useState<string>('camera');
  const mapRef = useRef(null);
  const [canDraw, setCanDraw] = useState(false)
  const [toolsBarOpen, setToolsBarOpen] = useState(false)

  // 地图初始化
  const handleMapLoad = (e: mapboxgl.MapboxEvent<undefined>) => {
    const map = e.target;

    if (!map) return

    map.flyTo({
      // center: [120,30],
      // zoom: map?.getMaxZoom(),
    });
  };

  const onTreeCheck: TreeProps['onCheck'] = (keys: any, info) => {
    let _targetItems: TreeDataNode[] = []
    setCheckedKeys(keys)
    info.checkedNodes.forEach(o => {
      o.isLeaf && _targetItems.push(o)
    })
    setTargetItems(_targetItems)
  }

  /**
   * 删除
   * @param key
   * @param param1
   */
  const onItemDelete = (key: any, { keys = [] }: any) => {
    setCheckedKeys(pre => {
      const newKeys = pre.filter(_key => _key !== key)
      console.log('newKeys', newKeys, keys)
      return newKeys
    })
    setTargetItems(pre => pre.filter(o => o.key !== key))
  }

  const onOk = (data: any) => {
    console.log('data', data)
  }

  const onReset = () => {
    setCheckedKeys([])
    setTargetItems([])
  }

  return (
    <TreeTransfer
      dataSource={boxDataSource}
      targetItems={targetItems}
      checkedKeys={checkedKeys}
      leftPanelWidth={800}
      rightPanelWidth={600}
      onTreeCheck={onTreeCheck}
      showLeftTabs
      activeTabKey={activeTabKey}
      onLeftTabsChange={val => setActiveTabKey(val)}
      customLeftPanelContent={(data) => {
        if (activeTabKey !== 'map') return null

        return (
          <div
            style={{ flex: 1 }}
          >
            <MapBox
              onLoad={handleMapLoad}
              ref={mapRef}
              width='100%'
              height="402px"
              draw={canDraw}
              toolsBarOpen={toolsBarOpen}
              onToolClick={e => {
                setCanDraw(pre => !pre)
                setToolsBarOpen(pre => !pre)
              }}
              drawerProps={{
                onActionable: e => console.log('e', e)
              }}
            ></MapBox>
          </div>
        )
      }}
      onItemDelete={onItemDelete}
      onOk={onOk}
      onReset={onReset}
    />
  )
};

export default App;
