import React from 'react';
import {
    Container,
    Segment,
    Form,
    Input,
    Button,
    Checkbox,
    Grid,
    Menu,
    List
} from 'semantic-ui-react';
import {getRequest} from '../../../actions';
import UnitItem from './UnitItem';
import ActionSelect from './ActionSelect';
import ActionItem from './ActionItem';
import ViewTree from './ViewTreeModal';

const defState = () => ({
    gidx: 0,
    groups: {},
    active: false,
    edit: {
        name: '',
        type: 'ln',
        op: '',
        id1: {
            st: '',
            list: [],
            data: {}
        },
        id2: {
            st: '',
            list: [],
            data: {}
        }
    },
    actDevlist: [],
    items: [],
    showTree: false
})
const gtype = {
    lc: {
        type: 'lc',
        id: '',
        op: '',
        value: ''
    },
    ln: {
        type: 'ln',
        dev: ''
    }
}

class ActionLinkAdd extends React.Component {
    state = {
        ...defState()
    }

    getSelectList = (unit, type = '') => {
        if (!unit) {
            return;
        }
        if(unit != 'act'){
            let edit = {
                ...this.state.edit
            };
            if (!(unit in edit)) {
                return;
            }
            edit[unit].st = type;
            edit[unit].data = {
                ...gtype.lc
            }
            if (type != 'di' && type != 'leone' && type != 'unit') {
                return this.setState({edit});
            }

            if (type == 'di' || type == 'leone') {
                this.props.toggleLoading(1);
                let json = {
                    type
                };
                fetch('/api/system/getselectlist', getRequest(json))
                    .then(response => response.json())
                    .then(json => {
                        if (json.status != 1) 
                            return this.props.showDialog(json.message);
                        edit[unit].list = json.data.record || [];
                        this.setState({edit}, () => {
                            this.props.toggleLoading(0);
                        });
                    });
            }
            if(type == 'unit') {
                let list = [];
                for(let i in this.state.groups){
                    list.push({id: i, name: this.state.groups[i].name});
                }
                edit[unit].list = list;
                edit[unit].data = {
                    ...gtype.ln
                }
                this.setState({edit})
            }
        }else{
            let actDevlist = [];
            if(!type) {
                this.setState({
                    actDevlist
                });
                return ;
            }
            this.props.toggleLoading(1);
            fetch('/api/system/getselectlist', getRequest({type}))
                .then(response => response.json())
                .then(json => {
                    if (json.status != 1) 
                        return this.props.showDialog(json.message);
                    actDevlist = json.data.record || []
                    this.setState({
                        actDevlist
                    }, ()=>{
                        this.props.toggleLoading(0);
                    })
                })
        }
    }

    updateData = (unit, data) => {
        let {edit} = this.state;
        if(!(unit in edit)) return ;
        edit[unit].data = data;

        this.setState({
            edit
        })
    }

    updateEditData = (tag, value) => {
        let {edit} = this.state;
        if(tag in edit){
            edit[tag] = value;
        }

        this.setState({
            edit
        })
    }

    updateActive = (active = false) => {
        this.setState({
            active: active ? 1 : 0
        })
    }

    joinUnit = () => {
        let {edit} = this.state;
        let {i18n} = this.props;
        if(!edit.name || edit.op.length == 0 || Object.keys(edit.id1.data).length == 0 || Object.keys(edit.id2.data).length == 0) return this.props.showDialog(i18n&&i18n.t ? i18n.t('tip.input_empty') : '');
        if(edit.id1.data.type == 'lc' && (edit.id1.data.id.length == 0 || edit.id1.data.op.length == 0 || edit.id1.data.value.length == 0)) return this.props.showDialog(i18n&&i18n.t ? i18n.t('tip.input_empty') : '');
        if(edit.id2.data.type == 'lc' && (edit.id2.data.id.length == 0 || edit.id2.data.op.length == 0 || edit.id2.data.value.length == 0)) return this.props.showDialog(i18n&&i18n.t ? i18n.t('tip.input_empty') : '');
        if(edit.id1.data.type == 'ln' && edit.id1.data.dev.length == 0) return this.props.showDialog(i18n&&i18n.t ? i18n.t('tip.input_empty') : '');
        if(edit.id2.data.type == 'ln' && edit.id2.data.dev.length == 0) return this.props.showDialog(i18n&&i18n.t ? i18n.t('tip.input_empty') : '');

        let unitKey = [];
        if(edit.id1.data.type == 'lc'){
            edit.id1 = {
                ...edit.id1.data
            }
        }else if(edit.id1.data.type == 'ln'){
            unitKey.push(edit.id1.data.dev)
            edit.id1 = {
                ...this.state.groups[edit.id1.data.dev]
            }
        }
        if(edit.id2.data.type == 'lc'){
            edit.id2 = {
                ...edit.id2.data
            }
        }else if(edit.id2.data.type == 'ln'){
            unitKey.push(edit.id2.data.dev)
            edit.id2 = {
                ...this.state.groups[edit.id2.data.dev]
            }
        }
        let groups = {...this.state.groups};
        for(let i in unitKey){
            if(unitKey[i] in groups) delete groups[unitKey[i]];
        }

        groups[`unit${this.state.gidx}`] = {
            ...edit
        }

        this.setState({
            gidx: this.state.gidx+1,
            groups: {...groups}
        }, ()=>{
            this.resetEdit()
        })
    }

