
import type { CommonEventFunction, TextareaProps } from '@tarojs/components'
import { Button, Image, Text, Textarea, View } from '@tarojs/components'
import type { Ref } from 'react'
import { forwardRef, memo, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from 'react'
import classNames from 'classnames'
import styles from './index.module.scss'
import Popup from '@/components/popup'
import NormalButton from '@/components/normalButton'
import IconFont from '@/components/iconfont/iconfont'
import { useSelector } from '@/reducers/hooks'

interface Params {
  title?: string
  value?: string
  isCompanyName?: boolean
  save: (value: any) => void // 确定保存
}
export interface ModifyModalRef {
  setModalShow: (val: boolean) => void
}
const ModifyModal = (props: Params, ref: Ref<ModifyModalRef>) => {
  const { title = '修改昵称', value: _value = '', isCompanyName = false } = props
  const [value, setValue] = useState('')
  const userInfo = useSelector(state => state.userInfo)
  const canEdit = useRef(true)
  const [tipsComp, setTipsComp] = useState<React.ReactNode | null>(null)
  // 不合法状态
  const isInvalidate = useMemo(() => {
    let flag = false
    // 仅允输入类型为数字、英文、中文
    const Reg = /^[a-zA-Z0-9\u4E00-\u9FA5]+$/
    if (!Reg.test(value)) {
      flag = true
      setTipsComp(() => {
        return <View className={styles['warn-tips']}>
          <View style={{ display: 'flex', alignItems: 'center' }}>
            <IconFont customStyle={{ marginRight: '8rpx' }} name="icon-tips" size={36} color="#f79b31"></IconFont>
            <Text>仅允许输入数字、英文、中文，禁止输入其他任何字符</Text>
          </View>
        </View>
      })
      return flag
    }
    // 修改组织名称
    if (isCompanyName) {
      // 检测是否没机会修改
      if (userInfo.adminUserInfo.first_change_name) {
        canEdit.current = true
        flag = false
        setTipsComp(() => {
          return <View className={styles['warn-tips']}>
            <View style={{ display: 'flex' }}>
              <IconFont customStyle={{ marginRight: '8rpx' }} name="icon-tips" size={36} color="#f79b31"></IconFont>
              <View>公司名称是辨识您身份的重要依据，请谨慎修改。（仅支持修改一次）</View>
            </View>
          </View>
        })
      }
      else {
        flag = true
        canEdit.current = false
        setTipsComp(() => {
          return <View className={styles['warn-tips']}>
            <View style={{ display: 'flex' }}>
              <IconFont customStyle={{ marginRight: '8rpx' }} name="icon-tips" size={36} color="#f79b31"></IconFont>
              <View>您修改的次数已达到上限！如需修改，请联系业务经理修改。</View>
            </View>
          </View>
        })
      }
    }
    return flag
  }, [value, isCompanyName, userInfo])

  useEffect(() => {
    setValue(_value)
  }, [_value])
  // popup输入长度
  const handleTextareaInput: CommonEventFunction<TextareaProps.onInputEventDetail> = (ev) => {
    setValue(ev.detail.value.slice(0, 20))
  }
  // 重置
  const handleTextareaReset = () => {
    setValue('')
  }
  const [textareaBottom, setTextareaBottom] = useState(0)
  const handleBlur: CommonEventFunction<TextareaProps.onBlurEventDetail> = () => {
    setTextareaBottom(0)
  }
  const handleFocus: CommonEventFunction<TextareaProps.onFocusEventDetail> = (ev) => {
    setTextareaBottom(ev.detail.height)
  }
  const [modalShow, setModalShow] = useState(false)
  useImperativeHandle(ref, () => ({ setModalShow }))

  return (
    <Popup onClose={() => setModalShow(false)} title={title} show={modalShow}>
      <View style={{ marginBottom: `${textareaBottom}px` }} className={styles['modify-ickname-content']}>
        {tipsComp}
        <View className={styles['modify-ickname-input']}>
          <Textarea disabled={!canEdit.current} showConfirmBar={false} auto-focus adjustPosition={false} value={value} onBlur={handleBlur} onFocus={handleFocus} onInput={handleTextareaInput} maxlength={20} />
          <Text>{value?.length}/20</Text>
        </View>
        <View className={styles['modify-ickname-tips']}>请设置2-20个字符，可由中文、英文、数字组成</View>
        <View className={styles['modify-ickname-operation']}>
          {
            // 检测是否没机会修改
            isCompanyName
              ? userInfo.adminUserInfo.first_change_name
                ? <>
                  <NormalButton round type="primary" plain onClick={handleTextareaReset} customClassName={classNames(styles.button, styles['modify-ickname-operation-reset'])}>重置</NormalButton>
                  <NormalButton round disabled={isInvalidate} onClick={() => props.save(value)} type="primary" customClassName={classNames(styles.button, styles['modify-ickname-operation-save'])}>保存</NormalButton>
                </>
                : <NormalButton round onClick={() => setModalShow(false)} type="primary" customClassName={classNames(styles.button, styles['modify-ickname-operation-IKnown'])}>知道了</NormalButton>
              : <>
                <NormalButton round type="primary" plain onClick={handleTextareaReset} customClassName={classNames(styles.button, styles['modify-ickname-operation-reset'])}>重置</NormalButton>
                <NormalButton round disabled={isInvalidate} onClick={() => props.save(value)} type="primary" customClassName={classNames(styles.button, styles['modify-ickname-operation-save'])}>保存</NormalButton>

              </>
          }
        </View>
      </View>
    </Popup>
  )
}
export default memo(forwardRef(ModifyModal))
