import React from 'react'
import produce from 'immer'
import { Modal, Tooltip, Button, Spin, Space } from 'antd'
import { PlusOutlined, ReloadOutlined } from '@ant-design/icons'

import { dispatch } from '../../../../model'
import Tree from '../../../../util/Component/Tree'
import PermissionButton from '../../../../util/Component/PermissionButton'
import Update from './update-rule-catalog'
import Version from './rule-catalog-version'
import { showMessage } from '../../../../util'

const FC = (props) => {
  const { onClick, readonly } = props
  const [loading, setLoading] = React.useState(false)
  const [data, setData] = React.useState()
  const [selectedNode, setSelectedNode] = React.useState()
  const [updateParams, setUpdateParams] = React.useState({
    visible: false,
    type: undefined,
    item: undefined,
  })
  const [versionParams, setVersionParams] = React.useState({
    visible: false,
    item: undefined
  })

  const [modal, contextHolder] = Modal.useModal()

  React.useEffect(() => {
    getTreeData()
  }, [])

  const treeData = React.useMemo(() => {
    if (data) {
      const newTreeData = produce(data, draft => {
        const setNode = (g) => {
          g.key = g.id
          g.title = g.name
        }
        draft.forEach((child) => {
          setNode(child)
        })
      })
  
      return newTreeData
    }

    return []
  }, [data])

  const getTreeData = () => {
    setLoading(true)
    dispatch({
      type: 'datamodel.getRuleCatalogList',
      callback: data => {
        setLoading(false);
        setData(data)

        if ((data??[]).length > 0 && !selectedNode) {
          onTreeSelect([data[0].id], { selectedNodes: [data[0]]})
        }
      },
      error: () => {
        setLoading(false);
      }
    })
  }

  const onTreeSelect = (selectedKeys, { selectedNodes }) => {
    if (selectedKeys.length === 0 || selectedNodes.length === 0) {
      return
    }
    
    setSelectedNode(selectedNodes[0])
    onClick?.(selectedNodes[0])
  }

  const onAddClick = () => {
    setUpdateParams({
      visible: true,
      type: 'add',
      item: undefined
    })
  }

  const onRefreshClick = () => {
    getTreeData()
  }

  const onMenuItemClick = (key, node) => {
    if (key === 'delete') {
      modal.confirm({
        title: '提示!',
        content: '您确定删除该目录吗?',
        onOk: () => {
          setLoading(true);
          dispatch({
            type: 'datamodel.deleteRuleCatalog',
            payload: {
              id: node?.id
            },
            callback: data => {
              showMessage('success', '删除目录成功')
              if (selectedNode?.id === node?.id) {
                setSelectedNode()
              }
              getTreeData()
            },
            error: () => {
              setLoading(false)
            }
          })
        }
      })
    } else if (key === 'edit') {
      setUpdateParams({
        visible: true,
        type: 'edit',
        item: node
      })
    } else if (key === 'up') {
      modal.confirm({
        title: '提示!',
        content: '您确定上移该目录吗?',
        onOk: () => {
          dispatch({
            type: 'datamodel.upRuleCatalog',
            payload: {
              params: {
                id: node?.id
              }
            },
            callback: data => {
              getTreeData()
            }
          })
        }
      })
    } else if (key === 'down') {
      modal.confirm({
        title: '提示!',
        content: '您确定下移该目录吗?',
        onOk: () => {
          dispatch({
            type: 'datamodel.downRuleCatalog',
            payload: {
              params: {
                id: node?.id
              }
            },
            callback: data => {
              getTreeData()
            }
          })
        }
      })
    } else if (key === 'version') {
      setVersionParams({
        visible: true,
        item: node,
      })
    }
  }

  return (
    <div>
      {
        !readonly && <div className='px-3' style={{ 
          display: 'flex',
          width: '100%',
          height: 40,
          alignItems: 'center',
          borderBottom: '1px solid #EFEFEF',
         }}>
          <Space>
            <PermissionButton 
              defaultPermission={true} 
              tip="新增目录"
              type="text" 
              icon={<PlusOutlined />} 
              onClick={onAddClick} 
            />
            <Tooltip title="刷新目录">
              <Button type="text" icon={<ReloadOutlined />} onClick={onRefreshClick} />
            </Tooltip>
          </Space>
        </div>  
      }
      <div className='p-3'>
        <Spin spinning={loading}>
          <Tree
            className='tree'
            showLine 
            showIcon={false} 
            treeData={treeData}
            onSelect={onTreeSelect}
            selectedKeys={(selectedNode?.id)?[selectedNode?.id]:undefined}
            shouldRowContextMenu={() => !readonly}
            menuData={[
              { id: 'edit', title: '编辑目录' },
              { id: 'up', title: '上移目录' },
              { id: 'down', title: '下移目录' },
              { id: 'delete', title: '删除目录' },
              { id: 'version', title: '历史版本' },
            ]}
            onMenuItemClick={onMenuItemClick}
          />
        </Spin>
      </div>
      <Update
        {...updateParams}
        onCancel={(refresh) => {
          setUpdateParams({
            visible: false,
            type: undefined,
            item: undefined
          })

          refresh && getTreeData()
        }}
      /> 
      <Version
        {...versionParams}
        onCancel={() => {
          setVersionParams({
            visible: false,
            item: undefined,
          })
        }}
      />
      {contextHolder}
    </div>
  )
}

export default FC