import { Input, message } from 'antd'; import _ from 'lodash'; import { useCallback, useState } from 'react'; import { useIntl } from 'umi'; import DynamicForm from '../DynamicForm'; import AddSelect from './select'; import { useControllableValue } from 'ahooks'; const messageLocaleKey = { addTagValTips: '请选择标签名称', tagName: '标签名称', tagNameAddName: '添加标签名称', tagVal: '标签值', tagValAddName: '添加标签值', }; export interface TagRuleValue { tag_id?: number; tag_name?: string; tag_value?: string; } export interface TagRuleOptions { label: string; value: string | number; disabled?: boolean; children?: TagRuleOptions[]; } export interface TagRuleSelectProps { options: TagRuleOptions[]; value?: TagRuleValue[]; onChange?: (val: TagRuleValue[]) => void; } const TagRuleSelect = (props: TagRuleSelectProps) => { const { options: parentOps } = props; const [options, setOptions] = useState(parentOps || []); const [value, onChange] = useControllableValue(props); const { formatMessage } = useIntl(); const addTagNameHandler = useCallback( (inputVal: string): boolean => { setOptions([ ...options, { label: inputVal, value: inputVal, children: [], }, ]); return true; }, [options], ); const addTagValHandler = useCallback( (inputVal: string, item: TagRuleValue): boolean => { const o = options.find((v) => v.value === item?.tag_name); if (!o) { message.warn(formatMessage({ id: messageLocaleKey.addTagValTips })); return false; } const newOp = { label: inputVal, value: -Number(_.uniqueId()) }; o.children = [...(o.children || []), newOp]; setOptions([...options]); return true; }, [formatMessage, options], ); return ( { const res = vals.map((item) => { if (item?.tag_id && item?.tag_name) { const tagValOptions = options?.find((v) => v.value === item?.tag_name)?.children || []; item.tag_value = tagValOptions.find((v) => v.value === item?.tag_id)?.label; } return item; }); return res; }} > {(item: TagRuleValue) => { const tagValOptions = options?.find((v) => v.value === item?.tag_name)?.children || []; return ( addTagValHandler(v, item)} name={'tag_id'} rules={[{ required: true }]} /> ); }} ); }; export default TagRuleSelect;