import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { D1_APIdel, D1_APIgetlist } from '@/store/action/D1dict'
import { RootState } from '@/store'
import { Button } from 'antd'
import MyTable from '@/components/MyTable'
import { D1listType } from './data'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import D1add from './D1add'
function D1dict() {
  const dispatch = useDispatch()

  const getListFu = useCallback(() => {
    dispatch(D1_APIgetlist())
  }, [dispatch])

  useEffect(() => {
    getListFu()
  }, [getListFu])

  const tableList = useSelector((state: RootState) => state.D1dict.list)

  // 点击删除
  const delTableFu = useCallback(
    async (id: string) => {
      const res: any = await D1_APIdel(id)
      if (res.code === 0) {
        MessageFu.success('删除成功!')
        getListFu()
      }
    },
    [getListFu]
  )

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: D1listType) => (
          <>
            <Button size='small' type='text' onClick={() => setAddInfo(item)}>
              编辑
            </Button>
            <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
          </>
        )
      }
    ]
  }, [delTableFu])

  // 新增和编辑
  const [addInfo, setAddInfo] = useState({} as D1listType)

  return (
    <div className={styles.D1dict}>
      <div className='pageTitle'>字典管理</div>

      {tableList.map(item => (
        <div key={item.id} className='D1row'>
          <div className='D1row1'>
            <h3>{item.name}</h3>
            <Button
              type='primary'
              onClick={() => setAddInfo({ id: '-1', parentId: item.id } as D1listType)}
            >
              新增
            </Button>
          </div>

          <MyTable
            list={item.children}
            columnsTemp={[
              ['txt', '字典值', 'name'],
              ['txt', '排序值', 'sort']
            ]}
            lastBtn={tableLastBtn}
            pagingInfo={false}
          />
        </div>
      ))}

      {/* 新增和编辑 */}
      {addInfo.id ? (
        <D1add info={addInfo} upTableFu={getListFu} closeFu={() => setAddInfo({} as D1listType)} />
      ) : null}
    </div>
  )
}

const MemoD1dict = React.memo(D1dict)

export default MemoD1dict
