import { useEffect, useState } from 'react'
import { Picker, View } from '@tarojs/components'
import './style.scss'

export default (props) => {
  const { kv, value, onChange, dicts, placeholder, mode, ...leftProps } = props
  const [rangeKey, rangeVal] = kv || ['label', 'value']

  const [inx, setInx] = useState()
  const [text, setText] = useState()

  const handleChange = (e) => {
    if (mode && mode !== 'selector') {
      onChange(e.detail.value)
      return
    }

    const index = e.detail.value - 0
    const item = dicts[index]
    if (onChange) {
      onChange(item[rangeVal], item)
    }
  }

  useEffect(() => {
    if (dicts && dicts.length > 0) {
      if (value !== undefined && value !== null) {
        for(let i = 0; i < dicts.length; i += 1) {
          if (dicts[i][rangeVal] === value) {
            setInx(i)
            setText(dicts[i][rangeKey])
            break;
          }
        }
      }
    }
  }, [dicts, rangeKey, rangeVal, value])

  useEffect(() => {
    if (mode && mode !== 'selector') {
      setText(value)
    }
  }, [mode, value])

  return (
    <Picker
      className='g-picker'
      rangeKey={rangeKey}
      onChange={handleChange}
      value={inx}
      range={dicts}
      mode={mode||'selector'}
      {...leftProps}
    >
      <View>{text || placeholder || '请选择'}</View>
    </Picker>
  )
}
