import React from 'react';
import { Select, Checkbox, Row, Col, Form, InputNumber } from 'antd';
import PropTypes from 'prop-types';
import styles from './index.less';
export default class InstanceVolume extends React.Component {
static propTypes = {
options: PropTypes.array,
value: PropTypes.any,
minSize: PropTypes.number,
};
static defaultProps = {
options: [],
value: {},
minSize: 0,
};
constructor(props) {
super(props);
const { type, size, deleteType } = props.value || {};
const { minSize } = props;
this.state = {
type,
size,
deleteType,
minSize,
};
}
static getDerivedStateFromProps(nextProps, prevState) {
if (
nextProps.options !== prevState.options ||
nextProps.minSize !== prevState.minSize
) {
const { options, value, minSize } = nextProps;
return {
options,
type: value.type,
minSize,
};
}
return null;
}
componentDidMount() {
this.onChange();
}
checkVolume = (callback) => {
const { type } = this.state;
if (!type) {
this.setState(
{
errorMsg: t('Please select a type!'),
validateStatus: 'error',
},
callback
);
return;
}
this.setState(
{
errorMsg: undefined,
validateStatus: 'success',
},
callback
);
};
onChange = () => {
this.checkVolume(() => {
const { onChange, options = [] } = this.props;
if (onChange) {
const { type, deleteType } = this.state;
const deleteTypeLabel =
deleteType === 1
? t('Delete with the instance')
: t('Do not delete with the instance');
const typeOption = options.find((it) => it.value === type);
const value = {
...this.state,
deleteTypeLabel,
typeOption,
};
onChange(value);
}
});
};
onSelectChange = (value) => {
this.setState(
{
type: value,
},
this.onChange
);
};
onInputChange = (value) => {
this.setState(
{
size: value,
},
this.onChange
);
};
onDeleteChange = () => {
const { deleteType } = this.state;
this.setState(
{
deleteType: 1 - deleteType,
},
this.onChange
);
};
render() {
const {
options,
type,
size,
deleteType,
validateStatus,
errorMsg,
minSize,
} = this.state;
const { name, showDelete = true } = this.props;
const selects = (
<Select
value={type}
options={options}
onChange={this.onSelectChange}
className={styles.select}
placeholder={t('Please select type')}
/>
);
const input = (
<InputNumber
value={size}
onChange={this.onInputChange}
min={minSize}
style={{ maxWidth: '60%' }}
precision={0}
formatter={(value) => `$ ${value}`.replace(/\D/g, '')}
onInput={(e) => this.onInputChange(e * 1)}
/>
);
const deleteValue = deleteType === 1;
const checkbox = showDelete ? (
<Checkbox onChange={this.onDeleteChange} checked={deleteValue}>
{t('Delete with the instance')}
</Checkbox>
) : null;
return (
<Form.Item
className={styles['instance-volume']}
name={name}
validateStatus={validateStatus}
help={errorMsg}
>
<Row gutter={24}>
<Col span={8}>
<span className={styles.label}>{t('Type')}</span>
{selects}
</Col>
<Col span={14}>
<span className={styles.label}>{t('Size')}</span>
{input}
<span className={styles['size-label']}>GiB</span>
{checkbox}
</Col>
</Row>
</Form.Item>
);
}
}