import React from 'react';
import {Container, Segment, Table, Button, Modal, Item, Label} from 'semantic-ui-react';
import ListItem from './ListItem';
import ScheduleModal from './ScheduleModal';

class SchedulePage extends React.Component {

	state ={
		modal: false,
		modalType: 0,
		modalData: {},
		modalWeek: [],
		modalShowTemp: false,
		modalDateType: 'w',
		modalSelected: [],
		modalCmd: '',
		modalTemp: '',
		itemModal: false,
		itemModalData: []
	}

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

	changeActive = (id) => {
		if(!id) return ;
		this.props.swSchedule({id});
	}

	delItem = (id) => {
		if(!id) return ;
		this.props.delSchedule({id});
	}

	openModal = (type, data = {}, items = []) => {
		let json = {
			modal: true,
			modalType: type,
			modalData: data,
			modalSelected: [...items]
		}
		if(type == 1){
			let dtype = '';
			if(data.ioscheduleparam5 && data.ioscheduleparam5 != '-'){
				let ws = data.ioscheduleparam5.split(',');
				let arr = [];
				dtype = 'w';
				for(let i in ws){
					if(isFinite(ws[i]) && ws[i] >= 1 && ws[i] <= 7){
						arr = [...arr, ws[i]];
					}
				}
				json = {
					...json,
					modalWeek: [...arr]
				};
				// this.setState({
				// 	week: [...arr]
				// });
			}else{
				dtype = 'd';
			}

			let act = data.ioschedulecmd || ''; 
			act = act.split(',');	
			if(act.length == 2){
				if(act[0] == '2') {
					json = {
						...json,
						modalShowTemp: true,
						modalCmd: act[0],
						modalTemp: act[1]
					}
				}else {
					json ={
						...json,
						modalShowTemp: false,
						modalCmd: act.join(' '),
						modalTemp: ''
					}
				}
			}

			json = {
				...json,
				modalDateType: dtype
			}
			// this.setState({
			// 	modalDateType: dtype
			// })
		}
		this.setState({
			...json
		});
	}

	closeModal = () => {
		this.setState({
			modal: false,
			modalType: 0,
			modalData: {},
			modalWeek: [],
			modalShowTemp: false,
			modalDateType: 'w',
			modalSelected: [],
			modalCmd: '',
			modalTemp: ''
		})
	}

	submitModal = (type, data) => {
		let {i18n, showDialog} = this.props;
		let json = {};
		if(type == 1 && !data.id) return showDialog(i18n&&i18n.t ? i18n.t('tip.input_empty') : '');
		if(!data.name || !data.time || !data.cmd || (data.cmd == 2 && !data.temp) || (this.state.modalDateType == 'd' && !data.date)) 
			return showDialog(i18n&&i18n.t ? i18n.t('tip.input_empty') : '');

		if((this.state.modalDateType == 'w' && this.state.modalWeek.length == 0)) return showDialog(i18n&&i18n.t ? i18n.t('tip.select_week') : '');

		json.name = data.name;
		json.active = data.active ? 1 : 0;

		if(!/^\d{1,2}:\d{1,2}$/.test(data.time)) return showDialog(i18n&&i18n.t ? i18n.t('tip.input_format') : '');
		let tarr = data.time.split(':');
		if(tarr[0] < 0 || tarr[0] > 23 || tarr[1] < 0 || tarr[1] > 59) return showDialog(i18n&&i18n.t ? i18n.t('tip.time_range') : '');
		json.min = tarr[1];
		json.hour = tarr[0];

		if(this.state.modalDateType == 'w'){
			json.week = this.state.modalWeek.join(',');
		}else{
			json.day = '';
			json.month = '';
			if(!/^\d{1,2}\-\d{1,2}$/.test(data.date)) return showDialog(i18n&&i18n.t ? i18n.t('tip.date_format') : '');
			let darr = data.date.split('-');
			if(darr[0] < 1 || darr[0] > 12 || darr[1] < 1 || darr[1] > 31) return showDialog(i18n&&i18n.t ? i18n.t('tip.date_range') : '');
			json.day = darr[1];
			json.month = darr[0];
		}

		let tmp = this.state.modalSelected.map(t => t.id);
		json.devs = tmp.join(',');

		if(data.cmd == 2){
			if(!data.temp) return showDialog(i18n&&i18n.t ? i18n.t('tip.input_empty_temp') : '');
			if(!(data.temp >= 16 && data.temp <= 30)) return showDialog(i18n&&i18n.t ? i18n.t('tip.temp_format') : '');
			json.action = `${data.cmd},${data.temp}`;
		}else{
			json.action = data.cmd.replace(' ', ',');
		}

		json.id = data.id;

		if(type == 0){
			this.props.addSchedule(json);
		}else{
			this.props.editSchedule(json);
		}

		this.closeModal();
	}

