import React, { useCallback, useEffect, useState } from 'react'
import styles from './index.module.scss'
import { Cascader } from 'antd-mobile'
import { cityArr } from './data'
import { MessageFu } from '@/utils/message'
import { forwardRef, useImperativeHandle } from 'react'

type Props = {
  ref: any //当前自己的ref，给父组件调用
}

function ZselectCity(_: Props, ref: any) {
  const [visible, setVisible] = useState(false)

  // const [value, setValue] = useState<string[]>(['广东省', '横琴粤澳深度合作区'])
  const [value, setValue] = useState<string[]>([])

  // useEffect(() => {
  //   console.log(123, value)
  //   // ['湖北省', '襄阳市']
  // }, [value])

  // 在中间选择的时候 只有完成2级的选择才让点击确定
  const [tempArr, setTempArr] = useState<string[]>([])

  const getValue = useCallback(() => {
    return value
  }, [value])

  // 可以让父组件调用子组件的方法
  useImperativeHandle(ref, () => ({
    getValue
  }))

  useEffect(() => {
    setTimeout(() => {
      const domBtn: any = document.querySelectorAll('.adm-cascader-header-button')!
      if (domBtn && visible) {
        if (tempArr && tempArr.length >= 2) {
          domBtn[1].style.opacity = '1'
          domBtn[1].style.pointerEvents = 'auto'
        } else {
          domBtn[1].style.opacity = '0.5'
          domBtn[1].style.pointerEvents = 'none'
        }
      }
    }, 100)
  }, [tempArr, visible])

  return (
    <div className={styles.ZselectCity}>
      <div className='ZseTxt' onClick={() => setVisible(true)}>
        {value && value.length >= 2 ? value.join('-') : <span>请选择</span>}
      </div>
      <Cascader
        options={cityArr}
        visible={visible}
        onClose={() => {
          setTempArr([])
          setVisible(false)
        }}
        value={value}
        onConfirm={val => {
          if (tempArr.length < 2) return MessageFu.warning('请选择完整省市!')
          // console.log(123, val)

          setValue(val as string[])
        }}
        onSelect={val => {
          setTempArr(val as string[])
          // ['湖北省']
          // ['湖北省', '襄阳市']
        }}
      />
    </div>
  )
}

export default forwardRef(ZselectCity)
