
import { Empty, Spin, Tree } from 'antd'
import { MenuItem } from '@/global'
import { useStyle } from '../style.ts'
import { useTranslation } from '@/i18n.ts'
import { useSetAtom } from 'jotai'
import { batchIdsAtom, menuDataAtom, selectedMenuAtom } from '@/store/menu.ts'
import { FormInstance } from 'antd/lib'
import { useAtomValue } from 'jotai'
import { TreeNodeRender } from './TreeNodeRender.tsx'
import { useEffect, useRef } from 'react'
import { flattenTree } from '@/utils'
import { useDeepCompareEffect } from 'react-use'

const MenuTree = ({ form }: { form: FormInstance }) => {


  const { styles } = useStyle()
  const { t } = useTranslation()
  const setCurrentMenu = useSetAtom(selectedMenuAtom)
  const setIds = useSetAtom(batchIdsAtom)
  const { data = [], isLoading } = useAtomValue(menuDataAtom)
  const flattenMenusRef = useRef<MenuItem[]>([])

  useDeepCompareEffect(() => {

    if (isLoading) return

    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore array
    if (data.length) {
      // @ts-ignore flattenTree
      flattenMenusRef.current = flattenTree<MenuItem[]>(data as any)
      // console.log(flattenMenusRef.current)
    }

  }, [ data, isLoading ])

  useEffect(() => {
    return () => {
      setCurrentMenu({} as MenuItem)
      setIds([])
    }
  }, [])

  const renderEmpty = () => {
    if ((data as any).length > 0 || isLoading) return null
    return <Empty description={t('message.emptyDataAdd', '暂无数据，点击添加')}/>
  }

  return (
    <>
      <Spin spinning={isLoading} style={{ minHeight: 200 }}>
        {
          renderEmpty()
        }
        <Tree.DirectoryTree
          className={styles.tree}
          treeData={data as any}
          defaultExpandAll={true}
          // draggable={true}
          titleRender={(node) => {
            return (<TreeNodeRender node={node as any} form={form}/>)
          }}
          fieldNames={{
            title: 'title',
            key: 'id'
          }}
          onSelect={(item) => {
            const current = flattenMenusRef.current?.find((menu) => menu.id === item[0])
            setCurrentMenu(current as MenuItem)
            form.setFieldsValue({ ...current })
          }}
          onCheck={(item) => {
            setIds(item as number[])
          }}
          checkable={true}
          showIcon={false}
        />
      </Spin>
    </>
  )
}

export default MenuTree