AddModal.tsx 6.98 KB
import { RESPONSE_CODE } from '@/constants/enum';
import {
  postResearchGroupsAccessAddBlackList,
  postResearchGroupsAccessAddWhiteList,
  postResearchGroupsList,
  postResearchGroupsNameSet,
} from '@/services';
import { Form, Input, Modal, Select, message } from 'antd';
import { forwardRef, useImperativeHandle, useState } from 'react';

import '../index.css';

export type AddModalProps = {
  setVisible: (visible: boolean) => void;
};

export type AddModalRef = {
  show: (accessType: 'WHITELIST' | 'BLACKLIST', onSuccess: () => void) => void;
};

const AddModal = forwardRef<AddModalRef, AddModalProps>((props, ref) => {
  const { setVisible } = props;
  const [form] = Form.useForm();
  const [visible, setModalVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const [accessTypeState, setAccessTypeState] = useState<
    'WHITELIST' | 'BLACKLIST'
  >('WHITELIST');
  const [onSuccessCallback, setOnSuccessCallback] = useState<() => void>(
    () => {},
  );
  const [groupOptions, setGroupOptions] = useState<
    { label: string; value: string; id: string }[]
  >([]);
  const [companyOptions, setCompanyOptions] = useState<
    { label: string; value: string; id: string }[]
  >([]);
  const [searchLoading, setSearchLoading] = useState(false);
  const [companyLoading, setCompanyLoading] = useState(false);

  useImperativeHandle(ref, () => ({
    show: (accessType, onSuccess) => {
      form.resetFields();
      setAccessTypeState(accessType);
      setOnSuccessCallback(() => onSuccess);
      setModalVisible(true);
      // 重置选项
      setCompanyOptions([]);
      setGroupOptions([]);
    },
  }));

  const handleCancel = () => {
    setModalVisible(false);
    setVisible(false);
  };

  const handleOk = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      const requestData = {
        ...values,
        accessType: accessTypeState,
      };

      let res;
      if (accessTypeState === 'WHITELIST') {
        res = await postResearchGroupsAccessAddWhiteList({ data: requestData });
      } else {
        res = await postResearchGroupsAccessAddBlackList({ data: requestData });
      }

      if (res && res.result === RESPONSE_CODE.SUCCESS) {
        message.success('添加成功');
        setModalVisible(false);
        setVisible(false);
        onSuccessCallback();
      } else {
        message.error(res?.message || '添加失败');
      }
    } catch (error) {
      console.error('验证表单失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 搜索课题组
  const handleSearch = async (value: string) => {
    if (!value) return;

    try {
      setSearchLoading(true);
      // 完全模仿原始代码,使用data包裹参数
      const res = await postResearchGroupsNameSet({
        data: { status: 'ADD_AUDIT_PASS', groupName: value },
      });

      if (res?.data) {
        const options = Object.entries(res.data).map(
          ([researchGroupsId, researchGroupsName]) => ({
            label: researchGroupsName as string,
            value: researchGroupsName as string,
            key: researchGroupsId,
            id: researchGroupsId,
          }),
        );
        setGroupOptions(options);
      }
    } catch (error) {
      console.error('获取课题组列表失败', error);
    } finally {
      setSearchLoading(false);
    }
  };

  // 根据课题组名称查询单位名称列表
  const fetchCompanyNamesByGroupName = async (groupName: string) => {
    if (!groupName) return;

    try {
      setCompanyLoading(true);
      // 使用postResearchGroupsList接口查询单位名称
      const res = await postResearchGroupsList({
        data: {
          current: 1,
          pageSize: 100,
          groupName: groupName,
        },
      });

      if (res?.data?.data) {
        // 提取所有相同groupName的不同companyName
        const companySet = new Set<string>();
        const companyIdMap = new Map<string, string>();

        res.data.data.forEach((item: any) => {
          if (item.groupName === groupName && item.companyName) {
            companySet.add(item.companyName);
            companyIdMap.set(item.companyName, item.id); // 保存id用于提交
          }
        });

        // 转换为选项格式
        const companies = Array.from(companySet).map((name) => ({
          label: name,
          value: name,
          id: companyIdMap.get(name) || '',
        }));
        setCompanyOptions(companies);
        // 如果只有一个选项,自动选中
        if (companies.length === 1) {
          form.setFieldsValue({
            companyName: companies[0].value,
            groupId: companies[0].id,
          });
        }
      }
    } catch (error) {
      console.error('获取单位名称列表失败', error);
    } finally {
      setCompanyLoading(false);
    }
  };

  const title =
    accessTypeState === 'WHITELIST' ? '添加课题组白名单' : '添加课题组风险名单';

  return (
    <Modal
      title={title}
      open={visible}
      onOk={handleOk}
      onCancel={handleCancel}
      confirmLoading={loading}
      maskClosable={true}
      destroyOnClose
    >
      <Form form={form} layout="vertical" name="add_form" initialValues={{}}>
        <Form.Item name="groupId" style={{ display: 'none' }}>
          <Input type="hidden" />
        </Form.Item>

        <Form.Item
          name="groupName"
          label="课题组名称"
          rules={[{ required: true, message: '请输入课题组名称!' }]}
        >
          <Select
            showSearch
            placeholder="请输入名称"
            filterOption={false}
            onSearch={handleSearch}
            loading={searchLoading}
            options={groupOptions}
            onChange={(value, option: any) => {
              // 清空公司选项
              form.setFieldsValue({
                companyName: undefined,
              });

              // 保存研究组ID
              if (option) {
                form.setFieldsValue({
                  groupId: option.id || '',
                });

                // 触发查询关联的单位名称
                fetchCompanyNamesByGroupName(value);
              }
            }}
          />
        </Form.Item>

        <Form.Item
          name="companyName"
          label="单位名称"
          rules={[{ required: true, message: '请选择单位名称' }]}
        >
          <Select
            placeholder="请选择单位名称"
            loading={companyLoading}
            options={companyOptions}
            disabled={companyOptions.length === 0}
            onChange={(_, option: any) => {
              if (option && option.id) {
                form.setFieldsValue({
                  groupId: option.id,
                });
              }
            }}
          />
        </Form.Item>

        <Form.Item name="remark" label="添加原因">
          <Input.TextArea rows={3} placeholder="请输入添加原因" />
        </Form.Item>
      </Form>
    </Modal>
  );
});

export default AddModal;