<template>
  <view class="pages-header" :style="{ paddingTop: statusBarHeight + 'px' }">
    <view class="header">
      <view v-if="showBack" class="back">
        <cwg-icon name="dropdown" class="back-icon" :color="color" @click="handleBack" />
      </view>

      <view>{{ headerTitleReady ? headerTitle : '' }}</view>
    </view>
    <view class="header-r">
      <slot></slot>
    </view>
  </view>
</template>

<script setup lang="ts">
import useRouter from "@/hooks/useRouter";
import useRoute from '@/hooks/useRoute'
import { computed, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import useGlobalStore from '@/stores/use-global-store'
const { t } = useI18n()
const router = useRouter()
const route = useRoute()
const globalStore = useGlobalStore()
const statusBarHeight = computed(() => globalStore.statusBarHeight);
const showBack = computed(() => {
  // 不显示返回按钮的页面
  const noBackPages = [
    '/',
    '/pages/card/index',
    '/pages/wallet/index',
    '/pages/mine/index',
    '/pages/login/index'
  ]

  return !noBackPages.includes(route.path)
})
function slashToDash(str: string) {
  return str.replace(/\//g, '.');
}
function getTranslationKey(): string {
  const path = route.path
  let key = ''
  if (!path) return ''
  if (path === '/') {
    key = 'pages.card.index'
  } else if (path.startsWith()) {
    key = path.slice(7)
  } else {
    key = path.slice(1)
  }
  return slashToDash(key)
}
const headerTitleReady = computed(() => {
  if (props.title) return true
  if (!route.path) return false
  const key = getTranslationKey()
  return !!t(key)
})

const headerTitle = computed(() => {
  if (props.title) return props.title
  const key = getTranslationKey()
  return t(key) || ''
})

const props = defineProps<{
  title: string;
  color: string;
}>();
function handleBack() {
  router.back();
}
</script>

<style scoped lang="scss">
@import "@/uni.scss";

.pages-header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  z-index: 1111;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 px2rpx(24);
  box-sizing: border-box;

  .header {
    position: relative;
    text-align: left;
    font-size: var(--font-size-22);
    color: var(--white);
    font-weight: 700;
    margin: px2rpx(10) 0;
    height: px2rpx(40);
    display: flex;
    align-items: center;
    line-height: px2rpx(40);

    .back {
      display: flex;
      align-items: center;
      justify-content: center;
      width: px2rpx(24);
      height: px2rpx(24);
      border-radius: 50%;
      margin-right: px2rpx(20);
    }

    .back-icon {
      line-height: px2rpx(71);
      font-size: var(--font-size-20);
      cursor: pointer;
    }
  }
}

.wallet-header {
  .header {
    color: #fff;
  }
}
</style>
