import React from 'react'
import cls from 'classnames'
import { Menu, Dropdown } from 'antd'
import i18n from 'i18next'
import newEventActions from 'actions/newEvent'
import treeStores from 'stores/tree'
import { getEventBlockByBid, layerWidth } from 'stores/funcs/newEvent'
import { conOptions } from 'const/enum'
import { is } from 'immutable'
import ConItem from '../ConItem'
import FormulaEditor from 'src/components/common/formulaEditor/EventFormulaEditor'

const MenuItem = Menu.Item

export default class BlockConConItem extends ConItem {
  constructor(props) {
    super(props)
    this.state.option = this.getConOption(props.bid)
    this.state.conOptions = conOptions

    this.onChangeConOption = this.onChangeConOption.bind(this)
    this.onDeleteCon = this.onDeleteCon.bind(this)

    this.isSelectedOption = this.isSelectedOption.bind(this)

    this.getValueWidth = this.getValueWidth.bind(this)
    this.getConOption = this.getConOption.bind(this)
    this.getConOptionName = this.getConOptionName.bind(this)
  }

  componentDidUpdate(preProps) {
    let obj = {}
    let conItem = this.getConItem()
    if (!is(this.state.conItem, conItem) || preProps.bid !== this.props.bid) {
      obj.conItem = conItem
      if (preProps.bid !== this.props.bid) {
        let option = this.getConOption()
        if (this.state.option !== option) {
          obj.option = option
        }
      }
    }
    if (Object.keys(obj).length > 0) {
      this.setState(obj)
    }
  }

  onEventChange(status) {
    let obj = {}
    if (status && status.types) {
      if (
        status.types.includes('updateBlockProp') &&
        this.props.bid === status.data.affectBlockId &&
        status.data.prop === 'op'
      ) {
        let option = this.getConOption()
        if (this.state.option !== option) {
          obj.option = option
        }
      }

      if (
        status.types.includes('updateBlockProp') &&
        this.props.bid === status.data.affectBlockId &&
        status.data.prop === 'cons'
      ) {
        this.forceUpdate()
      }
    }
    if (Object.keys(obj).length > 0) {
      this.setState(obj)
    }
  }

  onChangeConOption(option) {
    if (option && option.key) {
      let value = option.key
      this.setState(
        {
          option: value
        },
        () => {
          newEventActions.updateBlockProp({
            blockId: this.props.bid,
            prop: 'op',
            value: value
          })
        }
      )
    }
  }

  onDeleteCon() {
    this.props.onDelBlockCon({ index: this.props.index, resetLast: true })
    this.props.onConsChange()
  }

  isSelectedOption(option) {
    return this.state.option === option
  }

  getValueWidth() {
    const groupLayer = this.props.groupLayer > 0 ? this.props.groupLayer : 0
    const nestingLayer =
      this.props.nestGroupLayer > 0 ? this.props.nestGroupLayer - 1 : 0
    const extraGapGroupLayer =
      this.props.extraGapGroupLayer > 0
        ? (this.props.extraGapGroupLayer - 1) * 2
        : 0
    let originWidth =
      304 - ((groupLayer + nestingLayer) * 2) / 2 - extraGapGroupLayer / 2
    let width = layerWidth({
      originWidth: originWidth + this.state.widthDelta / 2,
      decreaseFactor: 10.5,
      layer: this.props.layer
    })
    return {
      width: width + 'px'
    }
  }

  getConOption(bid) {
    let _bid = bid || this.props.bid
    let nodeId = this.props.eventNodeId || treeStores.curEventNodeId
    let curBlock = getEventBlockByBid(_bid, nodeId)
    if (curBlock) {
      return curBlock.op || ''
    }
    return ''
  }

  getConOptionName() {
    let option = this.state.option
    if (option) {
      return i18n.t('EventView.jenga_cons.' + option)
    }
    return ''
  }

