/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
import React, {
forwardRef,
useEffect,
useImperativeHandle,
useRef,
useState,
} from 'react';
import { Alert, Button, Select } from 'antd';
import { useTranslation } from 'react-i18next';
import {
createRequestGeneration,
mergeIdentityOptions,
identityOptionLabel,
} from './latestTiers';
const RemoteIdentitySelect = forwardRef(function RemoteIdentitySelect(
{ type, value, onChange, fetchJSON },
ref,
) {
const { t } = useTranslation();
const gate = useRef(createRequestGeneration());
const timer = useRef();
const [query, setQuery] = useState('');
const [state, setState] = useState({
items: [],
total: 0,
page: 0,
busy: false,
error: '',
});
const selected = useRef(null);
const active = useRef(true);
useImperativeHandle(
ref,
() => ({
invalidate() {
active.current = false;
gate.current.next();
clearTimeout(timer.current);
},
}),
[],
);
const load = async (q, page, generation) => {
setState((old) => ({ ...old, busy: true, error: '' }));
try {
const result = await fetchJSON(
`/api/commission/v2/options/${type === 'company' ? 'organizations' : 'users'}?${new URLSearchParams({ q, p: String(page), page_size: '20' })}`,
);
if (!gate.current.current(generation)) return;
setState((old) => ({
items: mergeIdentityOptions(
page === 1 ? [] : old.items,
result.items || [],
selected.current,
),
total: result.total,
page,
busy: false,
error: '',
}));
} catch (error) {
if (gate.current.current(generation))
setState((old) => ({ ...old, busy: false, error: error.message }));
}
};
const search = (q) => {
clearTimeout(timer.current);
const generation = gate.current.next();
setQuery(q);
setState({
items: selected.current ? [selected.current] : [],
total: 0,
page: 0,
busy: true,
error: '',
});
timer.current = setTimeout(() => load(q, 1, generation), 300);
};
useEffect(() => {
active.current = true;
search('');
return () => {
active.current = false;
// 卸载时作废进行中的请求(原有逻辑)。
// eslint-disable-next-line react-hooks/exhaustive-deps
gate.current.next();
clearTimeout(timer.current);
};
// 仅在类型或数据源变化时重新搜索(原有逻辑,依赖为有意设置)。
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [type, fetchJSON]);
const selectIdentity = (id) => {
if (!active.current) return;
selected.current = state.items.find((item) => item.id === id) || null;
onChange(id);
};
return (