import React from 'react';
import {Container, Segment, Table, Button} from 'semantic-ui-react';
import {getRequest} from '../../../actions';
import {Link} from 'react-router';
import ListItem from './ListItem';
import LinkInfoModal from './LinkInfoModal';

const defState = {
	infoModal: {
		open: false,
		ln: [],
		lc: [],
		root: ''
	}
}

class ActionLinkPage extends React.Component {
	state = {
		...defState
	}

	componentDidMount(){
		this.props.getList();

		this.props.router.setRouteLeaveHook(this.props.route, () => {
			this.props.clearList();
		})
	}

	swLinkActive = (id) => {
		if(!id) return ;
		this.props.swLink({id});
	}
	delLink = (id) => {
		if(!id) return ;
		this.props.delLink({id});
	}
	openInfoModal = (id) => {
		if(!id) return ;

		fetch('/api/link/getlink', getRequest({id}))
			.then(response=>response.json())
			.then(json => {
				if(json.status != 1 ) return this.props.showDialog(json.message);
				this.setState({
					infoModal:{
						open: true,
						root: id,
						ln: json.data.rt.ln || [],
						lc: json.data.rt.lc || []
					}
				})
			})
	}
	closeInfoModal = () => {
		this.setState({
			infoModal:{
				...defState.infoModal
			}
		})
	}

	render(){
		let {i18n, list} = this.props;

		return (
			<Container>
				<Segment className="clearfix">
					<Button as={Link} to="/admin/addlink" basic color="green" floated="right" icon="plus" content="新增" style={{marginBottom: '10px'}} />
					<Table>
						<Table.Header>
							<Table.Row>
								<Table.HeaderCell>操作</Table.HeaderCell>
								<Table.HeaderCell>ID</Table.HeaderCell>
								<Table.HeaderCell>名稱</Table.HeaderCell>
								<Table.HeaderCell>啟用狀態</Table.HeaderCell>
								<Table.HeaderCell>觸發內容</Table.HeaderCell>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{
								list.map((t,idx) => (
									<ListItem key={idx} i18n={i18n} data={t} swActive={this.swLinkActive} delItem={this.delLink} showInfo={this.openInfoModal} />
								))
							}
						</Table.Body>
					</Table>
				</Segment>
				<LinkInfoModal i18n={i18n} 
					open={this.state.infoModal.open} 
					root={this.state.infoModal.root}
					ln={this.state.infoModal.ln} 
					lc={this.state.infoModal.lc}
					onClose={this.closeInfoModal} />
			</Container>
		)
	}
}

export default ActionLinkPage;