import React from 'react'
import i18n from 'i18next'
import cls from 'classnames'
import { Menu, Dropdown, Tooltip } from 'antd'
import newEventActions from 'actions/newEvent'
import newEventStores from 'stores/newEvent'
import widgetStore from 'stores/widget'
import { shallowEqualImmutable } from 'utils/utils'
import { getEventBlockByBid, getEventNodeById } from 'stores/funcs/newEvent'
import { getModuleInstanceNameLocale } from 'src/stores/funcs/event/methodUtils'
import { getTriggerEvents } from 'stores/funcs/event/eventUtils'
import { isHySa } from 'utils/commons/ctrlHide'
import BlockEnable from '../BlockEnable'
import iconStrObj from 'src/assets/icons/iconsStr'

const MenuItem = Menu.Item

export default class BlockEventTrigger extends React.Component {
  constructor(props) {
    super(props)
    this.curEventNodeId = newEventStores.curEventNodeId
    this.state = {
      events: this.getEvents(),
      trigger: this.getTrigger().name,
      mini: this.getTrigger().mini
    }

    this.onEventChange = this.onEventChange.bind(this)
    this.getEvents = this.getEvents.bind(this)
    this.getTrigger = this.getTrigger.bind(this)
    this.onSelectTrigger = this.onSelectTrigger.bind(this)
    this.getTriggerName = this.getTriggerName.bind(this)

    this.getTipInfo = this.getTipInfo.bind(this)
  }

  shouldComponentUpdate(nextProps, nextState) {
    return (
      !shallowEqualImmutable(this.props, nextProps) ||
      !shallowEqualImmutable(this.state, nextState)
    )
  }

  componentDidMount() {
    this.unsubscribe = newEventStores.listen(this.onEventChange)
  }

  componentWillUnmount() {
    this.unsubscribe()
  }

  componentDidUpdate(preProps) {
    if (preProps.bid !== this.props.bid) {
      this.setState({
        events: this.getEvents(),
        trigger: this.getTrigger().name,
        mini: this.getTrigger().mini
      })
    }
  }

  onEventChange(status) {
    let obj = {}
    if (status) {
      if (
        status.types.includes('curEventNodeId') &&
        this.curEventNodeId !== status.data.curEventNodeId
      ) {
        this.curEventNodeId = status.data.curEventNodeId
      }
      if (
        status.types.includes('updateBlockProp') &&
        this.props.bid === status.data.affectBlockId &&
        status.data.prop === 'trigger'
      ) {
        this.setState({
          trigger: this.getTrigger().name,
          mini: this.getTrigger().mini
        })
      }
    }
    if (Object.keys(obj).length > 0) {
      this.setState(obj)
    }
  }

  onSelectTrigger(option) {
    if (option.key === 'emptyContent') {
      return
    }
    let name = option.key
    let trigger = this.state.trigger
    if (trigger === name) {
      return
    }
    this.setState({
      trigger: name
    })
    let curNodeId = this.props.eventNodeId || this.curEventNodeId
    newEventActions.updateBlockProp({
      nodeId: curNodeId,
      blockId: this.props.bid,
      prop: 'trigger',
      value: name
    })
  }

  getEvents() {
    let curNodeId = this.props.eventNodeId || this.curEventNodeId
    return getTriggerEvents(curNodeId)
  }

  getTrigger() {
    let result = {}
    let curNodeId = this.props.eventNodeId || this.curEventNodeId
    let block = getEventBlockByBid(this.props.bid, curNodeId)
    if (block && block.eventId) {
      result['name'] = block.name
      result['mini'] = !!block.mini
    }
    return result
  }

  getTriggerName() {
    let curNodeId = this.props.eventNodeId || this.curEventNodeId
    let curEventNode = getEventNodeById(curNodeId)
    let nodeInfo = curEventNode
      ? widgetStore.widget[curEventNode.type]
      : undefined
    let name = this.state.trigger || ''
    if (curEventNode) {
      let isMini = this.state.mini
      if (isMini) {
        name = getModuleInstanceNameLocale({
          nodeId: curEventNode.id,
          type: 'events',
          name: name
        })
      } else {
        if (nodeInfo && nodeInfo.map && nodeInfo.map.eventsMap) {
          name =
            nodeInfo.map.eventsMap[name] && nodeInfo.map.eventsMap[name].locale
              ? nodeInfo.map.eventsMap[name].locale[i18n.language]
              : name
        }
      }
    }
    return name
  }

  getTipInfo(item) {
    let curNodeId = this.props.eventNodeId || this.curEventNodeId
    let objNode = getEventNodeById(curNodeId)
    let type = objNode && objNode.type
    if (type && item) {
      let stopPro = e => {
        e.stopPropagation()
      }
      let info = widgetStore.widget[type].map.eventsMap[item.name]
      let content = info && info.desc && info.desc[i18n.language]
      let link =
        i18n.language === 'en' ? info && info.linkEN : info && info.linkZH
      content = content ? (
        <div onClick={stopPro}>
          {content}
          {info && link ? (
            <a className="a-tag" href={link} target="_blank">
              {i18n.t('Tips.more')}
            </a>
          ) : (
            undefined
          )}
        </div>
      ) : (
        undefined
      )
      return (
        (!isHySa() && info && content && (
          <Tooltip
            title={content}
            placement="right"
            destroyTooltipOnHide={true}
          >
            <div className="block-map-help">
              <div
                className="ih5-icon-help"
                dangerouslySetInnerHTML={{ __html: iconStrObj.help }}
              />
            </div>
          </Tooltip>
        )) ||
        null
      )
    } else {
      return null
    }
  }

  render() {
    let eventTriggerMenu = () => {
      return (
        <Menu className="event-trigger-menu" onClick={this.onSelectTrigger}>
          {!this.state.events || this.state.events.length === 0 ? (
            <MenuItem key={'emptyContent'} className="empty-content">
              {i18n.t('EventView.jenga_event_block.emptyTrigger')}
            </MenuItem>
          ) : (
            this.state.events.map(event => {
              return (
                <MenuItem
                  key={event.name}
                  className={cls({
                    selected: this.state.trigger === event.name,
                    last: event.last
                  })}
                >
                  <div className="f--hlc">
                    {event.locale ? event.locale[i18n.language] : event.name}
                    {this.getTipInfo(event)}
                  </div>
                </MenuItem>
              )
            })
          )}
        </Menu>
      )
    }

    return (
      <div className="event-trigger f--h">
        <BlockEnable
          bid={this.props.bid}
          isEnable={this.props.isEnable}
          eventNodeId={this.props.eventNodeId}
        />
        <div className="event-wrap">
          <div className="select-wrap f--hlc">
            <Dropdown
              trigger={['click']}
              getPopupContainer={triggerNode => triggerNode.parentNode}
              overlayClassName={'event-trigger-dropdown'}
              overlay={eventTriggerMenu()}
            >
              <div className="trigger-select f--hlc">
                <div
                  className={cls('ant-dropdown-input f--hlc', {
                    placeholder: !this.getTriggerName()
                  })}
                >
                  {this.getTriggerName() ||
                    i18n.t('EventView.jenga_event_block.selectTrigger')}
                  {this.getTipInfo(this.state.trigger)}
                </div>
                <div className="ant-dropdown-icon" />
              </div>
            </Dropdown>
          </div>
        </div>
      </div>
    )
  }
}
