import {
  ModalForm,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { Form } from 'antd';
import React, { useState } from 'react';
import { UserController, types } from '../../../services';

interface RoleFormProps {
  title: string;
  trigger: JSX.Element;
  value?: UserController.UserFields;
  roleList: types.SelectOptionFields[];
  onOk: () => void;
}

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

const RoleForm: React.FC<RoleFormProps> = ({
  trigger,
  title,
  value,
  roleList,
  onOk,
}) => {
  const [form] = Form.useForm<ModalFormProps>();
  const [open, setOpen] = useState(false);
  const onOpenChange = async (open: boolean) => {
    if (!open) 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>
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        layout="horizontal"
        title={title}
        open={open}
        form={form}
        autoFocusFirstInput
        modalProps={{
          destroyOnClose: true,
          onCancel: () => setOpen(false),
        }}
        onOpenChange={onOpenChange}
        submitTimeout={2000}
        onFinish={async ({ roleIds }) => {
          const { userId = '' } = value || {};
          await UserController.authRoleApi({
            userId,
            roleIds,
          });
          onOk();
          setOpen(false);
        }}
      >
        <ProFormText
          name="userName"
          label="用户名称"
          disabled
          initialValue={value?.userName}
        />
        <ProFormSelect
          name="roleIds"
          label="关联角色"
          showSearch
          options={roleList}
        />
      </ModalForm>
    </>
  );
};

export default RoleForm;
