import React, { useState, useEffect } from 'react';
|
import { useCreateContext, useTranslate, useRecordContext } from 'react-admin'
|
import { Autocomplete, TextField, FormControl } from '@mui/material';
|
import request from '@/utils/request';
|
import * as Common from '@/utils/common';
|
import { useFormContext } from 'react-hook-form';
|
|
const TreeSelectInput = ({ resource, required, onChange, label, source = 'parentId', value, isTranslate = false, ...rest }) => {
|
const translate = useTranslate();
|
const form = useFormContext();
|
const [filter, setFilter] = React.useState("");
|
const [treeData, setTreeData] = React.useState([]);
|
|
const [proxyVal, setProxyVal] = React.useState('');
|
|
const record = useRecordContext()
|
const val = value || record?.[source];
|
|
useEffect(() => {
|
const http = async (resource) => {
|
const res = await request.post(resource + '/tree', {
|
condition: filter
|
});
|
if (res?.data?.code === 200) {
|
// Add a null option at the beginning
|
const flatTree = Common.flattenTree(res.data.data);
|
setTreeData([{ id: 0, name: ' ' }, ...flatTree]);
|
setProxyVal(val);
|
} else {
|
notify(res.data.msg);
|
}
|
}
|
http(resource);
|
}, [filter, value]);
|
|
const handleChange = (event, newValue) => {
|
const selectedVal = newValue ? newValue.id : 0;
|
setProxyVal(selectedVal);
|
form?.setValue(source, selectedVal, {
|
shouldValidate: true,
|
shouldDirty: true,
|
});
|
if (onChange) {
|
onChange({ target: { value: selectedVal } })
|
}
|
};
|
|
const validValueObj = treeData.find(item => item.id === (proxyVal || 0)) || null;
|
|
return (
|
<FormControl fullWidth required={required} size="small">
|
<Autocomplete
|
value={validValueObj}
|
onChange={handleChange}
|
options={treeData}
|
getOptionLabel={(option) => isTranslate && option.type === 0 ? translate(option.name) : option.name}
|
isOptionEqualToValue={(option, val) => option.id === val.id}
|
size="small"
|
ListboxProps={{ style: { maxHeight: '300px' } }}
|
renderOption={(props, option) => (
|
<li {...props} style={{ paddingLeft: (option.depth || 0) * 16 + 16 }}>
|
{isTranslate && option.type === 0 ? translate(option.name) : option.name}
|
</li>
|
)}
|
renderInput={(params) => (
|
<TextField
|
{...params}
|
label={translate(label)}
|
variant="filled"
|
required={required}
|
/>
|
)}
|
{...rest}
|
/>
|
</FormControl>
|
);
|
};
|
|
export default TreeSelectInput;
|