<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import axios from 'axios'
import { ArrowDown, Bell } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { ChatDotRound } from '@element-plus/icons-vue'

// 配置axios基础URL
axios.defaults.baseURL = 'http://localhost:8080'

// 类型定义
interface UserInfo {
  accountId: number
  accountName: string
  accountPassword?: string
  accountPhone?: string | null
  accountType?: string
  accountImg?: string | null
  accountGender?: string
  accountTag?: string | null
  salary?: number | null
  isDeleted?: number
  deletedAt?: string | null
  createdAt?: string
  updatedAt?: string
}

// StorageManager 工具类
class StorageManager {
  static getUserInfo(): UserInfo | null {
    const userInfoStr = localStorage.getItem('userInfo')
    if (userInfoStr) {
      try {
        return JSON.parse(userInfoStr)
      } catch {
        return null
      }
    }
    return null
  }

  static setUserInfo(userInfo: UserInfo): void {
    localStorage.setItem('userInfo', JSON.stringify(userInfo))
  }

  static clearUserInfo(): void {
    localStorage.removeItem('userInfo')
    localStorage.removeItem('token')
  }

  static getToken(): string | null {
    return localStorage.getItem('token')
  }
}

const router = useRouter()
const authStore = useAuthStore()

// 响应式数据
const user = ref({ name: '加载中...' })
const userAvatar = ref<string>('')
const loading = ref(false)

// emit定义
const emit = defineEmits(['collapse-change', 'button-click', 'input-change'])

// 获取本地存储的accountId
const getAccountId = (): number | null => {
  const userInfo = StorageManager.getUserInfo()
  return userInfo ? userInfo.accountId : null
}

// 获取用户信息
const fetchUserInfo = async () => {
  const accountId = getAccountId()

  if (!accountId) {
    user.value.name = '未登录'
    return
  }

  loading.value = true

  try {
    // 获取token
    const token = StorageManager.getToken()

    // 调用API
    const response = await axios.get(`/user/customers/${accountId}`, {
      headers: {
        'Authorization': token ? `Bearer ${token}` : ''
      }
    })

    // 直接处理返回的用户数据
    if (response.data && response.data.accountId) {
      const userData: UserInfo = response.data
      user.value.name = userData.accountName || '用户'
      userAvatar.value = userData.accountImg || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'

      // 更新本地存储的用户信息（不包含密码）
      const { accountPassword, ...safeUserData } = userData
      StorageManager.setUserInfo(safeUserData as UserInfo)
    } else {
      console.error('获取用户信息失败: 数据格式错误')
      user.value.name = '获取失败'
      ElMessage.error('获取用户信息失败')
    }
  } catch (error: any) {
    console.error('获取用户信息出错:', error)
    user.value.name = '获取失败'

    // 根据错误状态码显示不同的错误信息
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      // 清除本地存储并跳转到登录页
      StorageManager.clearUserInfo()
      authStore.logout()
      router.push('/login')
    } else if (error.response?.status === 404) {
      ElMessage.error('用户不存在')
    } else {
      ElMessage.error('网络错误，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 处理下拉菜单命令
const handleDropdownCommand = (command: string) => {
  if (command === 'logout') {
    // 清除本地用户数据和token
    StorageManager.clearUserInfo()
    authStore.logout()
    // 返回登录界面
    router.push('/login')
    ElMessage.success('退出登录成功')
  }
}

// 处理通知点击
const handleClick = () => {
  // 派发事件，不传参数
  emit('button-click')
}

// 组件挂载时获取用户信息
onMounted(() => {
  fetchUserInfo()
})
</script>

<template>
  <el-row>
    <el-col :span="8">
      <div class="menu-header">
        <span class="divider">|</span>
        <span class="title">商户线上经营平台</span>
      </div>
    </el-col>
    <el-col :span="8"> </el-col>
    <el-col :span="8">
      <div class="user-section">
        <el-avatar :size="40" :src="userAvatar" alt="用户头像">
        </el-avatar>

        <el-dropdown @command="handleDropdownCommand">
          <span class="user" v-loading="loading">
            {{ user.name }}
            <el-icon class="el-icon--right"><arrow-down /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-item divided command="logout">退出账号</el-dropdown-item>
          </template>
        </el-dropdown>
        <span class="divider">|</span>
                <el-icon class="notification-icon" @click="handleClick">
          <Bell />
        </el-icon>
      </div>
    </el-col>
  </el-row>
  
</template>

<style scoped>
.menu-header,
.user-section {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 0 20px;
  height: 60px;
}

.user-section {
  justify-content: flex-end;
}

.logo {
  height: 40px;
  width: auto;
  object-fit: contain;
}

.divider {
  font-size: 24px;
  font-weight: bold;
  color: #909399;
  margin: 0 8px;
}

.title {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  letter-spacing: 1px;
}

.user {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-radius: 4px;
  transition: all 0.3s ease;
  outline: unset;
}

.notification-icon {
  color: #909399;
  cursor: pointer;
  transition: color 0.3s;
}

.notification-icon:hover {
  color: #409eff;
}

/* 响应式优化 */
@media (max-width: 768px) {
  .title {
    font-size: 16px;
  }

  .logo {
    height: 32px;
  }

  .divider {
    font-size: 20px;
  }
}
</style>
