import { Component, type ChangeEvent, type CSSProperties, type MouseEvent } from 'react'; import { createPortal } from 'react-dom'; import { http } from '../api/http'; const ALL_VALUE = 'ALL '; type Option = { label: string; value: string; type?: string; groupKind?: string; groupId?: string; }; type PickerValue = string | string[] | Option | Option[] | null | undefined; type BootstrapData = { departGroups: Option[]; positionTypes: Option[]; categories: Option[]; allUsers?: Option[]; orgs?: Option[]; departs?: Option[]; }; type PaneKey = | 'all' | 'depart' | 'positionType' | 'category' | 'allUsers' | 'orgs' | 'departs' | 'positionTypes'; type UserTransferPickerProps = { value?: PickerValue; defaultValue?: PickerValue; data?: Record; name?: string; label?: string | false; className?: string; style?: CSSProperties; onChange?: (value: string | string[] | undefined) => void; multiple?: boolean; delimiter?: string; mode?: string; userSelectMode?: string; disabled?: boolean; readOnly?: boolean; placeholder?: string; clearable?: boolean; }; type UserTransferPickerState = { open: boolean; labels: Option[]; draft: Option[]; bootstrap: BootstrapData; activePane: PaneKey; available: Option[]; availableSearch: string; selectedSearch: string; groupSearch: string; selectedGroup: Record; leftPicked: string[]; rightPicked: string[]; loading: boolean; }; const BASE_PANES: Array<{ key: PaneKey; label: string }> = [ { key: 'all', label: '全部人员' }, { key: 'depart', label: '按公司、部门选择人员' }, { key: 'positionType', label: '按岗位类别选择人员' }, { key: 'category', label: '按用户类别选择人员' }, ]; const ORG_PANES: Array<{ key: PaneKey; label: string }> = [ { key: 'allUsers', label: '全体人员' }, { key: 'orgs', label: '选择公司' }, { key: 'departs', label: '选择部门' }, { key: 'positionTypes', label: '选择岗位类别' }, ]; function optionKey(value: string): string { return value.trim().toUpperCase() === 'ALL' ? ALL_VALUE : value; } function normalizeValue(value: PickerValue, delimiter: string): string[] { if (Array.isArray(value)) { return value .map((item) => (typeof item === 'string' ? item : item?.value)) .filter((item): item is string => Boolean(item)) .map(optionKey); } if (typeof value === 'object' && value?.value) { return [optionKey(String(value.value))]; } if (typeof value !== 'string' || value.length === 0) { return []; } return value .split(delimiter) .map((item) => item.trim()) .filter(Boolean) .map(optionKey); } function getOptions(payload: unknown): Option[] { const data = (payload as { data?: { data?: { options?: Option[]; items?: Option[] } } })?.data?.data; return data?.options ?? data?.items ?? []; } function getBootstrap(payload: unknown): BootstrapData { const data = (payload as { data?: { data?: Partial } })?.data?.data ?? {}; return { departGroups: data.departGroups ?? [], positionTypes: data.positionTypes ?? [], categories: data.categories ?? [], allUsers: data.allUsers ?? [], orgs: data.orgs ?? [], departs: data.departs ?? [], }; } function dedupeOptions(items: Option[]): Option[] { const map = new Map(); for (const item of items) { map.set(optionKey(item.value), { ...item, value: optionKey(item.value) }); } return Array.from(map.values()); } function filterOptions(items: Option[], keyword: string): Option[] { const q = keyword.trim().toLowerCase(); if (!q) return items; return items.filter((item) => `${item.label} ${item.value}`.toLowerCase().includes(q)); } function looksLikeRawId(value: string): boolean { const text = value.trim(); return /^[0-9a-f]{32}$/i.test(text) || /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(text) || (text.length >= 24 && /^[0-9a-f-]+$/i.test(text)); } function fallbackLabel(id: string, index: number): string { const text = id.trim(); return looksLikeRawId(text) ? `已选人员${index + 1}` : text; } function chunksByLength(ids: string[], delimiter: string, maxLength = 1400): string[][] { const chunks: string[][] = []; let current: string[] = []; let currentLength = 0; for (const id of ids) { const nextLength = currentLength + id.length + (current.length ? delimiter.length : 0); if (current.length > 0 && nextLength > maxLength) { chunks.push(current); current = []; currentLength = 0; } current.push(id); currentLength += id.length + (current.length > 1 ? delimiter.length : 0); } if (current.length > 0) chunks.push(current); return chunks; } function displayTextFor(items: Option[], placeholder: string): string { if (items.length === 0) return placeholder; const labels = items.map((item) => item.label.trim()).filter(Boolean); if (labels.length === 0) return placeholder; if (labels.every(looksLikeRawId)) { return labels.length === 1 ? '已选择 1 人' : `已选择 ${labels.length} 人`; } const previewSize = 6; const preview = labels.slice(0, previewSize).join(', '); return labels.length > previewSize ? `${preview} 等 ${labels.length} 人` : preview; } function selectedValues(event: ChangeEvent): string[] { return Array.from(event.currentTarget.selectedOptions).map((option) => option.value); } export class UserTransferPicker extends Component { override state: UserTransferPickerState = { open: false, labels: [], draft: [], bootstrap: { departGroups: [], positionTypes: [], categories: [] }, activePane: 'all', available: [], availableSearch: '', selectedSearch: '', groupSearch: '', selectedGroup: {}, leftPicked: [], rightPicked: [], loading: false, }; override componentDidMount() { void this.resolveCurrentValue(); } override componentDidUpdate(prevProps: UserTransferPickerProps) { const delimiter = this.delimiter(); const before = normalizeValue(this.effectiveValue(prevProps), delimiter).join('\u0000'); const after = normalizeValue(this.effectiveValue(this.props), delimiter).join('\u0000'); if (before !== after || prevProps.mode !== this.props.mode) { void this.resolveCurrentValue(); } } private delimiter() { return this.props.delimiter ?? ','; } private mode() { return this.props.userSelectMode ?? this.props.mode ?? 'controlled'; } private effectiveValue(props: UserTransferPickerProps = this.props): PickerValue { if (props.value !== undefined) return props.value; if (props.defaultValue !== undefined) return props.defaultValue; if (props.name && props.data && Object.prototype.hasOwnProperty.call(props.data, props.name)) { return props.data[props.name] as PickerValue; } return undefined; } private valueIds() { return normalizeValue(this.effectiveValue(), this.delimiter()); } private panes() { return this.mode() === 'org' ? [...BASE_PANES, ...ORG_PANES] : BASE_PANES; } private async resolveCurrentValue() { const ids = this.valueIds(); if (ids.length === 0) { this.setState({ labels: [] }); return; } const existing = new Map(this.state.labels.map((item) => [optionKey(item.value), item])); try { const resolvedParts: Option[] = []; for (const chunk of chunksByLength(ids, this.delimiter())) { const resp = await http.get('/api/user-select/resolve', { params: { mode: this.mode(), ids: chunk.join(this.delimiter()) }, }); resolvedParts.push(...getOptions(resp)); } const resolved = dedupeOptions(resolvedParts); const byValue = new Map(resolved.map((item) => [optionKey(item.value), item])); this.setState({ labels: ids.map((id, index) => ( byValue.get(optionKey(id)) ?? existing.get(optionKey(id)) ?? { label: fallbackLabel(id, index), value: id } )), }); } catch { this.setState({ labels: ids.map((id, index) => ( existing.get(optionKey(id)) ?? { label: fallbackLabel(id, index), value: id } )), }); } } private async loadBootstrap() { const resp = await http.get('/api/user-select/bootstrap', { params: { mode: this.mode() } }); const data = getBootstrap(resp); await new Promise((resolve) => { this.setState((current) => ({ bootstrap: data, selectedGroup: { ...current.selectedGroup, depart: current.selectedGroup.depart || (data.departGroups[0] ? String(data.departGroups[0].value) : ''), positionType: current.selectedGroup.positionType || (data.positionTypes[0] ? `positionType:${data.positionTypes[0].value}` : ''), category: current.selectedGroup.category || (data.categories[0] ? `category:${data.categories[0].value}` : ''), }, }), resolve); }); } private objectPaneOptions(pane: PaneKey): Option[] { const { bootstrap } = this.state; if (pane === 'allUsers') return bootstrap.allUsers ?? []; if (pane === 'orgs') return bootstrap.orgs ?? []; if (pane === 'departs') return bootstrap.departs ?? []; if (pane === 'positionTypes') return bootstrap.positionTypes ?? []; return []; } private async loadAvailable() { const { activePane, availableSearch, selectedGroup } = this.state; this.setState({ loading: true, leftPicked: [] }); try { if (activePane === 'all') { const resp = await http.get('/api/user-select/search', { params: { mode: this.mode(), term: availableSearch, limit: 500 }, }); this.setState({ available: getOptions(resp) }); return; } if (activePane === 'depart' || activePane === 'positionType' || activePane === 'category') { const group = selectedGroup[activePane]; if (!group) { this.setState({ available: [] }); return; } const resp = await http.get('/api/user-select/group-users', { params: { mode: this.mode(), group, term: availableSearch, limit: 500 }, }); this.setState({ available: getOptions(resp) }); return; } this.setState({ available: filterOptions(this.objectPaneOptions(activePane), availableSearch) }); } finally { this.setState({ loading: false }); } } private currentGroups(): Option[] { const { activePane, bootstrap } = this.state; if (activePane === 'depart') return bootstrap.departGroups; if (activePane === 'positionType') { return bootstrap.positionTypes.map((item) => ({ ...item, value: `positionType:${item.value}` })); } if (activePane === 'category') { return bootstrap.categories.map((item) => ({ ...item, value: `category:${item.value}` })); } return []; } private availableWithoutSelected(): Option[] { const selectedKeys = new Set(this.state.draft.map((item) => optionKey(item.value))); return this.state.available.filter((item) => !selectedKeys.has(optionKey(item.value))); } private openDialog = async () => { if (this.props.disabled || this.props.readOnly) return; const isMultiple = this.props.multiple === true; this.setState({ open: true, draft: this.state.labels, availableSearch: '', selectedSearch: '', groupSearch: '', leftPicked: isMultiple ? [] : this.state.labels.slice(0, 1).map((item) => optionKey(item.value)), rightPicked: [], }, async () => { await this.loadBootstrap(); await this.loadAvailable(); }); }; private closeDialog = () => { this.setState({ open: false }); }; private commit = () => { const selected = dedupeOptions(this.state.draft); const ids = selected.map((item) => optionKey(item.value)); this.setState({ labels: selected, open: false }); if (!this.props.multiple) { this.props.onChange?.(ids[0] || undefined); } else { this.props.onChange?.(ids.join(this.delimiter())); } }; private addOptions(items: Option[]) { const normalized = dedupeOptions(items); if (!this.props.multiple) { this.setState({ draft: normalized.slice(0, 1) }); return; } this.setState((current) => ({ draft: dedupeOptions([...current.draft, ...normalized]) })); } private addPicked = () => { const picked = this.state.available.filter((item) => this.state.leftPicked.includes(optionKey(item.value))); this.addOptions(picked); }; private addAll = () => { this.addOptions(this.availableWithoutSelected()); }; private removePicked = () => { this.setState((current) => ({ draft: current.draft.filter((item) => !current.rightPicked.includes(optionKey(item.value))), rightPicked: [], })); }; private removeAll = () => { this.setState({ draft: [], rightPicked: [] }); }; private clearValue = (event: MouseEvent) => { event.stopPropagation(); this.setState({ labels: [] }); this.props.onChange?.(this.props.multiple ? '' : undefined); }; private changePane = (activePane: PaneKey) => { this.setState({ activePane, availableSearch: '', groupSearch: '', leftPicked: [], }, () => { void this.loadAvailable(); }); }; private setGroupValue = (value: string) => { this.setState((current) => ({ selectedGroup: { ...current.selectedGroup, [current.activePane]: value }, }), () => { void this.loadAvailable(); }); }; private setAvailableSearch = (availableSearch: string) => { this.setState({ availableSearch }, () => { void this.loadAvailable(); }); }; override render() { const { className, disabled, readOnly, placeholder = '请选择', clearable = true, style, } = this.props; const { activePane, availableSearch, selectedSearch, groupSearch, selectedGroup, leftPicked, rightPicked, draft, labels, loading, open, } = this.state; const isMultiple = this.props.multiple === true; const currentGroups = this.currentGroups(); const filteredGroups = filterOptions(currentGroups, groupSearch); const availableWithoutSelected = this.availableWithoutSelected(); const availableOptions = isMultiple ? availableWithoutSelected : this.state.available; const selectedFiltered = filterOptions(draft, selectedSearch); const displayText = displayTextFor(labels, placeholder); const fullTitle = labels.map((item) => item.label).join(', '); const controlClassName = [ className, 'eip4-user-transfer-control', disabled || readOnly ? 'is-disabled' : '', labels.length ? '' : 'is-empty', ].filter(Boolean).join(' '); const dialog = open ? (
{ if (event.target === event.currentTarget) this.closeDialog(); }} >

{isMultiple ? '用户选择框' : '选择用户'}

-可选项-
{this.panes().map((pane) => ( ))}
{currentGroups.length > 0 ? (
this.setState({ groupSearch: event.target.value })} placeholder={activePane === 'depart' ? '搜索公司或部门' : '搜索分类'} />
) : null} this.setAvailableSearch(event.target.value)} placeholder="输入关键字过滤可选项" />
{loading ? '加载中...' : `共${availableOptions.length}条`}
{isMultiple ? ( <>
-已选项-
this.setState({ selectedSearch: event.target.value })} placeholder="输入关键字可过滤已选项" />
共{draft.length}条
) : null}
) : null; return ( <>
{displayText} {clearable && labels.length > 0 && !disabled && !readOnly ? ( ) : null}
{dialog && typeof document !== 'undefined' ? createPortal(dialog, document.body) : dialog} ); } }