<template>
  <header class="header-container" :class="{ 'hide-shadow': hideShadow }"
    :style="{ height, zIndex, lineHeight: height }">
    <div class="opts left-opts" v-if="$slots['left-opts'] || title || $slots.title">
      <a-button v-if="showBack" @click="back">返回</a-button>
      <a-button v-if="showHome" @click="backToHome">首页</a-button>
      <slot name="left-opts" />
    </div>
    <div class="title" v-if="title || $slots.title">
      <slot name="title">
        {{ title }}
      </slot>
    </div>
    <div class="opts right-opts" v-if="$slots['right-opts'] || title || $slots.title">
      <slot name="right-opts" />
      <a-button @click="handleLogout" type="primary" danger
        v-if="showLogout && username">退出：{{ username }}</a-button>
    </div>
    <slot />
  </header>
</template>

<script setup>
import { useRouter } from 'vue-router';
import { Modal } from 'ant-design-vue';
import { useAuthStore, useUserStore } from '@/store';
import { storeToRefs } from 'pinia';

defineProps({
  showHome: {
    type: Boolean,
    default: false,
  },
  showBack: {
    type: Boolean,
    default: false,
  },
  showLogout: {
    type: Boolean,
    default: true,
  },
  title: {
    type: String,
    default: null,
  },
  hideShadow: {
    type: Boolean,
    default: false
  },
  height: {
    type: String,
    default: '6vh',
  },
  zIndex: {
    type: Number,
    default: 999,
  }
});

const emit = defineEmits(['back']);
const router = useRouter();

const userStore = useUserStore();
const { username } = storeToRefs(userStore);

const authStore = useAuthStore();
const handleLogout = () => {
  Modal.confirm({
    title: '提示',
    content: `是否确认退出登录：${ username.value }`,
    okText: '确定',
    cancelText: '取消',
    onOk: () => {
      authStore.logout();
    },
  });
};

const back = () => {
  emit('back');
  defaultBack();
};

const defaultBack = () => {
  router.go(-1);
};

const backToHome = () => {
  router.push({ name: 'Index' });
};
</script>

<style scoped lang="scss">
.header-container {
  width: 100%;
  padding: 0 1rem;
  display: flex;
  align-items: center;
  gap: 10px;
  background-color: #1f2e54;
  color: #fff;
  box-shadow: rgba(0, 0, 0, 0.1) 0px 4px 6px -1px, rgba(0, 0, 0, 0.06) 0px 2px 4px -1px;

  &.hide-shadow {
    box-shadow: none;
  }

  .title {
    flex: 14;
    color: #fff;
    white-space: nowrap;
    overflow: hidden;
    text-align: center;
    text-overflow: ellipsis;
    font-size: clamp(16px, 2.5vw, 32px);
    font-weight: bold;
  }

  .opts {
    height: 100%;
    flex: 5;
    display: flex;
    align-items: center;
    flex-shrink: 0;
    gap: 8px;

    &.left-opts {
      justify-content: flex-start;
    }

    &.right-opts {
      justify-content: flex-end;
    }
  }
}
</style>
