import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { Button } from 'antd'
import { useDispatch, useSelector } from 'react-redux'
import { RootState } from '@/store'
import { MessageFu } from '@/utils/message'
import MyPopconfirm from '@/components/MyPopconfirm'
import MyTable from '@/components/MyTable'
import { I6_APIdel, I6_APIgetList } from '@/store/action/Isystem/I6role'
import { TypeI6table } from './data'
import { I6tableC } from '@/utils/tableData'
import I6edit from './I6edit'
function I6role() {
  const dispatch = useDispatch()

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

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

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

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

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

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        width: 200,
        render: (item: TypeI6table) => {
          return item.id === 1 && !window.location.href.includes('?k=4DAGE') ? (
            '-'
          ) : (
            <>
              <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.I6role}>
      <div className='pageTitle'>角色管理</div>
      <div className='I6top'>
        <Button type='primary' onClick={() => setEditId(-1)}>
          新增
        </Button>
      </div>
      {/* 表格主体 */}
      <div className='tableBox'>
        <MyTable
          yHeight={585}
          list={tableInfo.list}
          columnsTemp={I6tableC}
          lastBtn={tableLastBtn}
          pageNum={fromData.pageNum}
          pageSize={fromData.pageSize}
          total={tableInfo.total}
          onChange={(pageNum, pageSize) => setFromData({ ...fromData, pageNum, pageSize })}
          widthSet={{ roleDesc: 800, sort: 100 }}
        />
      </div>

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

const MemoI6role = React.memo(I6role)

export default MemoI6role
