import React, { useCallback, useEffect, useState } from 'react'
import styles from './index.module.scss'
import MyTable from '@/components/MyTable'
import { A3DictRowType, A3DictType } from './data'
import { useDispatch, useSelector } from 'react-redux'
import { A3_APIdel, A3_APIgetList } from '@/store/action/A3dict'
import { A3tableC } from '@/utils/tableData'
import { Button } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import { RootState } from '@/store'
import A3add from './A3add'

const titArr: { name: string; type: A3DictRowType }[] = [
  {
    name: '附件用途',
    type: 'effect'
  },
  {
    name: '维护类型',
    type: 'maintain'
  },
  {
    name: '乡镇',
    type: 'village'
  }
]

function A3dict() {
  const dispatch = useDispatch()

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

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

  // 表格相关---------------

  const listObj = useSelector((state: RootState) => state.A3dict.listObj)

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

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

  const tableLastBtn = useCallback(
    (type: A3DictRowType) => {
      return [
        {
          title: '操作',
          render: (item: A3DictType) =>
            item.name === '其他' ? (
              '-'
            ) : (
              <>
                <Button size='small' type='text' onClick={() => setAddInfo(item)}>
                  编辑
                </Button>
                <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
              </>
            )
        }
      ]
    },
    [delTableFu]
  )

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

      {titArr.map(item => (
        <div className='A3box' key={item.name}>
          <div className='A3Tit'>
            <h3>{item.name}</h3>
            <Button
              type='primary'
              onClick={() => setAddInfo({ type: item.type, id: -1 } as A3DictType)}
            >
              新增
            </Button>
          </div>

          <MyTable
            classKey={`A3box${item.type}`}
            yHeight={672}
            list={listObj[item.type]}
            columnsTemp={A3tableC}
            lastBtn={tableLastBtn(item.type)}
            pagingInfo={false}
          />
        </div>
      ))}

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

const MemoA3dict = React.memo(A3dict)

export default MemoA3dict
