import React from 'react';
import {Container, Segment, Header, Table, Button, Modal} from 'semantic-ui-react';
import ListItem from './ListItem';
import {get_user_list, add_dialog_msg, edit_user, add_user, del_user} from '../../../actions';
import UModal from './UserModal';

class UList extends React.Component {

	state ={
		edit: false,
		// 0 is add , 1 is edit
		editType: 0,
		editData: {}
	}

	openModal = (acc) => {
		if(!acc) return this.setState({edit: true, editType: 0});
		let {users} = this.props;
		let user = users.filter(t => t.account == acc);
		this.setState({
			edit: true,
			editType: 1,
			editData: user[0] || {}
		});
	}

	closeModal = () => {
		this.setState({edit: false, editData: {}});
	}

	onModalSubmit = (data) => {
		let {i18n} = this.props;
		if(data.type == 0 && (!data.account || !data.password)) return this.props.showDialog(i18n && i18n.t ? i18n.t('tip.input_empty') : '');
		this.setState({edit: false, editData: {}});
		if(data.type == 1){
			this.props.editUser(data);
		}else{
			this.props.addUser(data);
		}
	}

	delUser = (acc) => {
		if(!acc) return ;
		this.props.delUser({account: acc});
	}

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

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

	render () {
		let {i18n, users} = this.props;
		return (
			<Container>
				<Segment>
					<Header as="h2" content={i18n && 't' in i18n ? i18n.t('page.userlist.title.userlist') : ''} />
					<Table>
						<Table.Header>
							<Table.Row>
								<Table.HeaderCell width={6} content={i18n && i18n.t ? i18n.t('page.userlist.table.account') : ''} />
								<Table.HeaderCell width={6} content={i18n && i18n.t ? i18n.t('page.userlist.table.privilege') : ''} />
								<Table.HeaderCell width={4} content={i18n && i18n.t ? i18n.t('page.userlist.table.operate') : ''} />
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{
								users.map(t => <ListItem key={t.account} i18n={i18n} user={t} openModal={this.openModal} delUser={this.delUser}/>)
							}
						</Table.Body>
						<Table.Footer>
							<Table.Row>
								<Table.Cell colSpan="3">
									<Button type="button" fluid content={i18n && i18n.t ? i18n.t('page.userlist.table.button.add') : ''} onClick={()=>this.openModal()}/>
								</Table.Cell>
							</Table.Row>
						</Table.Footer>
					</Table>
				</Segment>
				<UModal i18n={i18n} open={this.state.edit} type={this.state.editType} data={this.state.editData} closeModal={this.closeModal} onSubmit={this.onModalSubmit}/>
			</Container>
		)
	}
}

export default UList;