import { useState, useEffect } from 'react'
import { Form, Input, Button, Space, Row, Col, Drawer } from 'antd'
import users from '@/assets/images/icon/userinfo.png'
import { changePass, changeInfo, getUserInfo } from '@/layout/request'
import { useNavigate } from 'react-router-dom'
import UploadImage from '@/components/uploadImage'

const UserInfo = () => {
  const navigator = useNavigate()

  const [imageUrl, setImageUrl] = useState('')
  const [form] = Form.useForm()
  const [form2] = Form.useForm()
  const [showModal, setShowModal] = useState(false)

  const fetchData = async obj => {
    try {
      const userData = await getUserInfo(obj)

      form.setFieldsValue({
        real_name: userData.real_name,
        tel: userData.tel,
        pic: userData.pic
      })
      const imageUrl = userData.pic
      setImageUrl(imageUrl)
    } catch (error) {
      console.error('Error fetching user data:', error)
    }
  }

  useEffect(() => {
    fetchData()
  }, [])

  const changePasswrd = async obj => {
    await changePass(obj)
    setShowModal(false)
  }

  const submitForm = async obj => {
    const updatedData = await changeInfo({ ...obj })
    if (updatedData) {
      await fetchData()
    }
  }

  return (
    <div style={{ padding: '20px 0' }}>
      <Form form={form} labelCol={{ span: 2 }} onFinish={submitForm}>
        <Form.Item label="头像" className="uploadPar" name="pic">
          <UploadImage value={imageUrl ? imageUrl : users} onChange={url => setImageUrl(url)}></UploadImage>
        </Form.Item>
        <Form.Item label="管理员名称" name="real_name" rules={[{ required: true, message: '请输入管理员名称' }]}>
          <Input autoComplete="off" placeholder="请输入管理员名称" style={{ width: 200 }}></Input>
        </Form.Item>
        <Form.Item label="手机号" name="tel" rules={[{ required: true, message: '请输入手机号' }]}>
          <Input autoComplete="off" placeholder="请输入手机号" style={{ width: 200 }}></Input>
        </Form.Item>
        <Form.Item label="密码">
          <Button type="primary" ghost onClick={() => setShowModal(true)}>
            修改密码
          </Button>
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 2 }}>
          <Space size={20}>
            <Button className="cancel" onClick={() => navigator(-1)}>
              取消
            </Button>
            <Button className="submit" htmlType="submit">
              保存
            </Button>
          </Space>
        </Form.Item>
      </Form>
      <Drawer
        open={showModal}
        onClose={() => {
          setShowModal(false)
        }}
        mask={false}
        maskClosable={false}
        footer={null}
        centered
        destroyOnClose
        keyboard={false}>
        <Form labelCol={{ span: 5 }} form={form2} onFinish={changePasswrd}>
          <Form.Item label="旧密码" name="old_password" rules={[{ required: true, message: '请输入旧密码' }]}>
            <Input.Password autoComplete="off" placeholder="请输入旧密码"></Input.Password>
          </Form.Item>
          <Form.Item
            label="新密码"
            name="password"
            rules={[
              { required: true, message: '请输入新密码' },
              {
                pattern:
                  /^((?=.*\d)(?=.*[A-Z])(?=.*[a-z]))|((?=.*\d)(?=.*[A-Z])(?=.*[\W_]))|((?=.*\d)(?=.*[a-z])(?=.*[\W_]))|((?=.*[A-Z])(?=.*[a-z])(?=.*[\W_]))[a-zA-Z\d\W_]{8,12}$/,
                message: '密码至少满足三种格式(大写字母、小写字母、数字、特殊符号), 长度为8~12位字符！',
                trigger: ['change', 'blur']
              },
              {
                validator(_, value) {
                  if (!value || form2.getFieldValue('re_password') === value) {
                    form2.setFields([{ name: 're_password', errors: [''] }])
                    return Promise.resolve()
                  }
                  form2.setFields([{ name: 're_password', errors: ['两次输入的密码不一致'] }])
                  return Promise.reject()
                }
              }
            ]}>
            <Input.Password autoComplete="off" placeholder="请输入新密码"></Input.Password>
          </Form.Item>
          <Form.Item
            label="确认新密码"
            name="re_password"
            rules={[
              { required: true, message: '请确认新密码' },
              {
                pattern:
                  /^((?=.*\d)(?=.*[A-Z])(?=.*[a-z]))|((?=.*\d)(?=.*[A-Z])(?=.*[\W_]))|((?=.*\d)(?=.*[a-z])(?=.*[\W_]))|((?=.*[A-Z])(?=.*[a-z])(?=.*[\W_]))[a-zA-Z\d\W_]{8,12}$/,
                message: '密码至少满足三种格式(大写字母、小写字母、数字、特殊符号), 长度为8~12位字符！',
                trigger: ['change', 'blur']
              },
              {
                validator(_, value) {
                  if (!value || form2.getFieldValue('password') === value) {
                    return Promise.resolve()
                  }
                  return Promise.reject(new Error('两次输入的密码不一致'))
                }
              }
            ]}>
            <Input.Password autoComplete="off" placeholder="请确认新密码"></Input.Password>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 5 }}>
            <Row justify={'center'}>
              <Space size={20}>
                <Col>
                  <Button className="cancel" onClick={() => setShowModal(false)}>
                    取消
                  </Button>
                </Col>
                <Col>
                  <Button className="submit" htmlType="submit">
                    确认
                  </Button>
                </Col>
              </Space>
            </Row>
          </Form.Item>
        </Form>
      </Drawer>
    </div>
  )
}

export default UserInfo
