import {
  ModalForm,
  ProFormRadio,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Form, message } from 'antd';
import React, { useState } from 'react';
import { OPTIONS } from '../../../constants';
import { CommonController, UserController, types } from '../../../services';
import validator from '../../../utils/validator';
interface EditFormProps {
  title: string;
  type: 'add' | 'update';
  trigger: JSX.Element;
  value?: UserController.UserFields;
  docList: CommonController.DocOptionFields[];
  roleList: types.SelectOptionFields[];
  onOk: () => void;
}

interface ModalFormProps extends UserController.UserFields {
  roleIds: string;
}

const EditForm: React.FC<EditFormProps> = ({
  trigger,
  title,
  value,
  type,
  docList,
  roleList,
  onOk,
}) => {
  const [form] = Form.useForm<ModalFormProps & { password2: string }>();
  const [open, setOpen] = useState(false);
  const onOpenChange = async (open: boolean) => {
    if (!open || type === 'add') return;
    const { roleIds } = await UserController.getDetailsApi(value?.userId);
    const [roleId] = roleIds || [];
    form.setFieldValue('roleIds', roleId);
  };

  return (
    <>
      {React.cloneElement(trigger, {
        async onClick() {
          setOpen(true);
        },
      })}
      <ModalForm<ModalFormProps & { password2: string }>
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        layout="horizontal"
        title={title}
        form={form}
        autoFocusFirstInput
        modalProps={{
          destroyOnClose: true,
          onCancel: () => setOpen(false),
        }}
        open={open}
        submitTimeout={2000}
        onOpenChange={onOpenChange}
        onFinish={async (values) => {
          const {
            roleIds,
            // eslint-disable-next-line @typescript-eslint/no-unused-vars
            password2,
            appId,
            medicalWorkersId = '',
            userType = '',
            sex = '',
            ...restValues
          } = values;

          const { label: medicalWorkersName = '' } =
            docList.find((item) => item.value === medicalWorkersId) || {};
          const params = {
            ...restValues,
            medicalWorkersId,
            medicalWorkersName,
            roleIds: roleIds ? [roleIds] : [],
            userType,
            sex,
          };
          if (type === 'add') {
            await UserController.addApi(params);
          } else if (type === 'update') {
            await UserController.updateApi({
              ...params,
              userId: value?.userId,
            });
          }
          message.success('提交成功');
          onOk();
          setOpen(false);
        }}
      >
        <ProFormText
          name="nickName"
          label="用户昵称"
          initialValue={value?.nickName}
          rules={[{ required: true }]}
        />
        <ProFormText
          name="phonenumber"
          label="手机号码"
          initialValue={value?.phonenumber}
          rules={[
            {
              validator: async (rule, value = '') => {
                if (value && !/^[0-9]{11}$/.test(value)) {
                  throw new Error('请输入11位数字组成的有效手机号码');
                }
              },
            },
          ]}
        />
        <ProFormText name="email" label="邮箱" initialValue={value?.email} />
        <ProFormText
          name="userName"
          label="用户名称"
          initialValue={value?.userName}
          required
          rules={[
            {
              validator: async (rule, value = '') => {
                if (!/^[a-zA-Z0-9_]{4,30}$/.test(value)) {
                  throw new Error(
                    '请输入4-30位字符，只能包含英文字母、数字和下划线',
                  );
                }
              },
            },
          ]}
        />
        {type === 'add' && (
          <>
            <ProFormText.Password
              name="password"
              label="密码"
              required
              rules={[
                {
                  validator: async (rule, value = '') => {
                    if (!validator.isPass(value)) {
                      throw new Error(
                        '请输入8-18位字符，包含大小写字母、数字、特殊字符四者组合',
                      );
                    }
                  },
                },
              ]}
            />
            <ProFormText.Password
              name="password2"
              label="确认密码"
              required
              rules={[
                {
                  validator: async (rule, value) => {
                    if (form.getFieldValue('password') !== value) {
                      throw new Error('密码不一致');
                    }
                  },
                },
              ]}
            />
          </>
        )}
        <ProFormSelect
          options={OPTIONS.OPTIONS_SEX}
          name="sex"
          label="性别"
          initialValue={value?.sex}
        />
        <ProFormSelect
          name="userType"
          label="用户类别"
          initialValue={value?.userType}
          options={OPTIONS.OPTIONS_USER}
        />
        <ProFormRadio.Group
          label="状态"
          name="status"
          initialValue={value?.status || '1'}
          options={OPTIONS.OPTIONS_AVAILABLE}
        />
        <ProFormSelect
          name="medicalWorkersId"
          label="医护信息"
          showSearch
          initialValue={value?.medicalWorkersId}
          options={docList.map((item) => {
            const { label = '', idno = '', value } = item;
            return {
              label: `${label} - ${idno}`,
              value,
            };
          })}
        />
        <ProFormSelect
          name="roleIds"
          label="关联角色"
          showSearch
          options={roleList}
        />
        <ProFormTextArea
          label="备注"
          name="remark"
          initialValue={value?.remark}
        />
      </ModalForm>
    </>
  );
};

export default EditForm;
