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

type Props = {
  info: D1listType
  upTableFu: () => void
  closeFu: () => void
}

function D1add({ info, upTableFu, closeFu }: Props) {
  useEffect(() => {
    FormBoxRef.current?.setFieldsValue({ ...info, sort: info.id === '-1' ? 999 : info.sort })
  }, [info])

  // 设置表单ref
  const FormBoxRef = useRef<FormInstance>(null)

  // 没有通过校验
  const onFinishFailed = useCallback(() => {
    // return MessageFu.warning("有表单不符号规则!");
  }, [])

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      const res = await D1_APIsave({
        ...values,
        id: info.id === '-1' ? null : info.id,
        type: 'dict',
        parentId: info.parentId
      })
      if (res.code === 0) {
        MessageFu.success(`${info.id === '-1' ? '新增' : '编辑'}成功`)
        upTableFu()
        closeFu()
      }
    },
    [closeFu, info, upTableFu]
  )

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

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

          {/* 确定和取消按钮 */}
          <br />
          <Form.Item wrapperCol={{ offset: 9, span: 16 }}>
            <Button type='primary' htmlType='submit'>
              提交
            </Button>
            &emsp;
            <MyPopconfirm txtK='取消' onConfirm={closeFu} />
          </Form.Item>
        </Form>
      </div>
    </Modal>
  )
}

const MemoD1add = React.memo(D1add)

export default MemoD1add
