import Taro from '@tarojs/taro'
import { View, Block } from '@tarojs/components'
import CtsFloatLayout from '../float-layout'
import { AtInput } from 'taro-ui'

import classNames from 'classnames'
import PropTypes, { InferProps } from 'prop-types'
import CtsComponent from '../../common/component'
import { CtsFloatInputProps, CtsFloatInputState } from 'types/float-input'

/**
 * 输入框输入/修改组件
 */
export default class CtsFloatInput extends CtsComponent<CtsFloatInputProps, CtsFloatInputState> {
  // static options = {
  //   addGlobalClass: true
  // }

  public static defaultProps: CtsFloatInputProps
  public static propTypes: InferProps<CtsFloatInputProps>

  public constructor(props: CtsFloatInputProps) {
    super(props)
    this.state = {
      value: ''
    }
  }

  public componentWillReceiveProps(props: CtsFloatInputProps): void {
    const { value } = props
    this.setState({ value: value || '' })
  }

  // 确定事件
  private onConfirm(): void {
    this.props.onConfirm(this.state.value)
  }

  public render(): JSX.Element {
    const { value } = this.state
    const { className, isOpened, title, type, name, placeholder, maxLength, onCancel } = this.props

    return (
      <CtsFloatLayout className={classNames(className)} isOpened={isOpened} renderContent={
        <Block>
          {
            // 自定义内容
            this.props.renderContent
          }

          <View className='list-edit is-detail'>
            <View className='list-edit-item'>
              <View className='item-left'>{name}</View>
              <View className='item-right'>
                {
                  isOpened &&
                  <AtInput
                    name='value'
                    type={type}
                    value={value}
                    onChange={(val) => { this.setState({ value: val }) }}
                    maxLength={maxLength}
                    placeholder={placeholder}
                    placeholderClass='p-color'
                    clear
                  />
                }
              </View>
            </View>
          </View>
        </Block>
      } onConfirm={this.onConfirm.bind(this)} onCancel={onCancel} title={title} />
    )
  }
}

CtsFloatInput.defaultProps = {
  isOpened: false,
  value: '',
  title: '',
  type: 'text',
  name: '',
  placeholder: '',
  maxLength: 140,
  onCancel() { },
  onConfirm() { }
}

CtsFloatInput.propTypes = {
  isOpened: PropTypes.bool,
  value: PropTypes.string,
  title: PropTypes.string,
  type: PropTypes.oneOf(['text', 'number', 'password', 'phone', 'idcard', 'digit']),
  name: PropTypes.string,
  placeholder: PropTypes.string,
  maxLength: PropTypes.number,
  onCancel: PropTypes.func,
  onConfirm: PropTypes.func
}