asb_cloud_front/src/components/WellTreeSelector.jsx

81 lines
2.0 KiB
React
Raw Normal View History

import { useState, useEffect } from 'react'
2021-05-28 12:04:50 +05:00
import { useParams } from 'react-router-dom'
import { WellService } from '../services/api'
import Loader from '../components/Loader'
import { TreeSelect } from 'antd'
import { useHistory } from 'react-router-dom'
const groupBy = (table, ...keys) => {
let key = keys[0]
let groups = table.reduce((rv, item) => {
let keyValue = item[key]
let group = rv.find(o => o.title === keyValue)
if (!group) {
group = {
title: keyValue,
value: keys.length === 1 ? `${item['id']}` : `${key} ${keyValue} ${item['id']}`,
selectable: keys.length === 1,
children: []
}
rv.push(group)
}
if (keys.length > 1)
group.children.push(item);
return rv;
}, []);
if (keys.length > 1) {
for (let group of groups) {
group.children = groupBy(group.children, ...keys.slice(1))
}
}
return groups
};
export default function WellTreeSelector(props) {
// const [wells, setWells] = useState([])
const [wellsTree, setWellsTree] = useState([])
const [loader, setLoader] = useState(false)
const history = useHistory()
2021-05-28 12:04:50 +05:00
let { id } = useParams();
let updateWellsList = async () => {
setLoader(true)
try {
let newWells = (await WellService.getWells()).map(w => { return { key: w.id, ...w } })
let wellsTree = groupBy(newWells, 'deposit', 'cluster', 'caption')
setWellsTree(wellsTree)
}
catch (e) {
2021-05-31 15:10:35 +05:00
console.error(`${e.message}`);
}
setLoader(false)
}
useEffect(() => { updateWellsList() }, [])
const onSelect = (value) => {
if (value)
history.push(`/well/${value}/`);
console.log(value)
}
return (
<>
<TreeSelect
className='header-tree-select'
bordered={false}
dropdownMatchSelectWidth={false}
placeholder='Выберите месторождение'
treeData={wellsTree}
treeDefaultExpandAll
onSelect={onSelect}
2021-05-28 12:04:50 +05:00
value = {id}
/>
{loader && <Loader />}
</>
)
}