import React, { useCallback, useEffect, useMemo, useState } from 'react'
import styles from './index.module.scss'
import { Button } from 'antd'
import MyTable from '@/components/MyTable'
import { A3_APIgetTypeList, A3_APItypeDel } from '@/store/action/A3course'
import { A3typeTableType } from '../type'
import { A3tableCtype } from '@/utils/tableData'
import MyPopconfirm from '@/components/MyPopconfirm'
import { MessageFu } from '@/utils/message'
import A3typeAdd from './A3typeAdd'

type Props = {
  closeFu: () => void
}

function A3typeTable({ closeFu }: Props) {
  const [list, setList] = useState<A3typeTableType[]>([])

  const getListFu = useCallback(async () => {
    const res = await A3_APIgetTypeList()
    if (res.code === 0) {
      const data: A3typeTableType[] = res.data
      setList(
        data.map(v => ({
          ...v,
          sort: v.id === 1 || v.name === '未分类' ? '/' : v.sort
        }))
      )
    }
  }, [])

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

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

  const tableLastBtn = useMemo(() => {
    return [
      {
        title: '操作',
        render: (item: A3typeTableType) =>
          item.id === 1 || item.name === '未分类' ? (
            '/'
          ) : (
            <>
              <Button
                size='small'
                type='text'
                onClick={() => setEditInfo({ id: item.id, name: item.name, sort: item.sort })}
              >
                编辑
              </Button>

              <MyPopconfirm txtK='删除' onConfirm={() => delTableFu(item.id)} />
            </>
          )
      }
    ]
  }, [delTableFu])

  //新增、编辑
  const [editInfo, setEditInfo] = useState({
    id: 0,
    name: '',
    sort: 0
  })
  return (
    <div className={styles.A3typeTable}>
      <div className='A3Ttop'>
        <div>
          <span className='A3TtopTit'>类别设置</span>&emsp;未分类的课程不会展示在用户端
        </div>
        <div>
          <Button
            type='primary'
            onClick={() => {
              if (list.length >= 20) return MessageFu.warning('最多支持20条数据!')
              setEditInfo({ id: -1, name: '', sort: 999 })
            }}
          >
            新增
          </Button>
          &emsp;
          <Button onClick={closeFu}>关闭</Button>
        </div>
      </div>

      <MyTable
        classKey='A3Ttable'
        yHeight={600}
        list={list}
        columnsTemp={A3tableCtype}
        lastBtn={tableLastBtn}
        pagingInfo={false}
      />

      {/* 新增 / 编辑*/}
      {editInfo.id ? (
        <A3typeAdd
          info={editInfo}
          closeFu={() => setEditInfo({ id: 0, name: '', sort: 0 })}
          editTableFu={getListFu}
        ></A3typeAdd>
      ) : null}
    </div>
  )
}

const MemoA3typeTable = React.memo(A3typeTable)

export default MemoA3typeTable
