import React from 'react'
import cls from 'classnames'
import i18n from 'i18next'
import treeActions from 'actions/tree'
import widgetStore from 'stores/widget'
import { getEventNodeById } from 'stores/funcs/newEvent'

export default class IotMessageConfig extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      groupId: this.getGroupId(),
      releaseGroupId: this.getReleaseGroupId(),
      topics: this.getTopics()
    }
    // this.msgData = undefined
    this.prefix = '${ProductKey}/${deviceName}/'

    this.getGroupId = this.getGroupId.bind(this)
    this.getTopics = this.getTopics.bind(this)
    this.getTitleName = this.getTitleName.bind(this)
    this.onChangeGroupId = this.onChangeGroupId.bind(this)
    this.onAddTopic = this.onAddTopic.bind(this)
    this.onDeleteTopic = this.onDeleteTopic.bind(this)
    this.onChangeTopic = this.onChangeTopic.bind(this)
    this.genAddButton = this.genAddButton.bind(this)
    this.genTopic = this.genTopic.bind(this)
  }

  componentDidUpdate(preProps) {
    if (preProps.nodeId !== this.props.nodeId) {
      this.setState({
        groupId: this.getGroupId(),
        releaseGroupId: this.getReleaseGroupId(),
        topics: this.getTopics()
      })
    }
  }

  getGroupId() {
    // 通过config获取
    let groupId = ''
    let node = getEventNodeById(this.props.nodeId)
    if (node) {
      groupId = node.props.groupId || groupId
    }
    return groupId
  }

  getReleaseGroupId() {
    // 通过config获取
    let groupId = ''
    let node = getEventNodeById(this.props.nodeId)
    if (node) {
      groupId = node.props.releaseGroupId || groupId
    }
    return groupId
  }

  getTopics() {
    let topics = []
    let node = getEventNodeById(this.props.nodeId)
    if (node) {
      topics = node.props.topics || topics
    }
    return topics
  }

  getTitleName() {
    let title = ''
    let node = getEventNodeById(this.props.nodeId)
    if (node && widgetStore.widget[node.type]) {
      let map = widgetStore.widget[node.type].map
      title = map.locale ? map.locale[i18n.language] : map.name
    }
    return title ? title + i18n.t('EventView.jenga_extra.defination') : title
  }

  onChangeGroupId(applyChange, release, e) {
    let value = e && e.target ? e.target.value : e
    let obj = {}
    if (release) {
      obj.releaseGroupId = value
    } else {
      obj.groupId = value
    }
    this.setState(obj, () => {
      if (applyChange) {
        treeActions.changeNodeProps({
          nodeId: this.props.nodeId,
          props: obj
        })
      }
    })
  }

  onAddTopic() {
    let obj = {}
    let topics = this.state.topics
    topics.push({
      name: 'topic' + (this.state.topics.length + 1),
      def: this.prefix + ''
    })
    obj.topics = topics
    this.setState(obj, () => {
      treeActions.changeNodeProps({
        nodeId: this.props.nodeId,
        props: obj
      })
    })
  }

  onDeleteTopic(index) {
    let obj = {}
    let topics = this.state.topics
    topics.splice(index, 1)
    obj.topics = topics
    this.setState(obj, () => {
      treeActions.changeNodeProps({
        nodeId: this.props.nodeId,
        props: obj
      })
    })
  }

  onChangeTopic(index, param, applyChange, e) {
    let value = e && e.target ? e.target.value : e
    let obj = {}
    let topics = this.state.topics
    topics[index][param] = value
    obj.topics = topics
    let nodeId = this.props.nodeId
    this.setState(obj, () => {
      if (applyChange) {
        treeActions.changeNodeProps({
          nodeId: nodeId,
          props: obj
        })
      }
    })
  }

  genAddButton() {
    return (
      <button className="btn-clear btn-add-param" onClick={this.onAddTopic}>
        <div className="icon">
          <span className="horizon" />
          <span className="vertical" />
        </div>
      </button>
    )
  }

  genTopic(topic, index) {
    let length = this.state.topics.length
    let extraBtn = length - 1 === index ? this.genAddButton() : null
    return (
      <div
        className={cls('param-item f--hlc', {
          'param-item-left': index % 2 !== 0,
          'param-item-bottom': length > 2 && index < length - (length % 2 || 2)
        })}
        key={index}
      >
        <div className="item-input-wrap f--hlc flex-1">
          <div className="item-inner-wrap name-wrap f--hlc">
            <div className="item-name item-inner-name">
              {i18n.t('EventView.jenga_extra.topicName')}
            </div>
            <input
              value={topic.name}
              onChange={this.onChangeTopic.bind(this, index, 'name', false)}
              onBlur={this.onChangeTopic.bind(this, index, 'name', true)}
            />
          </div>
          <div className="item-inner-wrap def-wrap f--hlc">
            <div className="item-name item-inner-name">
              {i18n.t('EventView.jenga_extra.topicDef')}
            </div>
            {/*<div className="def-prefix">{this.prefix}</div>*/}
            <input
              title={topic.def}
              value={topic.def}
              className="value"
              onChange={this.onChangeTopic.bind(this, index, 'def', false)}
              onBlur={this.onChangeTopic.bind(this, index, 'def', true)}
            />
          </div>
          <button
            className="btn-clear btn-delete-param"
            onClick={this.onDeleteTopic.bind(this, index)}
          />
        </div>
        {extraBtn}
      </div>
    )
  }

  render() {
    return (
      <div className="jenga-iot-message-config">
        <div className="config-wrap f--hlc">
          <div className="title">{i18n.t('EventView.jenga_extra.groupId')}</div>
          <input
            className="groupId-input"
            value={this.state.groupId}
            onChange={this.onChangeGroupId.bind(this, false, false)}
            onBlur={this.onChangeGroupId.bind(this, true, false)}
          />
          <div className="title next">
            {i18n.t('EventView.jenga_extra.releaseGroupId')}
          </div>
          <input
            className="groupId-input"
            value={this.state.releaseGroupId}
            onChange={this.onChangeGroupId.bind(this, false, true)}
            onBlur={this.onChangeGroupId.bind(this, true, true)}
          />
        </div>
        <div
          className={cls(
            'params',
            this.state.topics.length > 0 ? 'f--h' : 'f--hlc'
          )}
        >
          <div
            className={cls(
              'params-title',
              this.state.topics.length > 2 ? 'params-title-top f--h' : 'f--hlc'
            )}
          >
            {i18n.t('EventView.jenga_extra.topics')}
          </div>
          <div className="main-wrap f--hlc">
            {this.state.topics.length === 0
              ? this.genAddButton('in')
              : this.state.topics.map((topic, index) => {
                  return this.genTopic(topic, index)
                })}
          </div>
        </div>
        <div className="params-title params-def-title">
          {this.getTitleName()}
        </div>
      </div>
    )
  }
}
