<template>
  <div class="header-container">
    <el-menu
      mode="horizontal"
      :default-active="'/user'"
      background-color="#fccc0a"
      text-color="#000"
      active-text-color="#654321"
      router
      class="custom-menu"
      :ellipsis="false"
    >
      <!-- 左侧菜单 -->
      <el-menu-item index="/user">
        <el-icon><HomeFilled /></el-icon>
        <span class="menu-text">首页</span>
      </el-menu-item>
      <el-menu-item index="/user/search">
        <el-icon><ShoppingBag /></el-icon>
        <span class="menu-text">搜索商品</span>
      </el-menu-item>
      <el-menu-item index="/user/location">
        <el-icon><Shop /></el-icon>
        <span class="menu-text">选择门店</span>
      </el-menu-item>
      <!-- 显示当前选择的门店名称 -->
      <el-tooltip 
        v-if="branchDetails" 
        placement="bottom"
      >
        <template #content>
          <div style="max-width: 300px">
            <p><strong>地址：</strong>{{ branchDetails.branchAddress }}</p>
            <p><strong>电话：</strong>{{ branchDetails.branchPhone }}</p>
            <p><strong>营业时间：</strong>{{ branchDetails.branchStart }} - {{ branchDetails.branchEnd }}</p>
            <p><strong>状态：</strong>{{ branchDetails.branchStatus === 'open' ? '营业中' : '已关闭' }}</p>
          </div>
        </template>
        <span class="selected-store-name">{{ selectedStoreName || '未选择门店' }}</span>
      </el-tooltip>
      <span v-else class="selected-store-name">{{ selectedStoreName || '未选择门店' }}</span>
      
      <!-- 分隔元素，将右侧菜单推到最右边 -->
      <el-menu-item style="margin-right: auto; visibility: hidden">
        <span class="menu-text"></span>
      </el-menu-item>

      <!-- 非二级菜单的右侧按钮 -->
      <el-menu-item index="/login">
        <el-icon><User /></el-icon>
        <span class="menu-text">登录</span>
      </el-menu-item>
      <el-menu-item index="/register">
        <el-icon><Edit /></el-icon>
        <span class="menu-text">注册</span>
      </el-menu-item>
      <el-menu-item index="/user/shopping">
        <el-icon><ShoppingCart /></el-icon>
        <span class="menu-text">购物车</span>
      </el-menu-item>

      <el-sub-menu index="sub1">
        <template #title>
          <el-icon><Menu /></el-icon>
          <span class="menu-text">更多</span>
        </template>
        <el-menu-item index="/user/orders">
          <el-icon><Document /></el-icon>
          <span class="menu-text">订单查询</span>
        </el-menu-item>
        <!-- 个人主页 -->
        <el-menu-item index="/user/profile">
          <el-icon><User /></el-icon>
          <span class="menu-text">个人主页</span>
        </el-menu-item>
        <!-- 花费图表 -->
        <el-menu-item index="/user/charts">
          <el-icon><PieChart /></el-icon>
          <span class="menu-text">花费图表</span>
        </el-menu-item>
        <el-menu-item @click="handleContactClick">
          <el-icon><Phone /></el-icon>
          <span class="menu-text">联系客服</span>
        </el-menu-item>
        <el-menu-item index="/user/about">
          <el-icon><InfoFilled /></el-icon>
          <span class="menu-text">关于我们</span>
        </el-menu-item>
        <el-menu-item @click="handleLogout">
          <el-icon><SwitchButton /></el-icon>
          <span class="menu-text">退出登录</span>
        </el-menu-item>
      </el-sub-menu>
    </el-menu>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStoreStore } from '@/userStores/store'
import { storeToRefs } from 'pinia'
import { useUserStore } from '@/userStores/user'
import { useAuthStore } from '@/stores/auth'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import {
  HomeFilled,
  ShoppingBag,
  Shop,
  User,
  Edit,
  ShoppingCart,
  Menu,
  Document,
  PieChart,
  Phone,
  InfoFilled,
  SwitchButton
} from '@element-plus/icons-vue'

// 定义分店详情接口
interface BranchDetails {
  branchId: number
  branchName: string
  branchAddress: string
  branchPhone: string
  branchStart: string
  branchEnd: string
  branchStatus: string
  branchBoss: number
  province: string
  latitude: number
  longitude: number
  isDeleted: number
  deletedAt: string | null
  createdAt: string
  updatedAt: string
}

const router = useRouter()
const authStore = useAuthStore()
const userStore = useUserStore()
const store = useStoreStore()
const { selectedStoreName } = storeToRefs(store)

// 响应式变量存储分店详情
const branchDetails = ref<BranchDetails | null>(null)

// 获取分店详情的函数
const fetchBranchDetails = async (storeId: string) => {
  if (!storeId) {
    console.log('没有选择店铺ID')
    return
  }
  
  try {
    const response = await axios.get(`http://127.0.0.1:8080/branch/branch/${storeId}`)
    
    if (response.data.code === 200) {
      branchDetails.value = response.data.data
      console.log('获取到的分店详情:', branchDetails.value)
    } else {
      console.error('获取分店详情失败:', response.data.message)
      ElMessage.error(response.data.message || '获取分店详情失败')
    }
  } catch (error) {
    console.error('获取分店详情异常:', error)
    ElMessage.error('网络错误，获取分店详情失败')
  }
}

onMounted(async () => {
  // 加载本地存储的店铺信息
  store.loadStoreFromLocal()
  
  // 获取当前选中的店铺ID
  const currentStoreId = localStorage.getItem('selectedStoreId')
  
  // 如果有店铺ID，获取分店详情
  if (currentStoreId) {
    await fetchBranchDetails(currentStoreId)
  }
})

const handleContactClick = () => {
  const userId = userStore.getUserId

  if (!userId) {
    ElMessage.error('用户ID不存在,请先登录')
    return
  }

  if (!branchDetails.value) {
    ElMessage.error('店铺信息不存在,请先选择店铺')
    return
  }

  const merchantId = branchDetails.value.branchBoss

  // 使用路由跳转到聊天页面
  router.push({
    path: '/chat',
    query: {
      userId: userId.toString(),
      merchantId: merchantId.toString(),
      currentUserId: userId.toString(),
      type: 'user'
    }
  })
}

// 退出登录处理
const handleLogout = () => {
  // 清除本地用户数据和token
  authStore.logout()
  // 返回登录界面
  router.push('/login')
}
</script>

<style scoped>
.header-container {
  display: flex;
  background-color: #fccc0a;
  height: 80px;
  padding: 0 20px;
  min-width: 1400px;
}

.custom-menu {
  display: flex;
  align-items: center;
  height: 80px;
  line-height: 80px;
  font-size: 16px;
  background-color: transparent;
  width: 100%;
}

.custom-menu .el-menu-item {
  height: 80px;
  line-height: 80px;
  font-size: 16px;
}

.menu-text {
  margin-left: 5px;
}

/* 确保二级菜单正确显示 */
.el-sub-menu .el-menu {
  min-width: 180px;
}

/* 优化显示门店名称的样式 */
.selected-store-name {
  color: #654321;
  margin-left: 10px;
  font-size: 20px;
  cursor: pointer;
}

.selected-store-name:hover {
  text-decoration: underline;
}

/* Tooltip 内容样式 */
:deep(.el-tooltip__content) {
  p {
    margin: 5px 0;
    line-height: 1.5;
  }
}
</style>
