import { View } from '@tarojs/components'
import Taro, { useReady } from '@tarojs/taro'
import { useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.scss'
import IconFont from '@/components/iconfont/iconfont'

interface NavBarPropsType {
  children?: React.ReactNode
  hasLeft?: boolean
  leftSlot?: React.ReactNode
  title?: string
  onClickLeftIcon?: () => void
}
const NavBar = (props: NavBarPropsType) => {
  const { children, hasLeft = false, title = '', leftSlot, onClickLeftIcon } = props
  const handleClickLeftIcon = () => {
    onClickLeftIcon?.()
  }
  const menuButtonRect = useRef<Taro.getMenuButtonBoundingClientRect.Rect | null>(null)
  const systemInfo = useRef<Taro.getSystemInfoSync.Result | null>(null)
  const navBarExtendHeight = useRef<number>(0)
  const rpxToPx = useRef(0)
  const [, setForceUpdate] = useState({})
  const [height, setHeight] = useState(0)
  // 处理布局
  const handleLayout = () => {
    const { statusBarHeight, system } = systemInfo.current!
    const ios = !!(system.toLowerCase().search('ios') + 1)
    if (ios) {
      navBarExtendHeight.current = 4 // 下方扩展4像素高度 防止下方边距太小
    }
    else {
      navBarExtendHeight.current = 0
    }
    const { top, height: menuHeight } = menuButtonRect.current!
    const height = menuHeight + (top - statusBarHeight!) * 2 + statusBarHeight! // 整个navBar的高度
    console.log('height', height)
    setHeight(height)
  }
  useEffect(() => {
    systemInfo.current = Taro.getSystemInfoSync()
    menuButtonRect.current = Taro.getMenuButtonBoundingClientRect()
    rpxToPx.current = systemInfo.current.screenWidth / 750
    setForceUpdate({})
    handleLayout()
  }, [])

  const menuHeight = useMemo(() => {
    return menuButtonRect.current?.height
  }, [menuButtonRect.current])

  const menuTop = useMemo(() => {
    return menuButtonRect.current?.top
  }, [menuButtonRect.current])

  return <View className={styles.navBarContainer} style={{ height: `${height + navBarExtendHeight.current}px` }}>
    <View className={styles.navBar} style={{ height: `${menuHeight}px`, marginTop: `${menuTop}px` }}>
      <View className={styles.left_view}>
        {hasLeft && leftSlot
          ? leftSlot
          : <View className={styles.back} onClick={handleClickLeftIcon}>
            <IconFont name="icon-zhankai" size={50} color="#000000" customStyle={{ transform: 'rotate(90deg)' }}></IconFont>
            <View className={styles.iconName}>返回</View>
          </View>
        }

      </View>
      <View className={styles.title}>{ title || children }</View>
      <View className={styles.right_view}>
      </View>
    </View>

  </View>
}
export default NavBar
