import React from 'react'
import { Input, Dropdown, Checkbox, Icon, Menu } from 'antd'

class CheckToInput extends React.Component {
  constructor (props) {
    super(props)
    this.state = {
      visible: false
    }
  }

  SelectCheck = (e, item) => {
    e.stopPropagation()
    const value = this.props.value
    const newValue = []
    let isGet = false
    if (value && value.length) {
      value.forEach(t => {
        if (item.value.toString() === t) {
          isGet = true
          if (e.target.checked) {
            newValue.push(t)
          }
        } else {
          newValue.push(t)
        }
      })
    }
    if (!isGet && e.target.checked) {
      newValue.push(item.value.toString())
    }
    if (typeof this.props.onChange === 'function') {
      this.props.onChange(newValue)
    }
  }

  render () {
    const { checkedData = [], value, disabled, style, promptInfo } = this.props
    const selectedLabels = []
    if (checkedData && checkedData.length && value && value.length) {
      checkedData.forEach(t => {
        if (value.includes(t.value.toString())) {
          selectedLabels.push(t.label)
        }
      })
    }
    const tempValue = selectedLabels && selectedLabels.length ? selectedLabels.join(',') : null
    const overlayComponent = (
      <Menu>
        {
          checkedData && checkedData.length ? checkedData.map(item => (
            <Menu.Item key={item.value}>
              <Checkbox
                onChange={(e) => this.SelectCheck(e, item)}
                checked={value && value.length ? value.includes(item.value.toString()) : false}
                value={item.value}
                disabled={disabled}
              >
                {item.label}
              </Checkbox>
            </Menu.Item>
          )) : null
        }
      </Menu>
    )
    const dropAfter = (
      <Dropdown overlay={overlayComponent} visible={this.state.visible} onVisibleChange={v => this.setState({ visible: v })} trigger={['click']}>
        <Icon type='down' />
      </Dropdown>
    )

    return (
      <Input addonAfter={dropAfter} style={style} placeholder={promptInfo} value={tempValue} title={tempValue} readOnly />
    )
  }
}

export default CheckToInput