	showGroup = (items) => {
		this.setState({
			itemModal: true,
			itemModalData: [...items]
		});
	}
	closeGroupModal = () => {
		this.setState({
			itemModal: false,
			itemModalData: []
		});
	}

	querySelectList = (type) => {
		this.props.getSelectList({type});
	}

	// ================================

	addSelect = (data) => {
		if(!data) return;
		this.setState({
			modalSelected: [...this.state.modalSelected, data]
		})
	}

	removeSelected = (idx) => {
		let items = [...this.state.modalSelected];
		items.splice(idx, 1);
		this.setState({
			modalSelected: [...items]
		});
	}

	checkShowTemp = (val) => {
		this.setState({
			modalShowTemp: val == 2 ? true : false,
			modalCmd: val
		});
	}

	changeDateType = (type) => {
		if(!type) return;
		this.setState({
			modalDateType: type
		})
	}

	changeWeek = (checked, value) => {
		let week = this.state.modalWeek;
		if(checked){
			if(week.indexOf(value) == -1){
				week.push(value);
			}
		}else{
			if(week.indexOf(value) != -1){
				week.splice(week.indexOf(value), 1);
			}
		}
		this.setState({
			modalWeek: [...week]
		});
	}

	// ================================

	render() {
		let {i18n, devs, list, dos, les, ios, permissions} = this.props;
		
		return (
			<Container>
				<Segment className="clearfix">
					<Button type="button" floated="right" icon="plus" basic color="green" content={i18n&&i18n.t ? i18n.t('page.schedule.table.button.add') : ''} style={{marginBottom: '15px'}} onClick={() => {this.openModal(0)}}/>
					<Table>
						<Table.Header>
							<Table.Row>
								<Table.HeaderCell>{i18n&&i18n.t ? i18n.t('page.schedule.table.operate') : ''}</Table.HeaderCell>
								<Table.HeaderCell>{i18n&&i18n.t ? i18n.t('page.schedule.table.name') : ''}</Table.HeaderCell>
								<Table.HeaderCell>{i18n&&i18n.t ? i18n.t('page.schedule.table.schedule_time') : ''}</Table.HeaderCell>
								<Table.HeaderCell>{i18n&&i18n.t ? i18n.t('page.schedule.table.action') : ''}</Table.HeaderCell>
								<Table.HeaderCell>{i18n&&i18n.t ? i18n.t('page.schedule.table.active_status') : ''}</Table.HeaderCell>
								<Table.HeaderCell>{i18n&&i18n.t ? i18n.t('page.schedule.table.device') : ''}</Table.HeaderCell>
							</Table.Row>
						</Table.Header>
						<Table.Body>
							{
								list.map((t,idx) => (<ListItem key={idx} i18n={i18n} data={t} idx={idx} dos={dos} ios={ios} les={les} openModal={this.openModal} changeActive={this.changeActive} delItem={this.delItem} showGroup={this.showGroup} />))
							}
						</Table.Body>
					</Table>
				</Segment>
				<ShowGroupItem i18n={i18n} open={this.state.itemModal} items={this.state.itemModalData} onClose={this.closeGroupModal} />
				<ScheduleModal i18n={i18n} 
					open={this.state.modal} 
					data={this.state.modalData} 
					type={this.state.modalType} 
					querySelectList={this.querySelectList} 
					permissions={permissions} 
					devs={devs} 
					selected={this.state.modalSelected}
					week={this.state.modalWeek}
					showTemp={this.state.modalShowTemp}
					dateType={this.state.modalDateType}
					cmd={this.state.modalCmd}
					temp={this.state.modalTemp}
					addSelect={this.addSelect}
					checkShowTemp={this.checkShowTemp}
					removeSelected={this.removeSelected}
					changeDateType={this.changeDateType}
					changeWeek={this.changeWeek}
					onClose={this.closeModal} 
					onSubmit={this.submitModal} />
			</Container>
		)
	}
}

const ShowGroupItem = ({i18n,open,items, onClose}) => {

	return (
		<Modal open={open} onClose={() => {onClose()}} size="small">
			<Modal.Content>
				{
					items.map((t, idx) => <Item key={idx}><Label content={t.type}/>{t.name}</Item>)
				}
			</Modal.Content>
		</Modal>
	)
}

export default SchedulePage;