import { Textarea, View } from '@tarojs/components'
import { memo, useEffect, useMemo, useState } from 'react'
import classnames from 'classnames'
import styles from './index.module.scss'

// 其他说明
interface Param {
  title?: string
  onChange?: (val: string) => void
  placeholder?: string
  defaultValue?: string
  onlyRead?: false|true
}
const TextareaEnhance = ({ onChange, title = '', placeholder = '请输入', defaultValue, onlyRead = false }: Param) => {
  const [descData, setDescData] = useState({
    number: 0,
    value: '',
    count: 200,
    show: false,
  })
  const getDesc = (value = '') => {
    let res = value
    if (value.length > descData.count) {
      res = value.slice(0, descData.count)
    }
    setDescData({ ...descData, number: res.length, value: res })
    onChange?.(res)
  }

  useEffect(() => {
    getDesc(defaultValue)
  }, [defaultValue])

  const toggleShowRealTextarea = (show) => {
    setDescData({ ...descData, show })
  }
  return (
    <View className={styles.other_desc}>
      <View className={styles.title}>{title}</View>
      <View className={styles.textarea}>
        {(descData.show && !onlyRead)
          ? <Textarea autoFocus value={descData.value} onBlur={() => toggleShowRealTextarea(false)} className={styles.textarea_con} cursorSpacing={100} maxlength={descData.count} onInput={e => getDesc(e.detail.value)}></Textarea>
          : <View className={classnames(styles.textarea_con_pretend, descData.value && styles.textarea_con_pretend_ed)} onClick={() => toggleShowRealTextarea(true)}>{descData.value || placeholder}</View>
        }
        <View className={styles.descDataNum}>{`${descData.number}/${descData.count}`}</View>
      </View>
    </View>
  )
}
export default memo(TextareaEnhance)