  render() {
    let conOptionsMenu = () => {
      return (
        <Menu
          className="con-con-flag-select-menu"
          onClick={this.onChangeConOption}
        >
          {this.state.conOptions.map(option => {
            return (
              <MenuItem
                key={option}
                className={cls({
                  selected: this.isSelectedOption(option)
                })}
              >
                {this.getOptionName(option)}
              </MenuItem>
            )
          })}
        </Menu>
      )
    }

    let conFlagsMenu = () => {
      return (
        <Menu className="con-con-flag-select-menu" onClick={this.onChangeFlag}>
          {this.state.conFlags.map(option => {
            return (
              <MenuItem
                key={option}
                className={cls({
                  selected: this.isSelectedFlag(option)
                })}
              >
                {this.getOptionName(option)}
              </MenuItem>
            )
          })}
        </Menu>
      )
    }

    let conOperatorsMenu = () => {
      return (
        <Menu
          className="con-con-operator-select-menu"
          onClick={this.onChangeOperator}
        >
          {this.state.conOperatorOptions.map(option => {
            return (
              <MenuItem
                key={option}
                className={cls({
                  selected: this.isSelectedOperator(option)
                })}
              >
                {option}
              </MenuItem>
            )
          })}
        </Menu>
      )
    }

    return (
      <div className={cls('con-item f--hlc')}>
        {this.props.index === 0 ? (
          <React.Fragment>
            <div className="item-enable" />
            <Dropdown
              trigger={['click']}
              getPopupContainer={triggerNode => triggerNode.parentNode}
              overlayClassName={'con-con-flag-dropdown'}
              overlay={conOptionsMenu()}
            >
              <div className="con-con-flag-select f--hlc">
                <input
                  value={this.getConOptionName()}
                  readOnly={true}
                  className="ant-dropdown-input"
                />
                <div className="ant-dropdown-icon" />
              </div>
            </Dropdown>
          </React.Fragment>
        ) : (
          <React.Fragment>
            <div className="item-enable" />
            <Dropdown
              trigger={['click']}
              getPopupContainer={triggerNode => triggerNode.parentNode}
              overlayClassName={'con-con-flag-dropdown'}
              overlay={conFlagsMenu()}
            >
              <div className="con-con-flag-select f--hlc">
                <input
                  value={this.getConItemFlagName()}
                  readOnly={true}
                  className="ant-dropdown-input"
                />
                <div className="ant-dropdown-icon" />
              </div>
            </Dropdown>
          </React.Fragment>
        )}
        <div className="item-value-wrap f--h" style={this.getValueWidth()}>
          <FormulaEditor
            className="event-formula-editor"
            uid={this.props.bid + 'value1'}
            bid={this.props.bid}
            value={this.state.conItem.value1}
            onChangeCode={this.onChangeValue.bind(this, 'value1')}
          />
        </div>
        <Dropdown
          trigger={['click']}
          getPopupContainer={triggerNode => triggerNode.parentNode}
          overlayClassName={'con-con-operator-dropdown'}
          overlay={conOperatorsMenu()}
        >
          <div className="con-con-operator-select f--hlc">
            <input
              value={this.state.conItem.operator}
              readOnly={true}
              className="ant-dropdown-input"
            />
            <div className="ant-dropdown-icon" />
          </div>
        </Dropdown>
        <div className="item-value-wrap f--h" style={this.getValueWidth()}>
          <FormulaEditor
            className="event-formula-editor"
            uid={this.props.bid + 'value2'}
            bid={this.props.bid}
            value={this.state.conItem.value2}
            params={this.formulaExtraParams()}
            onChangeCode={this.onChangeValue.bind(this, 'value2')}
          />
        </div>
        <button
          className="btn-clear btn-con-item-del"
          onClick={this.onDeleteCon}
        />
        {this.props.index === 0 ? (
          <button className="btn-clear btn-add-con" onClick={this.onAddCon}>
            <div className="btn-icon">
              <span className="horizon" />
              <span className="vertical" />
            </div>
          </button>
        ) : null}
      </div>
    )
  }
}
