
import { useState, useEffect, useMemo } from 'react'
import Taro from '@tarojs/taro'
import homeBlack from '@/assets/icons/comm/home.png'
import homeWhite from '@/assets/icons/comm/home_white.png'
import gobackBlack from '@/assets/icons/comm/goback.png'
import gobackWhite from '@/assets/icons/comm/goback_white.png'

import './style.less'

export default (props) => {
  const { bgImg, logo, title = '首页', home } = props

  // 菜单胶囊
  const menuBound = useMemo(() => Taro.getMenuButtonBoundingClientRect(), [])
  // 整体顶部导航
  const navStyle = useMemo(() => {
    return {
      height: `${menuBound.bottom + 8}px`,
      backgroundImage: bgImg ? `url(${bgImg})` : 'none',
    }
  }, [menuBound.bottom, bgImg])
  // 导航栏
  const navBarStyle = useMemo(() => {
    return {
      top: `${menuBound.top}px`,
      height: `${menuBound.height}px`
    }
  }, [menuBound.top, menuBound.height])
  // 导航栏按钮
  const actionStyle = useMemo(() => {
    return {
      width: `${menuBound.width + 8}px`,
      paddingLeft: '8px',
      lineHeight: `${menuBound.height}px`,
      height: `${menuBound.height}px`,
    }
  }, [menuBound.width, menuBound.height])
  // 导航栏标题
  const contentStyle = useMemo(() => {
    const screenWidth = menuBound.right + 8;
    return {
      width: `${screenWidth - menuBound.width * 2 - 16}px`,
      color: bgImg ? '#fff' : '#333',
      lineHeight: `${menuBound.height}px`,
      height: `${menuBound.height}px`,
      paddingLeft: '8px',
      paddingRight: '8px',
    }
  }, [menuBound.width, menuBound.height, menuBound.right, bgImg])
  // logo
  const logoStyle = useMemo(() => {
    return {
      width: `${menuBound.height}px`,
      height: `${menuBound.height}px`,
    }
  }, [menuBound.height])

  const handleAction = () => {
    if (home || logo) return;

    if (Taro.getCurrentPages().length > 1) {
      Taro.navigateBack({ delta: 1 })
    }
  }

  useEffect(() => {
    Taro.setNavigationBarTitle(title)
  }, [title])

  return (
    <view className='custom-nav' style={navStyle}>
      <view className='custom-nav-bar' style={navBarStyle}>
        <view className='custom-nav-bar-action' style={actionStyle}>
          {
            !!logo && <image src={logo} className='custom-nav-bar-logo' mode='aspectFit' style={logoStyle} />
          }
          {
            !logo && !home && (
              <view className='custom-nav-bar-action-btns'>
                <view className='custom-nav-bar-action-part' onClick={handleAction}>
                  <image src={bgImg ? gobackWhite : gobackBlack} mode='aspectFit' />
                </view>
                <view className='custom-nav-bar-action-part'>
                  <image src={bgImg ? homeWhite : homeBlack} mode='aspectFit' />
                </view>
              </view>
            )
          }
        </view>
        <view className='custom-nav-bar-content' style={contentStyle}>{title}</view>
      </view>
    </view>
  )
}
