import React, { useCallback, useEffect, useRef } from 'react'
import styles from './index.module.scss'
import { Button, Form, FormInstance, Input, Modal, Select } from 'antd'
import MyPopconfirm from '@/components/MyPopconfirm'
import { TypeZ2list } from './type'
import { Z2editSelectDate, Z2editSelectlength } from './data'
import { Z2_APIsave } from '@/store/action/Z2numRule'
import { MessageFu } from '@/utils/message'

type Props = {
  editObj: TypeZ2list
  editFu: () => void
  closeFu: () => void
}

function Z2edit({ editObj, editFu, closeFu }: Props) {
  useEffect(() => {
    FormBoxRef.current?.setFieldsValue(editObj)
  }, [editObj])

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

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

  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      const obj = { ...values, id: editObj.id }
      const res = await Z2_APIsave(obj)
      if (res.code === 0) {
        MessageFu.success('编辑成功')
        editFu()
        closeFu()
      }
    },
    [closeFu, editFu, editObj.id]
  )

  return (
    <Modal
      wrapClassName={styles.Z2edit}
      open={true}
      title='编辑'
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='Z2aMain'>
        <Form
          scrollToFirstError={true}
          ref={FormBoxRef}
          name='basic'
          labelCol={{ span: 3 }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete='off'
        >
          <Form.Item label='编号类型' name='name'>
            <Input maxLength={30} disabled />
          </Form.Item>

          <Form.Item
            label='前缀'
            name='prefix'
            rules={[{ pattern: /^[A-Z0-9]*$/, message: '请输入大写英文字母或数字' }]}
          >
            <Input maxLength={6} showCount placeholder='请输入大写英文字母或数字' />
          </Form.Item>

          <Form.Item label='日期方式' name='dateType'>
            <Select options={Z2editSelectDate} />
          </Form.Item>

          <Form.Item label='流水号位数' name='length' rules={[{ required: true, message: '' }]}>
            <Select options={Z2editSelectlength} />
          </Form.Item>

          {/* 确定和取消按钮 */}
          <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 MemoZ2edit = React.memo(Z2edit)

export default MemoZ2edit