    resetEdit = () => {
        this.setState({
            edit:{
                ...defState().edit
            }
        })
    }

    addAction = (item) => {
        if(!item) return this.props.showDialog('動作請選擇完整');
        let cmds = item.act.split(' ');
        if(cmds.length != 2) return this.props.showDialog('動作選擇錯誤');
        if(cmds[0] == 2 && (cmds[1] < 16 || cmds[1] > 30)) return this.props.showDialog('溫度範圍錯誤(16-30)');

        this.setState({
            items: [...this.state.items, item]
        })
    }

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

    toggleView = (sw = false) => {
        this.setState({
            showTree: sw ? true : false
        })
    }

    removeNode = (node) => {
        if(!node) return ;
        let groups = {...this.state.groups};
        if(node in groups){
            delete groups[node];
            this.setState({
                groups: {...groups}
            })
        }
    }

    saveLink = () => {
        if(Object.keys(this.state.groups).length == 0) return this.props.showDialog('請先建立群組');
        if(Object.keys(this.state.groups).length > 1) return this.props.showDialog('根節點數量大於一');
        if(this.state.items.length == 0) return this.props.showDialog('請選擇動作');
        let json = {
            active: this.state.active,
            link: this.state.groups[Object.keys(this.state.groups)[0]],
            action: ''
        }

        let acts = this.state.items.map(t => {
            return `${t.id},${t.act.replace(' ', ',')},0`
        })

        json.action = acts.join('|')

        this.props.toggleLoading(1);
        fetch('/api/link/addlink', getRequest(json))
            .then(response => response.json())
            .then(json => {
                this.props.toggleLoading(0);
                if(json.status != 1) return this.props.showDialog(json.message);
                this.resetAll();
            })
    }

    resetAll = () => {
        this.setState({
            ...defState()
        })
    }

    render() {
        let {i18n} = this.props;
        return (
            <Container>
                <Menu >
                    <Menu.Menu position="right">
                        <Menu.Item content="ShowTree" onClick={()=>{
                                this.toggleView(1)
                            }}/>
                        <Menu.Item content="Save" onClick={()=>{
                                this.saveLink();
                            }}/>
                    </Menu.Menu>
                </Menu>
                <Form as={Segment}>
                    <Form.Field>
                        <Checkbox label="啟用連動" checked={this.state.active == 1} onChange={(e,d) =>{
                                this.updateActive(d.checked ? 1 : 0);
                            }}/>
                    </Form.Field>
                    <Form.Field>
                        <label>建立條件群組</label>
                        <Segment color="red">
                            <Form.Field>
                                <Input label="節點名稱" value={this.state.edit.name} onChange={(e,d) => {
                                    this.updateEditData('name', d.value);
                                }}/>
                            </Form.Field>
                            <Form.Field>
                                <label>觸發條件</label>
                                <select value={this.state.edit.op} onChange={(e) => {
                                        this.updateEditData('op', e.target.value);
                                    }}>
                                    <option value="">請選擇觸發條件</option>
                                    <option value="8">AND</option>
                                    <option value="9">OR</option>
                                </select>
                            </Form.Field>
                            <Grid columns={2} padded>
                                <UnitItem unit="id1" data={this.state.edit.id1} getList={this.getSelectList} updateData={this.updateData}/>
                                <UnitItem unit="id2" data={this.state.edit.id2} getList={this.getSelectList} updateData={this.updateData}/>
                            </Grid>
                            <div
                                style={{
                                textAlign: 'right'
                            }}>
                                <Button type="button" basic size="tiny" color="blue" content="加入" onClick={()=>{
                                        this.joinUnit();
                                    }}/>
                                <Button type="button" basic size="tiny" color="green" content="清除" onClick={()=>{this.resetEdit()}}/>
                            </div>
                        </Segment>
                    </Form.Field>
                    <ActionSelect i18n={i18n} unit="act" list={this.state.actDevlist} getList={this.getSelectList} addAction={this.addAction} />
                    <Form.Field>
                        <label>裝置動作列表</label>
                        <Segment color="blue">
                            <List>
                                {
                                    this.state.items.map((t,idx) => (
                                        <ActionItem key={idx} i18n={i18n} data={t} idx={idx} removeAction={this.removeAction}/>
                                    ))
                                }
                            </List>
                        </Segment>
                    </Form.Field>
                </Form>
                <ViewTree i18n={i18n} data={this.state.groups} open={this.state.showTree} closeView={this.toggleView} removeNode={this.removeNode} />
            </Container>
        )
    }
}

export default ActionLinkAdd;