import React, { useState, useEffect, useMemo } from 'react'
import { Radio } from 'antd'
import { GetSelectItemList } from '../../../../apis/process'

const RadioButton = (props) => {

  const { value, onChange, schema, addons } = props
  const { presetValue, disabled, sourceType, options, dictionary } = schema
  const [dictionaryList, setDictionaryList] = useState([])

  useEffect(() => {
    if (addons) {
      addons.setValue(addons.dataPath, presetValue)
    }
  }, [presetValue])

  const onFocus = async () => {
    const { data } = await GetSelectItemList({ nodeName: dictionary })
    if (Array.isArray(data)) {
      setDictionaryList(data)
    }
  }

  const radioChange = (e) => {
    if (addons) {
      addons.setValue(addons.dataPath, e.target.value)
    }
  }

  useEffect(() => {
    if (sourceType === '数据字典' && dictionary) {
      onFocus()
    }
  }, [sourceType, dictionary])

  const enums = useMemo(() => {
    switch (sourceType) {
      case '手动输入':
        return Array.isArray(options) ? options.map(v => v.value) : []
      case '数据字典':
        return Array.isArray(dictionaryList) ? dictionaryList.map(v => v.nodeName) : []
      default:
        return []
    }
  }, [sourceType, options, dictionaryList])

  return (
    <Radio.Group onChange={radioChange} value={value} disabled={disabled}>
      {enums.map(v => <Radio key={v} value={v}>{v}</Radio>)}
    </Radio.Group>
  )

}

export default RadioButton