import { FC, useEffect, useState } from "react";
import { Form, Modal, ModalProps, Select } from "antd";
import { getManageUserListApi, saveManageRoleGroupApi } from "@/api";
import { IManageDeptItem, IManageUserItem } from "@/types";

export interface AddGroupModalProps extends Omit<ModalProps, "onOk"> {
  assessId: number | string;
  item?: null | IManageDeptItem;
  onCancel?: () => void;
  onOk?: () => void;
}

export const AddGroupModal: FC<AddGroupModalProps> = ({
  assessId,
  open,
  item,
  onOk,
  onCancel,
  ...rest
}) => {
  const [form] = Form.useForm<any>();
  const [loading, setLoading] = useState(false);
  const [userLoading, setUserLoading] = useState(false);
  const [userList, setUserList] = useState<IManageUserItem[]>([]);

  const getUserList = async () => {
    try {
      setUserLoading(true);
      const data = await getManageUserListApi();
      setUserList(data);
    } finally {
      setUserLoading(false);
    }
  };

  const handleCancel = () => {
    form.resetFields();
    onCancel?.();
  };

  const handleConfirm = () => {
    form.submit();
  };

  const handleSubmit = async (values: any) => {
    try {
      setLoading(true);
      await saveManageRoleGroupApi({
        assessId: Number(assessId),
        userIds: values.crewUserIds?.join(","),
      });
      onOk?.();
      handleCancel();
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (open) {
      !userList.length && getUserList();

      if (item) {
        const crewUserIds = item.crewUserIds.split(",").map((i) => Number(i));
        form.setFieldsValue({
          ...item,
          crewUserIds,
        });
      }
    }
  }, [open, item, userList]);

  return (
    <Modal
      title={item ? "编辑评定组" : "新增评定组"}
      okText="提交"
      cancelText="取消"
      maskClosable={false}
      open={open}
      width={640}
      okButtonProps={{
        disabled: loading,
      }}
      onOk={handleConfirm}
      onCancel={handleCancel}
      {...rest}
    >
      <Form
        labelCol={{ span: 4, offset: 2 }}
        form={form}
        onFinish={handleSubmit}
      >
        <Form.Item label="用户" name="crewUserIds">
          <Select
            mode="multiple"
            placeholder="请选择"
            loading={userLoading}
            options={userList}
            fieldNames={{ label: "realName", value: "id" }}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};
