import React from 'react'
import i18n from 'i18next'
import { Switch } from 'antd'
import treeActions from 'actions/tree'
import { getEventNodeById } from 'stores/funcs/newEvent'

export default class NodeFuncGroup extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isSync: this.getIsSync()
    }

    this.getIsSync = this.getIsSync.bind(this)
    this.onChangeIsSync = this.onChangeIsSync.bind(this)
  }

  componentDidUpdate(preProps) {
    if (this.props.nodeId !== preProps.nodeId) {
      this.setState({
        isSync: this.getIsSync()
      })
    }
  }

  getIsSync() {
    let isSync = false
    let node = getEventNodeById(this.props.nodeId)
    if (node) {
      // 默认为false
      isSync = node.props.sync || isSync
    }
    return isSync
  }

  onChangeIsSync(e) {
    let props = {
      sync: e
    }
    this.setState({ isSync: props.sync }, () => {
      treeActions.changeNodeProps({
        nodeId: this.props.nodeId,
        props: props
      })
    })
  }

  render() {
    return (
      <div className="jenga-node-func-group f--hlc">
        <div className="title">{i18n.t('EventView.jenga_extra.func-sync')}</div>
        <Switch
          checked={this.state.isSync}
          onChange={this.onChangeIsSync}
          className="sync-switch"
        />
      </div>
    )
  }
}
