import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { useDispatch, useSelector } from 'react-redux'
import { D3_APIdel, D3_APIgetList } from '@/store/action/D3role'
import { RootState } from '@/store'
import { MessageFu } from '@/utils/message'
import { D3listType } from './data'
import { Button } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import MyTable from '@/components/MyTable'
import { D3tableC } from '@/utils/tableData'
import D3add from './D3add'
function D3role() {
  const dispatch = useDispatch()

  // 顶部筛选
  const [fromData, setFromData] = useState({
    pageNum: 1,
    pageSize: 10,
    searchKey: ''
  })

  // 封装发送请求的函数
  const getList = useCallback(() => {
    dispatch(D3_APIgetList(fromData))
  }, [dispatch, fromData])

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

  // 从仓库中获取表格数据
  const tableInfo = useSelector((state: RootState) => state.D3role.tableInfo)

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

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

  // 点击重置
  const resetSelectFu = useCallback(() => {
    setFromData({
      pageNum: 1,
      pageSize: 10,
      searchKey: ''
    })
  }, [])

  // 点击新增和编辑
  const [editId, setEditId] = useState(0)

  return (
    <div className={styles.D3role}>
      <div className='pageTitle'>角色管理</div>
      <div className='D3top'>
        <Button type='primary' onClick={() => setEditId(-1)}>
          新增
        </Button>
      </div>
      {/* 表格主体 */}
      <div className='tableBox'>
        <MyTable
          yHeight={630}
          list={tableInfo.list}
          columnsTemp={D3tableC}
          lastBtn={tableLastBtn}
          pageNum={fromData.pageNum}
          pageSize={fromData.pageSize}
          total={tableInfo.total}
          onChange={(pageNum, pageSize) => setFromData({ ...fromData, pageNum, pageSize })}
          widthSet={{ roleDesc: 800 }}
        />
      </div>

      {/* 新增和编辑 */}
      {editId ? (
        <D3add
          sId={editId}
          closeFu={() => setEditId(0)}
          addTableFu={resetSelectFu}
          editTableFu={getList}
        />
      ) : null}
    </div>
  )
}

const MemoD3role = React.memo(D3role)

export default MemoD3role
