import React from 'react';
import {Modal, Form, Button, Grid, Input } from 'semantic-ui-react';

const IOModal = ({i18n, open, type, data, onSubmit, onClose}) => {

	let iotype = i18n&&i18n.getResource&&i18n.language ? i18n.getResource(i18n.language + '.translation.porttype') : [];

	return (
		<Modal open={open}>
			<Modal.Header content={type == 1 ? '修改資料' : '新增資料'} />
			<Modal.Content>
				<Form onSubmit={(e,d)=>{
						e.preventDefault();
						onSubmit(type, d.formData);
					}} serializer={e=>{
						let json = {
							id: data.uid || '',
							addr: '',
							num: '',
							type: ''
						};

						let addr = e.querySelector('input[name="addr"]');
						if(addr && 'value' in addr) json.addr = addr.value;
						let num = e.querySelector('input[name="num"]');
						if(num && 'value' in num) json.num = num.value;
						let type = e.querySelector('select[name="io_type"]');
						if(type && 'value' in type) json.type = type.value;

						return json;
					}}>
					<Form.Field>
						<label>接口類型</label>
						<select name="io_type" defaultValue={data.type || ''} disabled={type == 1}>
							<option value="">請選擇類型</option>
							{
								iotype.map((t,idx) => (
									<option key={idx} value={t.code}>{t.name}</option>
								))
							}
						</select>
					</Form.Field>
					<Form.Field>
						<Input name="addr" label="起始位址" defaultValue={data.addr || ''} />
					</Form.Field>
					<Form.Field>
						<Input name="num" label="數量" defaultValue={data.num || ''} />
					</Form.Field>
					<Grid columns={2}>
						<Grid.Column>
							<Button type="submit" fluid content="Submit" />
						</Grid.Column>
						<Grid.Column>
							<Button type="button" fluid content="Cancel" onClick={()=>{onClose()}}/>
						</Grid.Column>
					</Grid>
				</Form>
			</Modal.Content>
		</Modal>
	)
}

export default IOModal ;