530 lines
18 KiB
TypeScript
530 lines
18 KiB
TypeScript
import { Component, type ChangeEvent, type MouseEvent } from 'react';
|
||
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<string, unknown>;
|
||
name?: string;
|
||
label?: string | false;
|
||
onChange?: (value: string | string[] | undefined) => void;
|
||
multiple?: boolean;
|
||
delimiter?: string;
|
||
mode?: 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<string, string>;
|
||
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<BootstrapData> } })?.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<string, Option>();
|
||
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 selectedValues(event: ChangeEvent<HTMLSelectElement>): string[] {
|
||
return Array.from(event.currentTarget.selectedOptions).map((option) => option.value);
|
||
}
|
||
|
||
export class UserTransferPicker extends Component<UserTransferPickerProps, UserTransferPickerState> {
|
||
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.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;
|
||
}
|
||
try {
|
||
const resp = await http.get('/api/user-select/resolve', {
|
||
params: { mode: this.mode(), ids: ids.join(this.delimiter()) },
|
||
});
|
||
const resolved = dedupeOptions(getOptions(resp));
|
||
const byValue = new Map(resolved.map((item) => [optionKey(item.value), item]));
|
||
this.setState({
|
||
labels: ids.map((id) => byValue.get(optionKey(id)) ?? { label: id.trim(), value: id }),
|
||
});
|
||
} catch {
|
||
this.setState({ labels: ids.map((id) => ({ label: id.trim(), value: id })) });
|
||
}
|
||
}
|
||
|
||
private async loadBootstrap() {
|
||
const resp = await http.get('/api/user-select/bootstrap', { params: { mode: this.mode() } });
|
||
const data = getBootstrap(resp);
|
||
this.setState((current) => ({
|
||
bootstrap: data,
|
||
selectedGroup: {
|
||
...current.selectedGroup,
|
||
depart: current.selectedGroup.depart || '',
|
||
positionType: current.selectedGroup.positionType
|
||
|| (data.positionTypes[0] ? `positionType:${data.positionTypes[0].value}` : ''),
|
||
category: current.selectedGroup.category
|
||
|| (data.categories[0] ? `category:${data.categories[0].value}` : ''),
|
||
},
|
||
}));
|
||
}
|
||
|
||
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;
|
||
this.setState({
|
||
open: true,
|
||
draft: this.state.labels,
|
||
availableSearch: '',
|
||
selectedSearch: '',
|
||
groupSearch: '',
|
||
leftPicked: [],
|
||
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<HTMLButtonElement>) => {
|
||
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 {
|
||
disabled,
|
||
readOnly,
|
||
placeholder = '请选择',
|
||
clearable = true,
|
||
} = this.props;
|
||
const {
|
||
activePane,
|
||
availableSearch,
|
||
selectedSearch,
|
||
groupSearch,
|
||
selectedGroup,
|
||
leftPicked,
|
||
rightPicked,
|
||
draft,
|
||
labels,
|
||
loading,
|
||
open,
|
||
} = this.state;
|
||
|
||
const currentGroups = this.currentGroups();
|
||
const filteredGroups = filterOptions(currentGroups, groupSearch);
|
||
const availableWithoutSelected = this.availableWithoutSelected();
|
||
const selectedFiltered = filterOptions(draft, selectedSearch);
|
||
const displayText = labels.length > 0 ? labels.map((item) => item.label).join(', ') : placeholder;
|
||
|
||
return (
|
||
<>
|
||
<div
|
||
className={`eip4-user-transfer-control${disabled || readOnly ? ' is-disabled' : ''}${labels.length ? '' : ' is-empty'}`}
|
||
onClick={this.openDialog}
|
||
role="button"
|
||
tabIndex={disabled || readOnly ? -1 : 0}
|
||
>
|
||
<span className="eip4-user-transfer-text">{displayText}</span>
|
||
{clearable && labels.length > 0 && !disabled && !readOnly ? (
|
||
<button type="button" onClick={this.clearValue} aria-label="清空">
|
||
×
|
||
</button>
|
||
) : null}
|
||
<span className="eip4-user-transfer-icon" aria-hidden="true" />
|
||
</div>
|
||
|
||
{open ? (
|
||
<div className="eip4-user-transfer-mask" onMouseDown={(event) => {
|
||
if (event.target === event.currentTarget) this.closeDialog();
|
||
}}
|
||
>
|
||
<div className="eip4-user-transfer-dialog">
|
||
<div className="eip4-user-transfer-head">
|
||
<h3>用户选择框</h3>
|
||
<button type="button" onClick={this.closeDialog}>×</button>
|
||
</div>
|
||
<div className="eip4-user-transfer-body">
|
||
<section className="eip4-user-transfer-panel">
|
||
<div className="eip4-user-transfer-title">-可选项-</div>
|
||
<div className="eip4-user-transfer-tabs">
|
||
{this.panes().map((pane) => (
|
||
<button
|
||
type="button"
|
||
key={pane.key}
|
||
className={activePane === pane.key ? 'is-active' : ''}
|
||
onClick={() => this.changePane(pane.key)}
|
||
>
|
||
{pane.label}
|
||
</button>
|
||
))}
|
||
</div>
|
||
{currentGroups.length > 0 ? (
|
||
<div className="eip4-user-transfer-group">
|
||
<input
|
||
value={groupSearch}
|
||
onChange={(event) => this.setState({ groupSearch: event.target.value })}
|
||
placeholder={activePane === 'depart' ? '搜索公司或部门' : '搜索分类'}
|
||
/>
|
||
<select
|
||
value={selectedGroup[activePane] || ''}
|
||
onChange={(event) => this.setGroupValue(event.target.value)}
|
||
>
|
||
<option value="">
|
||
{activePane === 'depart' ? '下拉选择一个公司或部门' : '下拉选择一个分类'}
|
||
</option>
|
||
{filteredGroups.map((item) => (
|
||
<option key={item.value} value={item.value}>{item.label}</option>
|
||
))}
|
||
</select>
|
||
</div>
|
||
) : null}
|
||
<input
|
||
className="eip4-user-transfer-search"
|
||
value={availableSearch}
|
||
onChange={(event) => this.setAvailableSearch(event.target.value)}
|
||
placeholder="输入关键字过滤可选项"
|
||
/>
|
||
<select
|
||
multiple
|
||
className="eip4-user-transfer-list"
|
||
value={leftPicked}
|
||
onChange={(event) => this.setState({ leftPicked: selectedValues(event) })}
|
||
onDoubleClick={this.addPicked}
|
||
>
|
||
{availableWithoutSelected.map((item) => (
|
||
<option key={optionKey(item.value)} value={optionKey(item.value)}>{item.label}</option>
|
||
))}
|
||
</select>
|
||
<div className="eip4-user-transfer-count">
|
||
{loading ? '加载中...' : `共${availableWithoutSelected.length}条`}
|
||
</div>
|
||
</section>
|
||
|
||
<div className="eip4-user-transfer-actions">
|
||
<button type="button" onClick={this.addPicked} disabled={leftPicked.length === 0}>></button>
|
||
<button type="button" onClick={this.removePicked} disabled={rightPicked.length === 0}><</button>
|
||
<button type="button" onClick={this.addAll} disabled={availableWithoutSelected.length === 0}>>></button>
|
||
<button type="button" onClick={this.removeAll} disabled={draft.length === 0}><<</button>
|
||
</div>
|
||
|
||
<section className="eip4-user-transfer-panel">
|
||
<div className="eip4-user-transfer-title">-已选项-</div>
|
||
<input
|
||
className="eip4-user-transfer-search"
|
||
value={selectedSearch}
|
||
onChange={(event) => this.setState({ selectedSearch: event.target.value })}
|
||
placeholder="输入关键字可过滤已选项"
|
||
/>
|
||
<select
|
||
multiple
|
||
className="eip4-user-transfer-list"
|
||
value={rightPicked}
|
||
onChange={(event) => this.setState({ rightPicked: selectedValues(event) })}
|
||
onDoubleClick={this.removePicked}
|
||
>
|
||
{selectedFiltered.map((item) => (
|
||
<option key={optionKey(item.value)} value={optionKey(item.value)}>{item.label}</option>
|
||
))}
|
||
</select>
|
||
<div className="eip4-user-transfer-count">共{draft.length}条</div>
|
||
</section>
|
||
</div>
|
||
<div className="eip4-user-transfer-foot">
|
||
<button type="button" className="primary" onClick={this.commit}>确认</button>
|
||
<button type="button" onClick={this.closeDialog}>取消</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
) : null}
|
||
</>
|
||
);
|
||
}
|
||
}
|