<template>
  <view 
    :class="['nana-nav-title', innerClass]"
    :style="{
      backgroundColor: theme.resolveThemeColor(backgroundColor),
      height: theme.resolveThemeSize(height),
      paddingLeft: align === 'left' ? theme.resolveThemeSize('NavBarLeftModePaddingLeft', 20) : undefined,
      ...props.innerStyle,
    }"
  >
    <view 
      v-if="align !== 'left'"
      class="nana-nav-button-wrapper" :style="{
        marginRight: rightPillSpace ? `${menuButtonInfo.width}px` : undefined,
        width: theme.resolveThemeSize(leftWidth),
      }"
    >
      <slot v-if="showLeftButton && leftButton" name="left">
        <IconButton 
          :icon="getButton(leftButton)"
          v-bind="iconProps"
          shape="square-full"
          @click="handleButtonNavBack(leftButton, () => emit('leftButtonPressed'))"
        />
      </slot>
      <IconButton v-else icon="space" shape="square-full" />
      <slot name="left-custom" />
    </view>
    <slot name="center">
      <HorizontalScrollText
        v-if="titleScroll"
        :outerStyle="{
          ...titleTextStyle,
          ...props.titleStyle,
          paddingLeft: 0,
          paddingRight: 0,
        }"
        :innerClass="titleClass"
        :color="textColor"
        :textAlign="align"
        :text="title"
      />
      <Text
        v-else
        :outerStyle="{
          ...titleTextStyle,
          ...props.titleStyle,
          flex: 1,
        }"
        :innerClass="titleClass"
        :textAlign="align"
        :color="textColor"
        :text="title"
      />
    </slot>
    <view 
      class="nana-nav-button-wrapper-end"
      :style="{
        marginRight: rightPillSpace ? `${menuButtonInfo.width ?? 0}px` : undefined,
        minWidth: theme.resolveThemeSize(height),
      }"
    >
      <slot v-if="showRightButton && rightButton" name="right">
        <IconButton 
          :icon="getButton(rightButton)"
          v-bind="iconProps"
          shape="square-full"
          @click="handleButtonNavBack(rightButton, () => emit('rightButtonPressed'))"
        />
      </slot>
      <IconButton v-else icon="space" shape="square-full" />
    </view>
  </view>
</template>

<script setup lang="ts">
import type { IconProps } from '../basic/Icon.vue';
import { propGetThemeVar, useTheme } from '../theme/ThemeDefine';
import { DynamicSize } from '../theme/ThemeTools';
import HorizontalScrollText from '../typography/HorizontalScrollText.vue';
import Text from '../basic/Text.vue';
import IconButton from '../basic/IconButton.vue';
import { isTopLevelPage } from '../utils/PageAction';

export type NavBarButtonTypes = 'back'|'menu'|'search'|'setting'|'custom';

export interface NavBarProps {
  /**
   * 标题栏高度
   * @default '44px'
   */
  height?: number|string;
  /**
   * 左侧按钮
   * 
   * 特殊按钮:
   * * back：返回按钮
   * * menu：菜单按钮
   * * search：搜索按钮
   * * setting：设置按钮
   * @default ''
   */
  leftButton?: NavBarButtonTypes|string,
  /**
   * 标题文字，支持自定义元素
   */
  title?: string,
  /**
   * 标题对齐
   * @default 'center'
   */
  align?: 'center'|'left',
  /**
   * 右侧按钮
   */
  rightButton?: NavBarButtonTypes|string,
  /**
   * 是否显示右侧按钮
   * @default true
   */
  showRightButton?: boolean;
  /**
   * 是否显示右侧按钮的胶囊间距
   */
  rightPillSpace?: boolean,
  /**
   * 手动指定右侧按钮的胶囊间距（像素）
   * @default 50
   */
  rightPillSpaceForce?: number,
  /**
   * 是否显示左侧按钮
   * @default true
   */
  showLeftButton?: boolean;

  leftWidth?: number|string;
  /**
   * 自定义背景颜色
   */
  backgroundColor?: string;
  /**
   * 自定义文字颜色
   * @default Color.black
   */
  textColor?: string;
  /**
   * 自定义样式
   */
  innerStyle?: object;
  /**
   * 自定义标题文字样式
   */
  titleStyle?: object;
  /**
   * 自定义标题文字样式
   */
  titleClass?: any;
  /**
   * 标题文字超出时，是否自动滚动
   * @default true
   */
  titleScroll?: boolean;
  /**
   * 图标透传样式
   */
  iconProps?: IconProps;
  /**
   * 自定义类名
   */
  innerClass?: any;
}

function getButton(type: NavBarButtonTypes|string) {
  let button = '';
  switch (type) {
    case 'back': button = 'arrow-left-bold'; break;
    case 'menu': button = 'elipsis'; break;
    case 'search': button = 'search'; break;
    case 'setting': button = 'setting'; break;
    default: button = type; break;
  }
  return button;
}

const emit = defineEmits([  'leftButtonPressed', 'rightButtonPressed' ]);

const theme = useTheme();

const props = withDefaults(defineProps<NavBarProps>(), {
  titleScroll: true,
  align: () => propGetThemeVar('NavBarAlign', 'center'),
  height: () => propGetThemeVar('NavBarHeight', '44px'),
  showLeftButton: true,
  showRightButton: true,
  rightPillSpaceForce: 50,
  textColor: () => propGetThemeVar('NavBarTitleColor', 'black'),
});

// #ifdef MP
const menuButtonInfo = uni.getMenuButtonBoundingClientRect();
// #endif

// #ifndef MP
const menuButtonInfo = {
  width: props.rightPillSpaceForce,
};
// #endif

const titleTextStyle = theme.useThemeStyle({
  flex: 1,
  fontSize: DynamicSize('NavBarTitleFontSize', 30),
  paddingLeft: DynamicSize('NavBarTitlePaddingHorizontal', 15),
  paddingRight: DynamicSize('NavBarTitlePaddingHorizontal', 15),
});

function handleButtonNavBack(button: NavBarButtonTypes|string, callback: () => void) {
  if (button === 'back') {
    if (isTopLevelPage()) {
      uni.reLaunch({
        url: theme.getVar('AppHomePage', '/pages/index/index'),
      });
    } else {
      uni.navigateBack({
        fail() {
          uni.reLaunch({
            url: theme.getVar('AppHomePage', '/pages/index/index'),
          }); 
        },
      });
    }
  } else {
    callback();
  }
}

</script>

<style>
.nana-nav-title {
  position: relative;
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
.nana-nav-button-wrapper {
  position: relative;
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  height: 100%;
  flex-shrink: 0;
}
.nana-nav-button-wrapper-end {
  position: relative;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  height: 100%;
  flex-shrink: 0;
}
</style>

