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

type Props = {
  sInfo: A3DictType
  closeFu: () => void
  upTableFu: () => void
}

function A3add({ sInfo, closeFu, upTableFu }: Props) {
  // 表单的ref
  const FormBoxRef = useRef<FormInstance>(null)

  // 编辑进来获取详情
  const getInfoFu = useCallback(async (info: A3DictType) => {
    FormBoxRef.current?.setFieldsValue(info)
  }, [])

  useEffect(() => {
    if (sInfo.id > 0) getInfoFu(sInfo)
    else FormBoxRef.current?.setFieldsValue({ sort: 999 })
  }, [getInfoFu, sInfo])

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

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

      // if (1 + 1 === 2) {
      //   console.log('------222', obj)
      //   return
      // }

      const res = await A3_APIsave(obj)

      if (res.code === 0) {
        MessageFu.success(`${sInfo.id > 0 ? '编辑' : '新增'}成功`)
        upTableFu()
        closeFu()
      }
    },
    [closeFu, sInfo, upTableFu]
  )

  return (
    <Modal
      wrapClassName={styles.A3add}
      open={true}
      title={sInfo.id > 0 ? '编辑字典' : '新增字典'}
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <Form
        ref={FormBoxRef}
        name='basic'
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete='off'
        scrollToFirstError
      >
        <Form.Item
          label='字典值'
          name='name'
          rules={[{ required: true, message: '请输入字典值' }]}
          // getValueFromEvent={(e) => e.target.value.replace(/\s+/g, "")}
          getValueFromEvent={e => e.target.value.trim()}
        >
          <Input maxLength={30} showCount placeholder='请输入内容' />
        </Form.Item>

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

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

const MemoA3add = React.memo(A3add)

export default MemoA3add
