import React from 'react';
import {Menu, Segment, Table, Header, Label} from 'semantic-ui-react';
import {convertTime} from '../../../tools';
import IOPanelListItem  from './IOPanelListItem';

class IOPanel extends React.Component {
	state = {
		tabIdx: '1'
	}

	tabItemClick = (e, el) => {
		this.setState({
			tabIdx: el.name
		}, ()=>{
			this.props.getStatus({id: this.props.data.uid || '', type: this.state.tabIdx});
		});
	}

	componentWillReceiveProps(nprops) {
		if(nprops.data && nprops.data.uid) {
			if(this.props.data && this.props.data.uid){
				if(this.props.data.uid != nprops.data.uid) {
					this.props.getStatus({id: nprops.data.uid, type: this.state.tabIdx});
				}
			}else{
				this.props.getStatus({id: nprops.data.uid, type: this.state.tabIdx});
			}
		}
	}

	render(){
		let {i18n, show, data, ioModal, delIOList, showAIOSet} = this.props;
		if(!show) return null;
	
		let iolist = data.iolist || [];
		let ios = iolist.filter(t => {
			if(t.type == this.state.tabIdx) return t;
		});
		let status = data.status || {};
		let ss = status[this.state.tabIdx] || [];
		return (
			<div>
				<Menu attached="top" tabular>
					<Menu.Item content="DigitOutput" name="1" active={this.state.tabIdx == "1"} onClick={this.tabItemClick} />
					<Menu.Item content="DigitInput" name="2" active={this.state.tabIdx == "2"} onClick={this.tabItemClick} />
					<Menu.Item content="AnalogyOutput" name="3" active={this.state.tabIdx == "3"} onClick={this.tabItemClick} />
					<Menu.Item content="AnalogyInput" name="4" active={this.state.tabIdx == "4"} onClick={this.tabItemClick} />
					<Menu.Menu position="right">
						<Menu.Item content="AddIO" icon="plus" onClick={()=>{ioModal(0)}}/>
					</Menu.Menu>
				</Menu>
				<Segment attached="bottom">
					<Table>
						<Table.Header>
							<Table.Row>
								<Table.HeaderCell>起始位置</Table.HeaderCell>
								<Table.HeaderCell>接口數量</Table.HeaderCell>
								<Table.HeaderCell>操作</Table.HeaderCell>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{
								ios.map((t,idx) => (
									<IOPanelListItem key={idx} i18n={i18n} data={t} ioModal={ioModal} delIOList={delIOList} showAIOSet={showAIOSet} />
								))
							}
						</Table.Body>
					</Table>

					<Segment>
						<Header as="h3" content="接口資訊"/>
						{
							ss.map((t,idx) => (
								<div key={idx}>
									<Label basic color="olive" content={`SetName:${t.name}`} />
									<Label basic color="blue" content={`PortNum:${t.port}`}/>
									<Label basic color="blue" content={`原始數值:${t.value}`}/>
									<Label basic color="blue" content={`轉換數值:${t.value2}`}/>
									<Label basic color="green" content={`最後更新於:${convertTime(t.tst, true)}`}/>
								</div>
							))
						}
					</Segment>
				</Segment>
			</div>
		)
	}
}

export default IOPanel;