fms/components/elements/commands/elements/options/index.tsx
2023-01-27 16:57:28 +07:00

71 lines
2.6 KiB
TypeScript

import styles from './styles.module.css'
import Option from '../option'
import {useContext, useEffect, useState} from "react";
import Context, {ContextInterface} from "../command/context";
import {Select, OutlinedInput, FormControl, MenuItem, Checkbox, ListItemText} from "@mui/material";
import {OptionInterface} from "../../../../../api/sm/responses/comamnds";
interface OptionsInterface {
optionList: OptionInterface[]
}
export default function Options({optionList}: OptionsInterface) {
let {optionList: ol, setOptionList} = useContext<ContextInterface>(Context)
let [selectedOptions, setSelectedOptions] = useState<OptionInterface[]>([]);
let [selectedValues, setSelectedValues] = useState<string[]>(Object.keys(ol) || []);
useEffect(() => {
let result: OptionInterface[] = [];
optionList.forEach((value, index, array) => {
let check = selectedValues.find(item => item === value.name)
check && result.push(value)
})
setSelectedOptions(result)
let temp: any = {}
optionList.forEach((value, index, array) => {
let check = selectedValues.find(item => item === value.name)
check && (temp[value.name] = value.acceptValue ? '' : true)
})
setOptionList(temp)
}, [selectedValues]);
if (!optionList.length) {
return <></>
}
const handleChange = (event: any) => {
const { target: { value }} = event
setSelectedValues(typeof value === 'string' ? value.split(',') : value)
};
return (
<>
{optionList.length > 0 &&
<>
<Select
value={selectedValues}
label="Options"
multiple
displayEmpty
onChange={handleChange}
input={<OutlinedInput />}
renderValue={(selectedValues) => `Options`}
size="small"
>
{optionList.map((option: OptionInterface, index: number) => (
<MenuItem key={index} value={option.name}>
<Checkbox checked={selectedValues.indexOf(option.name) > -1} />
<ListItemText primary={option.name} />
</MenuItem>
))}
</Select>
&nbsp;
</>}
{selectedOptions.map((option: OptionInterface, index: number) => (
<Option key={index} {...option} />
))}
</>
)
}