import Taro, { useState, useEffect } from '@tarojs/taro'
import { AtDrawer, AtCheckbox } from "taro-ui"
import { View, Text, Image } from '@tarojs/components'
import classnames from 'classnames'
import { CustomLabel, ItemExtra, UnEditeableView } from '../index'
import CheckboxItem from './CheckBoxItem'
import CheckBoxListItem from './CheckBoxListItem'
import { OptionsInterface } from '../../interface/dataInterface'
import { getGlobalData, setGlobalData } from '../../util/global_data'
import arrowImg from '../../assets/ic_arrow_right.png'
import './index.scss'

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

const CheckboxItemGroup = ({
  itemExtra,
  editable,
  options,
  term,
  value = [],
  onChange,
  help,
  required,
  hidden,
  optionKey,
  defaultValue,
  onView,
  type = 'tags',
  loadDicData,
  listItemChildren
}: CheckboxItemGroupProps) => {
  const [stateOptions, setStateOptions] = useState(options)
  const [stateValue, setStateValue] = useState(value || defaultValue || [])
  const [drawerShow, setDrawerShow] = useState(false)

  useEffect(() => {
    setStateValue(value || defaultValue || [])
  }, [value])

  useEffect(() => {
    getDicOptions()
  }, [])

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

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

  const checkboxOnChange = val => {
    if (editable || editable === undefined) {
      if (type === 'dropdown') {
        setStateValue(val)
      } else {
        if (value.includes(val)) {
          const newValue = value.filter(i => i !== val)
          onChange(newValue)
        } else {
          const newValue = value.concat(val)
          onChange(newValue)
        }
      }
    }
  }

  const onCancel = () => {
    const showValue = value || defaultValue || []
    setStateValue(showValue)
    setDrawerShow(false)
  }

  const onSubmit = () => {
    onChange(stateValue)
    setDrawerShow(false)
  }

  if (!stateOptions || !stateOptions.length || hidden) {
    return null
  }

  const showValue = value || defaultValue || []

  const unEditeableViewValue = showValue.length && stateOptions.length ? showValue.map(item => (stateOptions as any).find(i => i.value === item).label).join(' ') : ''

  if (editable === false || (editable === undefined && onView)) {
    return <UnEditeableView term={term} help={help} value={unEditeableViewValue} layout={unEditeableViewValue.length >= 14 ? 'column' : 'row'} listItemChildren={listItemChildren} />
  }

  const pickerShowText = stateOptions.map(option => {
    if (showValue.includes(option.value)) {
      return option.label
    }
  }).filter(i => i).join(' ')

  const containerCLs = classnames(['checkbox-container', listItemChildren ? 'item-container' : 'item-container-margin'])

  return (
    <View className={containerCLs}>
      {type === 'dropdown' &&
        <View className='picker-container'>
          <CustomLabel term={term} help={help} required={required} position />
          {/* <AtListItem className='list-item' title='' onClick={() => setDrawerShow(true)} arrow='right' hasBorder={false} extraText={pickerShowText} /> */}
          <View className='list-item' onClick={() => setDrawerShow(true)}>
            <Text className='list-item-text'>{pickerShowText}</Text>
            <Image
              className="list-item-arrow"
              mode="aspectFit"
              src={arrowImg}
            />
          </View>
          <AtDrawer
            show={drawerShow}
            right
            mask
            width='100vw'
          >
            <View className='drawer-wrap'>
              <View className='header'>
                <Text onClick={onCancel}>取消</Text>
                <Text>{term}</Text>
                <Text className='submit' onClick={onSubmit}>确定</Text>
              </View>
              <View className='content'>
                <AtCheckbox
                  options={stateOptions}
                  selectedList={stateValue}
                  onChange={checkboxOnChange}
                />
              </View>
            </View>
          </AtDrawer>
        </View>
      }
      {
        type === 'checkbox' && <View>
          <CustomLabel term={`${term}`} help={help} required={required} />
          {itemExtra && <View className='check-box-extra-wrap'><ItemExtra text={itemExtra} /></View>}
          <View className='checkbox-list-content'>
            {stateOptions.map((item, index) => {
              const { value, label } = item;
              return <CheckBoxListItem
                key={value}
                className={index === stateOptions.length - 1 ? 'last-child' : ''}
                checked={showValue.includes(value)}
                onClick={() => checkboxOnChange(value)}
              >
                <Text>
                  {label}
                </Text>
              </CheckBoxListItem>
            })}
          </View>
        </View>
      }
      {
        type === 'tags' &&
        <View>
          <CustomLabel term={`${term}`} help={help} required={required} />
          {itemExtra && <View className='check-box-extra-wrap'><ItemExtra text={itemExtra} /></View>}
          <View className='checkbox-content'>
            {stateOptions.map(item => {
              const { value, label } = item;
              return <CheckboxItem
                className='--item'
                key={value}
                checked={showValue.includes(value)}
                compStyle={{
                  margin: '2px'
                }}
                onClick={() => checkboxOnChange(value)}
              >
                <Text>
                  {label}
                </Text>
              </CheckboxItem>
            })}
          </View>
        </View>
      }
      {(type === 'dropdown' && itemExtra) && <ItemExtra text={itemExtra} />}
    </View>
  )
}

export default CheckboxItemGroup

