import React, { useCallback, useEffect, useRef } from 'react'
import styles from './index.module.scss'
import { Button, Form, FormInstance, Input, InputNumber, Modal } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { A3_APItypeSave } from '@/store/action/A3course'
import { MessageFu } from '@/utils/message'

type Props = {
  info: { id: number; name: string; sort: number }
  closeFu: () => void
  editTableFu: () => void
}

function A3typeAdd({ info, closeFu, editTableFu }: Props) {
  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null)

  useEffect(() => {
    FormBoxRef.current?.setFieldsValue(info)
  }, [info])

  // 没有通过校验
  const onFinishFailed = useCallback(() => {}, [])

  //  通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      const obj = {
        ...values,
        id: info.id > 0 ? info.id : null,
        display: 1
      }

      const res = await A3_APItypeSave(obj)
      if (res.code === 0) {
        MessageFu.success(info.id > 0 ? '编辑成功!' : '新增成功!')
        editTableFu()
        closeFu()
      }
    },
    [closeFu, editTableFu, info.id]
  )

  return (
    <Modal
      wrapClassName={styles.A3typeAdd}
      open={true}
      title={info.id > 0 ? '编辑' : '新增'}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <Form
        ref={FormBoxRef}
        name='basic'
        labelCol={{ span: 4 }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete='off'
        scrollToFirstError
      >
        <Form.Item
          label='课程类别名称'
          name='name'
          rules={[{ required: true, message: '请输入课程类别名称!' }]}
          getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
        >
          <Input placeholder='请输入内容' maxLength={10} showCount />
        </Form.Item>

        <div className='A3TAfromRow'>
          <Form.Item
            label='排序值'
            name='sort'
            rules={[{ required: true, message: '请输入排序值!' }]}
          >
            <InputNumber min={1} max={999} precision={0} placeholder='请输入' />
          </Form.Item>
          <div className='A3TA_6Frow'>
            请输入1~999的数字。数字越小，排序越靠前。数字相同时，更新发布的内容排在前面
          </div>
        </div>

        {/* 确定和取消按钮 */}
        <Form.Item className='A3TAbtn'>
          <Button type='primary' htmlType='submit'>
            提交
          </Button>
          &emsp;
          <MyPopconfirm txtK='取消' onConfirm={closeFu} />
        </Form.Item>
      </Form>
    </Modal>
  )
}

const MemoA3typeAdd = React.memo(A3typeAdd)

export default MemoA3typeAdd
