import Taro, { useState, useEffect } from '@tarojs/taro'
import { View, Text, Picker, Image } from '@tarojs/components'
import classnames from 'classnames'
import { OptionsInterface } from '../../interface/dataInterface'
import { CustomLabel, ItemExtra, UnEditeableView } from '../index'
import { getGlobalData, setGlobalData } from '../../util/global_data'
import Tag from './Tag'
import CustomRadio from './CustomRadio'
import './index.scss'
import arrowImg from '../../assets/ic_arrow_right.png'

interface RadioButtonGroupProps {
  itemExtra?: string
  name: string
  term: string
  value?: any
  defaultValue?: any
  onChange: (value) => void
  editable?: boolean
  help?: string
  required?: boolean
  options: Array<OptionsInterface>
  hidden?: boolean
  optionKey?: string
  onView?: boolean
  type: 'radio' | 'dropdown' | 'group'
  loadDicData?: (optionKey) => Promise<any>
  listItemChildren?: boolean
}

const RadioButtonGroup = ({
  itemExtra,
  editable,
  options,
  term,
  value,
  onChange,
  help,
  required,
  hidden,
  optionKey,
  defaultValue,
  onView,
  type = 'group',
  loadDicData,
  listItemChildren
}: RadioButtonGroupProps) => {
  const [stateOptions, setStateOptions] = useState(options)
  useEffect(() => {
    getDicOptions()
  }, [])

  const getDicOptions = () => {
    if (optionKey && loadDicData) {
      handlerGetDicOptions(optionKey)
        .then((res: Array<any>) => {
          if (res) {
            setStateOptions(res)
          }
        })
        .catch(err => {
          // console.log('err', err)
        })
    }
  }

  const handlerGetDicOptions = (optionKey: string) => {
    const globalId = `radio-${optionKey}`
    return new Promise((resolve, reject) => {
      if (getGlobalData(globalId)) {
        resolve(getGlobalData(globalId))
      } else if (loadDicData) {
        loadDicData({ key: optionKey }).then((res) => {
          if (res && res.length) {
            resolve(res)
            setGlobalData(globalId, res)
          } else {
            reject()
          }
        })
      } else {
        reject()
      }
    })
  }

  const radioOnChange = (radioValue) => {
    const showValue = value !== undefined ? value : defaultValue
    if (editable || editable === undefined) {
      let newValue = radioValue
      if (type === 'dropdown') {
        const { value } = radioValue.detail
        newValue = stateOptions[parseInt(value)].value
      }
      if (newValue === showValue) {
        onChange('')
      } else {
        onChange(newValue)
      }
    }
  }

  if (!stateOptions || !stateOptions.length || hidden) {
    return null
  }
  const showValue = value !== undefined ? value : defaultValue
  if (editable === false || (editable === undefined && onView)) {
    const item = stateOptions.find(item => item.value === showValue) || { label: '' }
    return <UnEditeableView term={term} help={help} value={item.label} listItemChildren={listItemChildren} />
  }

  const pickerShowText = stateOptions.find(item => item.value === showValue) ? (stateOptions.find(item => item.value === showValue) as any).label : ''
  const pickerValue = stateOptions.map(item => item.value).indexOf(showValue)
  const containerCLs = classnames(['radio-group-container', listItemChildren ? 'item-container' : 'item-container-margin'])

  return (
    <View className={containerCLs}>
      {type === 'dropdown' &&
        <View className='radio-picker-container'>
          <CustomLabel term={term} help={help} required={required} position />
          <Picker
            mode='selector'
            onChange={radioOnChange}
            value={pickerValue}
            range={stateOptions.map(i => i.label)}
            className='radio-picker-wrap'
          >
            <View className='radio-picker-content'>
              <Text className='radio-picker-text'>{pickerShowText}</Text>
              <Image
                className="picker-arrow"
                mode="aspectFit"
                src={arrowImg}
              />
            </View>
          </Picker>
        </View>
      }
      {
        type === 'radio'
        && <View className='radio-content'>
          <CustomLabel term={`${term}`} help={help} required={required} />
          {itemExtra && <View className='radio-item-extra-wrap'><ItemExtra text={itemExtra} /></View>}
          <View
            className='radio-wrap'
          >
            {stateOptions.map((item, index) => {
              return <View
                onClick={() => radioOnChange(item.value)}
                key={item.value}>
                <CustomRadio
                  active={showValue === item.value}
                  className={index === stateOptions.length - 1 ? 'last-child' : ''}
                >
                  {item.label}
                </CustomRadio>
              </View>
            })}
          </View>
        </View>
      }
      {type === 'group' &&
        <View>
          <CustomLabel term={`${term}`} help={help} required={required} />
          {itemExtra && <View className='radio-item-extra-wrap'>
            <ItemExtra text={itemExtra} />
          </View>}
          <View className='radio-group-content'>
            {stateOptions.map(item => {
              return <View
                onClick={() => radioOnChange(item.value)}
                key={item.value}>
                <Tag
                  active={showValue === item.value}
                >
                  {item.label}
                </Tag>
              </View>
            })}
          </View>
        </View>
      }
      {(itemExtra && type === 'dropdown') && <ItemExtra text={itemExtra} />}
    </View>
  )
}

export default RadioButtonGroup


