import { userSaveAPI } from '@/store/action/Z1user'
import { SaveUserType } from '@/types'
import { MessageFu } from '@/utils/message'
import { Button, Form, FormInstance, Input, Modal } from 'antd'
import React, { useCallback, useRef } from 'react'
import styles from './index.module.scss'
import MyPopconfirm from '@/components/MyPopconfirm'

type Props = {
  id: any
  closePage: () => void
  addTableList: () => void
}

function UserAdd({ id, closePage, addTableList }: Props) {
  const formRef = useRef<FormInstance>(null)
  // 通过校验点击确定
  const onFinish = useCallback(
    async (values: any) => {
      const obj: SaveUserType = {
        ...values,
        status: 1,
        password: '123456' // 添加默认密码
      }

      const res: any = await userSaveAPI(obj)

      if (res.message === '用户已添加') {
        return formRef.current?.setFields([
          {
            name: 'userName',
            errors: ['已存在重复用户名']
          }
        ])
      }

      if (res.code === 0) {
        MessageFu.success('新增成功!')
        addTableList()
        closePage()
      }
      // console.log("通过校验，点击确定");
    },
    [addTableList, closePage]
  )

  return (
    <Modal
      wrapClassName={styles.userAdd}
      destroyOnClose
      open={true}
      title='新增用户'
      footer={
        [] // 设置footer为空，去掉 取消 确定默认按钮
      }
    >
      <div className='userAddMain'>
        <Form
          ref={formRef}
          scrollToFirstError={true}
          name='basic'
          labelCol={{ span: 5 }}
          onFinish={onFinish}
          autoComplete='off'
        >
          <Form.Item
            label='用户名'
            name='userName'
            rules={[
              { required: true, message: '请输入用户名!' },
              { min: 6, max: 15, message: '用户名需为6-15个字符!' },
              {
                pattern: /^[a-zA-Z0-9]+$/,
                message: '用户名只能包含数字和字母!'
              }
            ]}
            getValueFromEvent={e => e.target.value.replace(/\s+/g, '')}
          >
            <Input
              disabled={id}
              maxLength={15}
              showCount
              placeholder='请输入内容，6-15字，不能重复'
            />
          </Form.Item>

          <Form.Item label='初始密码' name='password'>
            <div>123456</div>
          </Form.Item>

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

const MemoUserAdd = React.memo(UserAdd)

export default MemoUserAdd
