import {
  ERROR_CODE,
  GENDER_OPTIONS,
  PRIOPRITY_OPTIONS,
  USER_TYPE_OPTIONS,
} from '@/constants/constants';
import { addUser, editUser, getUserById } from '@/services/userList';
import {
  Button,
  DatePicker,
  Form,
  Input,
  message,
  Modal,
  Radio,
  Select,
  TreeSelect,
} from 'antd';
import React, { useEffect } from 'react';

interface UserEditModalProps {
  //   visible: boolean;
  orgTreeData: User.OrganizationNode[];
  onCancel: () => void;
  onOk: (values?: any) => void;
  confirmLoading?: boolean;
  currentUserInfo?: User.UserModalBaseNode;
  selectedOrg?: number;
}

const UserEditModal: React.FC<UserEditModalProps> = ({
  orgTreeData,
  onCancel,
  onOk,
  confirmLoading = false,
  currentUserInfo,
}) => {
  const { recordData, visible, selectedOrg } = currentUserInfo || {};
  const { id } = recordData || {};
  const [form] = Form.useForm();

  useEffect(() => {
    if (id) {
      getUserById({ id }).then((res) => {
        const { data } = res;
        form.setFieldsValue(data);
      });
    } else {
      const initialValues = {
        user_group_id: selectedOrg ? selectedOrg : null,
        status: 1,
      };
      form.setFieldsValue(initialValues);
    }
  }, [visible, form, recordData, selectedOrg]);

  const handleOk = async () => {
    const values = await form.validateFields();
    try {
      const params = { ...values };
      if (id) {
        params.id = id;
      }
      const result: any = id ? await editUser(params) : await addUser(params);
      const { code } = result || {};
      if (code === ERROR_CODE) {
        onOk();
      } else {
        message.error('保存失败');
      }
    } catch (error) {
      message.error('请检查表单字段');
    }
  };

  const validateMessages = {
    required: '${label} is required!',
    types: {
      email: '${label} is not a valid email!',
      number: '${label} is not a valid number!',
    },
    number: {
      range: '${label} must be between ${min} and ${max}',
    },
  };

  // Password validation rule
  const passwordValidator = (_: any, value: string) => {
    if (!value) {
      return Promise.reject('请输入新密码');
    }

    if (value.length < 6) {
      return Promise.reject('密码长度至少6位');
    }

    const hasNumber = /\d/.test(value);
    const hasLetter = /[a-zA-Z]/.test(value);
    // const hasSpecialChar = /[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(value);

    if (!hasNumber) {
      return Promise.reject('密码必须包含数字');
    }

    if (!hasLetter) {
      return Promise.reject('密码必须包含字母');
    }

    // if (!hasSpecialChar) {
    //   return Promise.reject('密码必须包含特殊字符');
    // }

    return Promise.resolve();
  };

  return (
    <Modal
      title={id ? '编辑用户信息' : '新增用户'}
      open={visible}
      onCancel={onCancel}
      onOk={handleOk}
      confirmLoading={confirmLoading}
      width={600}
      maskClosable={false}
      centered={true}
      destroyOnHidden={true}
      cancelText="取消"
      okText="确定"
      //   按钮居中对其
      footer={null}
      // footer={
      //   <div style={{ display: 'flex', justifyContent: 'right' }}>
      //     <Button
      //       type="primary"
      //       onClick={handleOk}
      //       style={{ marginRight: '20px' }}
      //     >
      //       确定
      //     </Button>
      //     <Button onClick={onCancel} style={{ marginRight: '20px' }}>
      //       取消
      //     </Button>
      //   </div>
      // }
    >
      <Form
        form={form}
        labelCol={{ span: 5 }}
        onFinish={handleOk}
        wrapperCol={{ span: 18 }}
        layout="horizontal"
        style={{ paddingTop: '20px', paddingBottom: '20px' }}
        validateMessages={validateMessages}
      >
        <Form.Item
          name="user_name"
          label="用户姓名"
          rules={[{ required: true, message: '请输入用户姓名' }]}
        >
          <Input placeholder="请输入用户姓名" />
        </Form.Item>

        <Form.Item
          name="password"
          label="密码"
          rules={[{ required: true, validator: passwordValidator }]}
          help="密码必须包含数字和字母,字母区分大小写,且至少6位"
          style={{ marginBottom: '30px' }}
        >
          <Input.Password placeholder="请输入密码" />
        </Form.Item>

        <Form.Item
          name="user_group_id"
          label="用户分组"
          rules={[{ required: true, message: '请选择用户分组' }]}
        >
          <TreeSelect
            showSearch
            allowClear={false}
            treeDefaultExpandAll
            placeholder="请选择用户分组"
            treeData={orgTreeData}
            fieldNames={{ label: 'name', value: 'id', children: 'children' }}
          />
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Radio.Group>
            <Radio value={1}>启用</Radio>
            <Radio value={2}>禁用</Radio>
          </Radio.Group>
        </Form.Item>

        <Form.Item
          name="user_type"
          label="用户类别"
          rules={[{ required: false, message: '请选择用户类别' }]}
        >
          <Select placeholder="请选择用户类别" options={USER_TYPE_OPTIONS} />
        </Form.Item>
        <Form.Item name="birthday" label="出生日期">
          <DatePicker style={{ width: '414px' }} />
        </Form.Item>
        <Form.Item
          name="priority"
          label="优先级"
          rules={[{ required: false, message: '请选择用户优先级' }]}
        >
          <Select placeholder="请选择用户类别" options={PRIOPRITY_OPTIONS} />
        </Form.Item>
        <Form.Item
          name="gender"
          label="性别"
          rules={[{ required: false, message: '请选择性别' }]}
        >
          <Select placeholder="请选择性别" options={GENDER_OPTIONS} />
        </Form.Item>
        <Form.Item
          name="identity_no"
          label="身份证号"
          rules={[
            { required: false, message: '请输入身份证号' },
            {
              pattern:
                /^[1-9]\d{5}(18|19|20|21|22|23|24|25|26|27|28|29|30|31)\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20)$/,
              message: '请输入有效的身份证号',
            },
          ]}
        >
          <Input placeholder="请输入身份证号" />
        </Form.Item>

        {/* 电话号码 */}
        <Form.Item
          name="cell_phone"
          label="电话号码"
          rules={[{ required: false, message: '请输入电话号码' }]}
        >
          <Input placeholder="请输入电话号码" />
        </Form.Item>
        {/* 邮箱 */}
        <Form.Item
          name="email"
          label="邮箱"
          rules={[
            { required: false, message: '请输入邮箱' },
            { type: 'email', message: '请输入有效的邮箱地址' },
          ]}
        >
          <Input placeholder="请输入邮箱" />
        </Form.Item>

        <Form.Item label={null}>
          <Button
            type="primary"
            htmlType="submit"
            style={{ marginRight: '20px' }}
          >
            确定
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default UserEditModal;
