<template>
  <el-dropdown trigger="click">
    <div class="avatar">
      <img :src="avatarUrl" alt="avatar" />
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item @click="openDialog('infoRef')">
          <el-icon><User /></el-icon>{{ $t("header.personalData") }}
        </el-dropdown-item>
        <el-dropdown-item @click="openDialog('passwordRef')">
          <el-icon><Edit /></el-icon>{{ $t("header.changePassword") }}
        </el-dropdown-item>
        <el-dropdown-item @click="openDialog('blackListRef')">
          <el-icon><Edit /></el-icon>{{ $t("header.blacklist") }}
        </el-dropdown-item>
        <el-dropdown-item divided @click="logout">
          <el-icon><SwitchButton /></el-icon>{{ $t("header.logout") }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  <!-- infoDialog -->
  <InfoDialog ref="infoRef" @avatar-updated="handleAvatarUpdated" />
  <!-- passwordDialog -->
  <PasswordDialog ref="passwordRef" />
  <!---blackListDialog--->
  <BlackListDialog ref="blackListRef" />
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from "vue";
import { LOGIN_URL } from "@/config";
import { useRouter } from "vue-router";
import { logoutApi } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useAuthStore } from "@/stores/modules/auth";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { ElMessageBox, ElMessage } from "element-plus";
import InfoDialog from "./InfoDialog.vue";
import PasswordDialog from "./PasswordDialog.vue";
import BlackListDialog from "./BlackListDialog.vue";
import { getMerchantByPhone } from "@/api/modules/homeEntry";
import { localGet, localSet } from "@/utils/index";
import { resetRouter } from "@/routers/index";
import defaultAvatar from "@/assets/images/avatar.gif";
import { localClear } from "@/utils";

const router = useRouter();
const userStore = useUserStore();
const authStore = useAuthStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

// 头像URL，先从本地存储读取，避免刷新后显示默认图片
const getCachedAvatar = () => {
  const userInfo = localGet("geeker-user")?.userInfo || {};
  const phone = userInfo.phone;
  if (phone) {
    const cachedAvatar = localGet(`avatar_${phone}`);
    return cachedAvatar || "";
  }
  return "";
};

const headImg = ref<string>(getCachedAvatar());

// 计算头像URL，如果有上传的头像则使用上传的，否则使用默认头像
const avatarUrl = computed(() => {
  console.log(headImg.value);
  return headImg.value && headImg.value !== null && headImg.value !== "" ? headImg.value : defaultAvatar;
});

// 处理头像更新事件
const handleAvatarUpdated = async (newAvatarUrl?: string) => {
  console.log("收到头像更新事件，新头像URL:", newAvatarUrl);
  const userInfo = localGet("geeker-user")?.userInfo || {};
  if (newAvatarUrl && newAvatarUrl.trim() !== "") {
    // 如果传递了新的头像URL，直接更新
    headImg.value = newAvatarUrl;
    if (userInfo.phone) {
      localSet(`avatar_${userInfo.phone}`, newAvatarUrl);
      console.log("直接更新头像URL:", newAvatarUrl, "当前 headImg.value:", headImg.value);
    }
  } else {
    // 如果没有传递URL或URL为空，则重新获取用户信息
    console.log("头像URL为空，重新获取用户信息");
    await getUserInfo();
  }
};

// 获取用户信息
const getUserInfo = async () => {
  const userInfo = localGet("geeker-user")?.userInfo || {};
  if (userInfo.phone) {
    // 先检查登录时存储的用户信息中是否有头像
    const loginAvatarUrl = userInfo.headImg || userInfo.avatar || "";
    if (loginAvatarUrl && loginAvatarUrl.trim() !== "") {
      headImg.value = loginAvatarUrl;
      localSet(`avatar_${userInfo.phone}`, loginAvatarUrl);
      console.log("从登录信息中获取头像URL:", loginAvatarUrl);
    }

    try {
      const res: any = await getMerchantByPhone({ phone: userInfo.phone });
      console.log("API返回数据:", res);
      if (res.code == 200 && res.data) {
        // 兼容 headImg 和 avatar 两种字段名
        const avatarUrl = res.data.headImg || res.data.avatar || "";
        if (avatarUrl && avatarUrl.trim() !== "") {
          headImg.value = avatarUrl;
          // 缓存头像URL到本地存储
          localSet(`avatar_${userInfo.phone}`, avatarUrl);
          console.log("设置头像URL:", headImg.value);
        } else {
          console.warn("API返回的头像URL为空，保持使用缓存或默认头像");
          // 如果API返回空，但本地有缓存，保持使用缓存
          if (!headImg.value) {
            const cached = getCachedAvatar();
            if (cached) {
              headImg.value = cached;
            }
          }
        }
      } else {
        console.warn("获取用户信息失败，响应码:", res.code);
      }
    } catch (error) {
      // API调用失败时，如果本地有缓存，继续使用缓存的头像
      if (!headImg.value) {
        const cached = getCachedAvatar();
        if (cached) {
          headImg.value = cached;
        }
      }
    }
  } else {
    console.warn("用户信息中没有phone字段");
  }
};

// 组件挂载时获取用户信息
onMounted(() => {
  getUserInfo();
});

// 退出登录
const logout = () => {
  ElMessageBox.confirm("您是否确认退出登录?", "温馨提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    try {
      // 1.执行退出登录接口
      // await logoutApi();

      // 2.清除动态路由
      resetRouter();

      // 3.清除菜单列表和权限信息
      authStore.authMenuList = [];
      authStore.authButtonList = {};
      authStore.routeName = "";

      // 4.清除 tabs、keepAlive 数据
      await tabsStore.setTabs([]);
      await keepAliveStore.setKeepAliveName([]);

      // 5.清除 Token 和用户信息
      userStore.setToken("");
      userStore.setUserInfo({ name: "" });
      localClear();

      // 6.重定向到登陆页
      router.replace(LOGIN_URL);
      ElMessage.success("退出登录成功！");
    } catch (e) {
      console.error("退出登录失败:", e);
      // 即使出错也要清除数据并跳转
      await tabsStore.setTabs([]);
      await keepAliveStore.setKeepAliveName([]);
      userStore.setToken("");
      localClear();
      router.replace(LOGIN_URL);
    }
  });
};

// 打开修改密码和个人信息弹窗
const infoRef = ref<InstanceType<typeof InfoDialog> | null>(null);
const passwordRef = ref<InstanceType<typeof PasswordDialog> | null>(null);
const blackListRef = ref<InstanceType<typeof BlackListDialog> | null>(null);
const openDialog = (ref: string) => {
  if (ref == "infoRef") infoRef.value?.openDialog();
  if (ref == "passwordRef") passwordRef.value?.openDialog();
  if (ref == "blackListRef") blackListRef.value?.openDialog();
};
</script>

<style scoped lang="scss">
.avatar {
  width: 40px;
  height: 40px;
  overflow: hidden;
  cursor: pointer;
  border-radius: 50%;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
