Sidebar.vue 35.7 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370
<template>
  <nav class="nav-rail" :class="{ expanded: isExpanded }">
    <div class="nav-header">
      <!-- 左上角应用Logo -->
      <div
        id="tour-logo"
        class="app-logo"
        @click="go('/app/welcome')"
        :title="isExpanded ? '' : $t('sidebar.backToHome')"
      >
        <img src="/logo.svg" :alt="$t('auth.title')" class="logo-icon" />
        <span v-if="isExpanded" class="app-name">{{ $t('auth.title') }}</span>
      </div>

      <!-- 展开/折叠按钮 -->
      <div class="expand-toggle" @click="toggleSidebar" :title="isExpanded ? $t('welcomeSidebar.collapsePanel') : $t('welcomeSidebar.expandPanel')">
        <svg class="toggle-icon-svg" viewBox="0 0 1024 1024" fill="none" xmlns="http://www.w3.org/2000/svg">
          <rect x="140" y="140" width="744" height="744" rx="80" stroke="currentColor" stroke-width="40" />
          <line x1="380" y1="140" x2="380" y2="884" stroke="currentColor" stroke-width="40" />
        </svg>
      </div>
    </div>
    <div class="logo-divider"></div>
    <div class="nav-group-top">
      <!-- 主页 -->
      <div
        class="nav-item"
        :class="{ active: isActive('/app/welcome'), 'is-expanded': isExpanded }"
        :title="isExpanded ? '' : $t('sidebar.home')"
        @click="go('/app/welcome')"
      >
        <img
          v-if="isActive('/app/welcome')"
          src="/homelight.svg"
          :alt="$t('sidebar.home')"
          class="icon-svg"
        />
        <img v-else src="/homedark.svg" :alt="$t('sidebar.home')" class="icon-svg" />
        <span v-if="isExpanded" class="nav-label">{{ $t('sidebar.home') }}</span>
      </div>
      <!-- 工作台 -->
      <div
        id="tour-workspace"
        class="nav-item"
        :class="{ active: isActive('/app/workspace'), 'is-expanded': isExpanded }"
        :title="isExpanded ? '' : $t('sidebar.workspace')"
        @click="go('/app/workspace')"
      >
        <img
          v-if="isActive('/app/workspace')"
          src="/businesslight.svg"
          :alt="$t('sidebar.workspace')"
          class="icon-svg"
        />
        <img v-else src="/business.svg" :alt="$t('sidebar.workspace')" class="icon-svg" />
        <span v-if="isExpanded" class="nav-label">{{ $t('sidebar.workspace') }}</span>
      </div>
      <!-- 知识库 -->
      <div
        id="tour-knowledge"
        class="nav-item"
        :class="{ active: isActive('/app/knowledge'), 'is-expanded': isExpanded }"
        :title="isExpanded ? '' : $t('sidebar.knowledge')"
        @click="go('/app/knowledge')"
      >
        <img
          v-if="isActive('/app/knowledge')"
          src="/zhishikulight.svg"
          :alt="$t('sidebar.knowledge')"
          class="icon-svg"
        />
        <img v-else src="/zhishiku.svg" :alt="$t('sidebar.knowledge')" class="icon-svg" />
        <span v-if="isExpanded" class="nav-label">{{ $t('sidebar.knowledge') }}</span>
      </div>
      <!-- 嘉宝仁和样本流转系统 -->
      <div
        class="nav-item pgx-entry"
        :class="{ active: isActive('/app/pgx'), 'is-expanded': isExpanded }"
        title="嘉宝仁和 · 样本流转系统"
        @click="go('/app/pgx')"
        style="margin-top: 4px;"
      >
        <span class="pgx-icon" style="font-size:18px; width:20px; text-align:center;">🧬</span>
        <span v-if="isExpanded" class="nav-label" style="font-size:13px;">样本流转系统</span>
      </div>
    </div>

    <div class="nav-group-bottom">
      <!-- 消息中心入口 -->
      <div
        class="nav-item message-center-entry"
        :class="{ 'is-expanded': isExpanded }"
        :title="isExpanded ? '' : $t('sidebar.notifications')"
        @click="toggleNotificationCenter"
      >
        <div class="icon-wrapper">
          <el-badge :value="unreadCount" :max="99" :hidden="unreadCount <= 0" class="badge-item">
            <img src="/xiaoxizhongxin.svg" :alt="$t('sidebar.notifications')" class="icon-svg" />
          </el-badge>
        </div>
        <span v-if="isExpanded" class="nav-label">{{ $t('sidebar.notifications') }}</span>
      </div>
      <!-- 任务 -->
      <div
        v-if="showNewbieTaskEntry"
        class="nav-item"
        :class="{ 'is-expanded': isExpanded }"
        :title="isExpanded ? '' : $t('sidebar.task')"
        @click="toggleNewbieTask"
      >
        <img src="/renwu.svg" :alt="$t('sidebar.task')" class="icon-svg" />
        <span v-if="isExpanded" class="nav-label">{{ $t('sidebar.task') }}</span>
      </div>
      <!-- 用户设置 -->
      <el-dropdown
        trigger="click"
        :placement="isExpanded ? 'top-start' : 'right-start'"
        class="user-dropdown"
        @visible-change="handleUserDropdownVisibleChange"
      >
        <div
          class="nav-item user-avatar"
          :class="{ 'gold-member': isGoldMember, 'is-expanded': isExpanded }"
        >
          <div class="avatar-wrapper">
            <img
              :src="displayAvatarUrl"
              :alt="$t('settingsSidebar.user')"
              class="icon-svg"
              :class="{ 'is-default': isDefaultAvatar }"
            />
            <div
              v-if="isGoldMember"
              class="gold-badge"
              v-html="goldBadgeSvg"
            ></div>
          </div>
          <span v-if="isExpanded" class="nav-label user-name">{{ authStore.user?.username || $t('settingsSidebar.user') }}</span>
        </div>
        <template #dropdown>
          <el-dropdown-menu class="user-info-dropdown">
            <!-- 用户角色 / User role -->
            <el-dropdown-item class="user-info-item-wrapper">
              <div class="user-info-item user-info-first-item">
                <span class="info-label">
                  {{ $t("settingsSidebar.userRoleLabel") }}:</span
                >
                <span class="info-value">{{ userRoleDisplay }}</span>
              </div>
            </el-dropdown-item>

            <!-- 认证状态 -->
            <el-dropdown-item class="user-info-item-wrapper">
              <div class="user-info-item">
                <span class="info-label"
                  >{{ t("settings.authentication.statusLabel") }}:</span
                >
                <span class="info-value">
                  <template v-if="certificationStatusInfo.isUnverified">
                    <span class="status-uncertified">
                      {{ t("settings.authentication.statusUnverified") }}
                    </span>
                    <span>&nbsp;|</span>
                    <span
                      class="status-go-auth"
                      @click.stop="goToAuthentication"
                    >
                      {{ t("settings.authentication.goToAuth") }}
                    </span>
                  </template>
                  <template v-else>
                    <span :class="certificationStatusInfo.class">
                      {{ certificationStatusInfo.text }}
                    </span>
                  </template>
                </span>
              </div>
            </el-dropdown-item>

            <!-- 领医豆余额 -->
            <el-dropdown-item class="user-info-item-wrapper">
              <div class="user-info-item">
                <span class="info-label">
                  {{ $t("settingsSidebar.beansBalanceLabel") }}:</span
                >
                <span class="info-value">
                  {{ beansBalance !== null ? beansBalance + "豆" : "-" }}
                </span>
              </div>
            </el-dropdown-item>

            <!-- 领医豆有效期 -->
            <el-dropdown-item class="user-info-item-wrapper">
              <div class="user-info-item">
                <span class="info-label"
                  >{{ t("settingsSidebar.expired") }}:</span
                >
                <span class="info-value">
                  {{
                    beansMaxExpireTime
                      ? formatExpireTime(beansMaxExpireTime)
                      : "-"
                  }}
                </span>
              </div>
            </el-dropdown-item>

            <!-- 可用金额 -->
            <el-dropdown-item class="user-info-item-wrapper">
              <div class="user-info-item">
                <span class="info-label"
                  >{{ $t("settingsSidebar.availableBalance") }}:</span
                >
                <span class="info-value">
                  {{ fundsBalance !== null ? "¥" + fundsBalance : "-" }}
                </span>
              </div>
            </el-dropdown-item>
            <div class="divider"></div>
            <!-- 设置 -->
            <el-dropdown-item
              @click="go('/app/settings')"
              class="logout-item"
              :class="{ active: isActive('/app/settings') }"
            >
              <img
                v-if="isActive('/app/settings')"
                src="/shezilight.svg"
                alt="settings"
                class="logout-icon"
              />
              <img v-else src="/shezhi.svg" alt="settings" class="logout-icon" />
              <span>{{ $t("sidebar.settings") }}</span>
            </el-dropdown-item>
            <!-- 帮助中心 -->
            <el-dropdown-item
              @click="go('/app/help-center')"
              class="logout-item"
              :class="{ active: isActive('/app/help-center') }"
            >
              <img
                v-if="isActive('/app/help-center')"
                src="/shezilight.svg"
                alt="help"
                class="logout-icon"
              />
              <img v-else src="/shezhi.svg" alt="help" class="logout-icon" />
              <span>{{ $t("sidebar.helpCenter") }}</span>
            </el-dropdown-item>
            <!-- 退出登录 -->
            <el-dropdown-item @click="handleLogout" class="logout-item">
              <img src="/logout.svg" alt="logout" class="logout-icon" />
              <span>{{ $t("sidebar.logout") }}</span>
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
  </nav>
  <NewbieTaskDialog ref="newbieTaskDialogRef" />
  <NotificationCenter ref="notificationCenterRef" />
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import { storeToRefs } from "pinia";
import { useI18n } from "vue-i18n";
import { useRoute, useRouter } from "vue-router";
import { Close, Check, ArrowDown, Bell } from "@element-plus/icons-vue";
import { useAuthStore } from "@/stores/auth";
import { useAppStore } from "@/stores/app";
import { useNotifyStore } from "@/stores/notify";
import NewbieTaskDialog from "@/components/common/NewbieTaskDialog.vue";
import NotificationCenter from "@/components/common/NotificationCenter.vue";
import {
  apiGetUserAvatar,
  apiGetCertificationStatus,
  type CertificationStatus,
} from "@/api/user";
import {
  getCurrentUserMemberType,
  getBeansBalance,
  getFundsBalance,
  getExpireTime,
  getNewbieTasksConfig,
  getNewbieTasksGrantedList,
} from "@/api/pay";
import type { MemberTypeItem } from "@/api/pay";

const router = useRouter();
const route = useRoute();
const authStore = useAuthStore();
const appStore = useAppStore();
const notifyStore = useNotifyStore();
const { unreadCount } = storeToRefs(notifyStore);
const { t } = useI18n();

const isExpanded = computed(() => !appStore.sidebarCollapsed);
const showNewbieTaskEntry = ref(true); // 默认显示,待加载后决定
const hadUncompletedTasks = ref(false); // 标记是否曾存在未完成任务(用于区分"刚完成"和"初始就全完成")

const displayUnreadCount = computed(() => {
  const count = unreadCount.value;
  return count > 99 ? '99+' : count;
});

const avatarUrl = ref<string>("");
const memberType = ref<MemberTypeItem | null>(null);
const certificationStatus = ref<CertificationStatus | null>(null);
const salesPosition = ref<string>("");
const beansBalance = ref<number | null>(null);
const fundsBalance = ref<number | null>(null);
const beansMaxExpireTime = ref<string | null>(null);

const newbieTaskDialogRef = ref<any>(null);
const notificationCenterRef = ref<any>(null);

// 切换展开/折叠
const toggleSidebar = () => {
  appStore.toggleSidebar();
};

const openNewbieTask = () => {
  notificationCenterRef.value?.close();
  newbieTaskDialogRef.value?.open();
};

// 点击新手任务图标:已显示则关闭,未显示则打开(与消息中心切换逻辑一致)
const toggleNewbieTask = () => {
  if (newbieTaskDialogRef.value?.isOpen?.()) {
    newbieTaskDialogRef.value?.close();
  } else {
    notificationCenterRef.value?.close();
    newbieTaskDialogRef.value?.open();
  }
};

const toggleNotificationCenter = () => {
  newbieTaskDialogRef.value?.close();
  notificationCenterRef.value?.toggle();
};

// 用户信息(部分字段使用模拟数据,后续逐步接入接口)
const userInfo = ref({
  isCertified: false,
});
// 格式化领医豆过期时间(与 MembersRecordsPanel.vue 保持一致)
const formatExpireTime = (timeStr: string | null): string => {
  if (!timeStr) return "";
  try {
    const date = new Date(timeStr);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, "0");
    const day = String(date.getDate()).padStart(2, "0");
    return `${year}-${month}-${day}`;
  } catch (error) {
    return timeStr || "";
  }
};

// 计算属性:确保头像 URL 始终有效
const displayAvatarUrl = computed(() => {
  if (!avatarUrl.value || avatarUrl.value.trim() === "") {
    return "/gerenshezhi.svg";
  }
  return avatarUrl.value;
});

// 计算属性:判断是否为默认头像
const isDefaultAvatar = computed(() => {
  return !avatarUrl.value || avatarUrl.value.trim() === "";
});

// 计算属性:判断是否为 gold 会员
const isGoldMember = computed(() => {
  return memberType.value?.memberCode === "gold";
});

// 计算属性:用户角色显示(优先取 roleName,兜底使用 memberName 和 salesPosition 拼装)
const userRoleDisplay = computed(() => {
  // 1. 优先使用后端未来统一提供的 roleName
  if (authStore.user?.roleName) return authStore.user.roleName;

  const roles: string[] = [];

  // 2. 获取会员等级拼装
  if (memberType.value?.memberName) {
    const name = memberType.value.memberName;
    roles.push(name.includes("会员") ? name : `${name}会员`);
  }

  // 3. 获取销售职务
  if (salesPosition.value) {
    roles.push(salesPosition.value);
  }

  // 4. 用 " | " 分隔展示
  return roles.join(" | ");
});

// 计算属性:认证状态信息(合并文案和样式类)
const certificationStatusInfo = computed(() => {
  if (!certificationStatus.value) {
    return {
      text: "-",
      class: "status-uncertified",
      isUnverified: false,
    };
  }

  switch (certificationStatus.value) {
    case "UNVERIFIED":
      return {
        text: t("settings.authentication.statusUnverified"),
        class: "status-uncertified",
        isUnverified: true,
      };
    case "PENDING":
      return {
        text: t("settings.authentication.statusPending"),
        class: "status-pending",
        isUnverified: false,
      };
    case "APPROVED":
      return {
        text: t("settings.authentication.statusApproved"),
        class: "status-certified",
        isUnverified: false,
      };
    case "REJECTED":
      return {
        text: t("settings.authentication.statusRejected"),
        class: "status-rejected",
        isUnverified: false,
      };
    default:
      return {
        text: certificationStatus.value,
        class: "status-uncertified",
        isUnverified: false,
      };
  }
});

// 跳转到设置页的“信息认证”标签
const goToAuthentication = () => {
  router
    .push({
      name: "Settings",
      query: { tab: "authentication" },
    })
    .catch((err) => {
      if (err.name !== "NavigationDuplicated") {
        console.error("Navigation error:", err);
      }
    });
};

// Gold 徽章 SVG(内联,确保颜色正确显示)
const goldBadgeSvg = `<svg t="1766112243924" class="icon" viewBox="0 0 1177 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" width="20" height="20"><path d="M11.32075689 589.93820321l530.52268198 530.52268197a51.7341 51.7341 0 1 1-72.36702838 72.36702838L-61.04627148 662.30523158a51.7341 51.7341 0 1 1 72.36702837-72.36702837zM306.46968072 125.23333367l-12.5918634-12.5918634A78.957187 78.957187 0 0 1 286.49638054 15.38018551a77.780249 77.780249 0 0 1 92.70216288-28.36787531 80.236467 80.236467 0 0 1 50.80165394 83.94575272 76.756824 76.756824 0 0 1-68.82104414 67.73553765l48.37735815 245.43277566 393.38716429-89.44564694A78.036105 78.036105 0 0 1 824.25576515 194.27147868a79.622412 79.622412 0 0 1 111.11957145 111.11957146 78.036105 78.036105 0 0 1-100.40925131 21.31208878l-89.44564694 393.38716429 244.92620649 47.87078897a76.756824 76.756824 0 0 1 72.47557846-63.1402317 80.338809 80.338809 0 0 1 79.96556532 56.08444659 77.626735 77.626735 0 0 1-33.68685061 90.27786778 79.161871 79.161871 0 0 1-96.28433118-12.26621174l-12.59186269-12.5918627L625.02933747 1058.91272844l-557.2261156-557.2261156z m-3.18414921 3.18414921" fill="#fab80c"></path></svg>`;

const go = (path: string) => {
  // 检查当前路径是否已经是目标路径
  if (route.path === path) {
    return; // 如果已经在目标页面,直接返回,不进行导航
  }

  // 使用 catch 来处理导航错误
  router.push(path).catch((err) => {
    // 忽略重复导航错误
    if (err.name !== "NavigationDuplicated") {
      console.error("Navigation error:", err);
    }
  });
};

const isActive = (path: string): boolean => {
  // 支持子路由高亮
  return route.path.startsWith(path);
};

const handleLogout = () => {
  // 直接清除状态并跳转,避免异步冲突
  authStore.logout();

  // 使用 setTimeout 避免路由守卫冲突
  setTimeout(() => {
    router.replace("/auth");
  }, 50);
};

// 加载用户头像
const loadUserAvatar = async () => {
  try {
    // 优先从 auth store 获取用户信息,避免重复请求
    let userData = authStore.user;

    // 如果 store 中没有用户信息,则调用 fetchProfile
    if (!userData) {
      const result = await authStore.fetchProfile();
      userData = result.data || null;
    }

    // 如果有用户ID,尝试获取头像
    if (userData?.id) {
      try {
        const response = await apiGetUserAvatar(userData.id);
        // 如果返回的是 blob 数据,转换为 URL
        if (response.data instanceof Blob) {
          // 如果之前有 blob URL,先释放
          if (avatarUrl.value && avatarUrl.value.startsWith("blob:")) {
            URL.revokeObjectURL(avatarUrl.value);
          }
          // 检查 Blob 是否有内容
          if (response.data.size > 0) {
            avatarUrl.value = URL.createObjectURL(response.data);
          } else {
            // 空 Blob,使用默认头像
            avatarUrl.value = "";
          }
        } else if (typeof response.data === "string") {
          // 检查字符串是否为空
          const dataStr = String(response.data);
          avatarUrl.value = dataStr.trim() || "";
        } else {
          // 其他情况,使用默认头像
          avatarUrl.value = "";
        }
      } catch (error: any) {
        // 如果是 404 错误,静默处理,使用默认头像
        if (error?.response?.status === 404) {
          avatarUrl.value = "";
        } else {
          console.warn("获取用户头像失败:", error);
          avatarUrl.value = "";
        }
      }
    } else {
      avatarUrl.value = "";
    }
  } catch (error) {
    console.warn("获取用户信息失败:", error);
    avatarUrl.value = "";
  }
};

// 监听头像更新事件
const handleAvatarUpdated = () => {
  // 重新加载头像
  loadUserAvatar();
};

// 加载会员类型
const loadMemberType = async () => {
  try {
    const response = await getCurrentUserMemberType();
    if (response.data) {
      memberType.value = response.data;
    }
  } catch (error) {
    console.warn("获取会员类型失败:", error);
    memberType.value = null;
  }
};

// 加载领医豆余额
const loadBeansBalance = async () => {
  try {
    const { data } = await getBeansBalance();
    if (data && typeof data.balance === "number") {
      beansBalance.value = data.balance;
    } else {
      beansBalance.value = null;
    }
  } catch (error) {
    console.warn("获取领医豆余额失败:", error);
    beansBalance.value = null;
  }
};

// 加载资金可用余额
const loadFundsBalance = async () => {
  try {
    const { data } = await getFundsBalance();
    if (data && typeof data.balance === "number") {
      fundsBalance.value = data.balance;
    } else {
      fundsBalance.value = null;
    }
  } catch (error) {
    console.warn("获取资金余额失败:", error);
    fundsBalance.value = null;
  }
};

// 加载领医豆最大有效期(与 MembersRecordsPanel.vue 逻辑一致)
const loadBeansExpireTime = async () => {
  try {
    const { data } = await getExpireTime();
    const expireTimes: string[] = [];

    if (data?.memberExpireTime) {
      expireTimes.push(data.memberExpireTime);
    }

    if (data?.items && Array.isArray(data.items)) {
      data.items.forEach((item: any) => {
        if (item.expireTime) {
          expireTimes.push(item.expireTime);
        }
      });
    }

    if (expireTimes.length > 0) {
      const sortedTimes = expireTimes
        .map((time) => new Date(time).getTime())
        .filter((time) => !isNaN(time))
        .sort((a, b) => b - a);

      const maxTime = sortedTimes[0];
      if (maxTime !== undefined) {
        beansMaxExpireTime.value = new Date(maxTime).toISOString();
      } else {
        beansMaxExpireTime.value = null;
      }
    } else {
      beansMaxExpireTime.value = null;
    }
  } catch (error) {
    console.warn("获取领医豆有效期失败:", error);
    beansMaxExpireTime.value = null;
  }
};

// 加载用户认证状态与销售职务
const loadCertificationAndSalesInfo = async () => {
  try {
    const { data } = await apiGetCertificationStatus();
    certificationStatus.value = data.status as CertificationStatus;
    const salesPos = (data as any).salesPosition;
    salesPosition.value = salesPos ? String(salesPos) : "";
    // 同步是否已认证标记(供其他逻辑可能使用)
    userInfo.value.isCertified = certificationStatus.value === "APPROVED";
  } catch (error) {
    console.warn("获取认证状态失败:", error);
    certificationStatus.value = null;
    salesPosition.value = "";
  }
};

// 用户信息下拉显示状态变化时,展开时刷新关键信息
const handleUserDropdownVisibleChange = (visible: boolean) => {
  if (!visible) return;

  // 打开用户设置下拉前,先关闭消息中心/新手任务卡片,避免遮挡与同时显示
  try {
    newbieTaskDialogRef.value?.close?.();
    notificationCenterRef.value?.close?.();
  } catch (e) {
    // ignore
  }

  // 打开下拉时先清空旧数据,避免展示过期信息
  certificationStatus.value = null;
  userInfo.value.isCertified = false;
  beansBalance.value = null;
  fundsBalance.value = null;
  beansMaxExpireTime.value = null;

  // 重新获取最新数据
  loadBeansBalance();
  loadFundsBalance();
  loadBeansExpireTime();
  loadCertificationAndSalesInfo();
};

// 组件挂载时加载头像、会员信息、资产信息与认证信息,并监听事件
onMounted(() => {
  loadUserAvatar();
  loadMemberType();
  loadBeansBalance();
  loadFundsBalance();
  loadBeansExpireTime();
  loadCertificationAndSalesInfo();
  loadNewbieTaskStatus();
  // 开启消息通知监听
  notifyStore.fetchUnread();
  notifyStore.startListening();
  // 监听头像更新事件
  window.addEventListener("avatar-updated", handleAvatarUpdated);
  // 监听新手任务完成事件,刷新领医豆余额
  window.addEventListener("newbie-task-completed", handleBeansBalanceUpdate);
  // 监听打开新手任务事件(来自消息中心)
  window.addEventListener("open-newbie-task", handleOpenNewbieTask);
});

// 领医豆余额更新处理逻辑
const handleBeansBalanceUpdate = () => {
  loadBeansBalance();
  loadNewbieTaskStatus();
};

// 处理由消息中心触发的打开新手任务事件
const handleOpenNewbieTask = () => {
  openNewbieTask();
};

// 加载新手任务完成状态,决定是否显示侧边栏入口
const loadNewbieTaskStatus = async () => {
  try {
    const [configRes, grantedRes] = await Promise.all([
      getNewbieTasksConfig().catch(() => ({ data: { tasks: [] as any[] } })),
      getNewbieTasksGrantedList().catch(() => ({ data: [] as string[] })),
    ]);

    const tasks = (configRes.data as any)?.tasks || [];
    const grantedKeys = (grantedRes.data as string[]) || [];

    if (tasks.length === 0) {
      showNewbieTaskEntry.value = false;
      return;
    }

    const hasUncompleted = tasks.some((task: any) => !grantedKeys.includes(task.key));

    if (hasUncompleted) {
      // 还有未完成的任务,记录状态并显示入口
      hadUncompletedTasks.value = true;
      showNewbieTaskEntry.value = true;
    } else if (hadUncompletedTasks.value) {
      // 之前有未完成任务,现在全部完成了 → 弹出祝贺提示并关闭新手任务卡片
      ElMessage.success(t('newbieTask.allCompleted'));
      // 关闭新手任务弹窗
      newbieTaskDialogRef.value?.close();
      // 隐藏侧边栏入口
      showNewbieTaskEntry.value = false;
    } else {
      // 初始加载时就全部完成,直接隐藏
      showNewbieTaskEntry.value = false;
    }
  } catch (error) {
    console.warn("加载新手任务状态失败:", error);
    showNewbieTaskEntry.value = true; // 报错时默认显示
  }
};

// 组件卸载时清理 blob URL 和事件监听
onUnmounted(() => {
  notifyStore.stopListening();
  if (avatarUrl.value && avatarUrl.value.startsWith("blob:")) {
    URL.revokeObjectURL(avatarUrl.value);
  }
  // 移除事件监听
  window.removeEventListener("avatar-updated", handleAvatarUpdated);
  window.removeEventListener("newbie-task-completed", handleBeansBalanceUpdate);
  window.removeEventListener("open-newbie-task", handleOpenNewbieTask);
});
</script>

<style scoped>
.nav-rail {
  width: 54px;
  background: #FCFCFD;
  border-right: 1px solid var(--color-border, #333);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  flex-shrink: 0;
  backdrop-filter: blur(10px);
  position: relative;
  z-index: 100;
}

.nav-rail.expanded {
  width: 200px;
  align-items: flex-start;
  padding: 16px 12px;
}

.nav-header {
  width: 100%;
  display: flex;
  flex-direction: column-reverse;
  align-items: center;
  gap: 12px;
}

.nav-rail.expanded .nav-header {
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
  padding: 0 4px;
  margin-bottom: 0;
  gap: 8px;
}

.expand-toggle {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 6px;
  transition: all 0.2s ease;
  margin-bottom: 0;
  align-self: center;
  flex-shrink: 0;
}

.nav-rail.expanded .expand-toggle {
  align-self: center;
}

.expand-toggle:hover {
  background: var(--color-hover, #37373d);
}

.toggle-icon-svg {
  width: 20px;
  height: 20px;
  color: #464d5a;
}

/* 深色主题下图标为白色 */
.theme-dark .toggle-icon-svg {
  color: #ffffff;
}

.expand-toggle:hover .toggle-icon-svg {
  opacity: 0.8;
}

.nav-rail.expanded .toggle-icon-svg {
  transform: rotate(180deg);
}

.app-logo {
  margin-bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  padding: 8px;
  border-radius: 8px;
  width: auto;
}

.app-logo:hover {
  background: var(--color-hover, #37373d);
}

.nav-rail.expanded .app-logo {
  justify-content: flex-start;
  gap: 12px;
  padding: 8px 4px;
}

.app-name {
  font-size: 18px;
  font-weight: 600;
  color: var(--color-text, #eee);
  white-space: nowrap;
  overflow: hidden;
  animation: fadeIn 0.3s ease forwards;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateX(-10px); }
  to { opacity: 1; transform: translateX(0); }
}

.logo-icon {
  width: auto;
  height: 24px;
  object-fit: contain;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.3));
  flex-shrink: 0;
}

.logo-icon:hover {
  transform: scale(1.05);
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.5));
}

.logo-divider {
  width: 100%;
  height: 1px;
  background-color: var(--color-border, #333);
  margin: 16px 0;
}

.nav-group-top {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  flex: 1;
  width: 100%;
}

.nav-rail.expanded .nav-group-top {
  align-items: flex-start;
}

.nav-group-bottom {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  width: 100%;
}

.nav-rail.expanded .nav-group-bottom {
  align-items: flex-start;
}

.nav-item {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
  color: var(--color-text-secondary, #999);
  background: transparent;
}

.nav-item.is-expanded {
  width: 100%;
  height: 40px;
  justify-content: flex-start;
  padding: 0 12px;
  gap: 12px;
}

.nav-item.is-expanded:hover {
  transform: none;
  background: var(--color-hover);
}

.nav-label {
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  animation: fadeIn 0.3s ease forwards;
  flex: 1;
}

.user-name {
  font-weight: 500;
  color: var(--color-text);
}

.nav-item:hover {
  background: var(--color-hover);
  color: var(--color-text);
  transform: none;
}

.nav-item:hover i {
  color: var(--color-text);
}

.nav-item.active {
  background: var(--tab-selected);
  color: var(--color-text);
}

.nav-item.active i {
  color: var(--color-text);
}

.nav-item.active::after {
  display: none;
}

.message-center-entry {
  position: relative;
}

.icon-wrapper {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.badge-item {
  display: flex;
  align-items: center;
  justify-content: center;
}

:deep(.badge-item .el-badge__content) {
  top: 0;
  right: 10px;
}

.nav-item i {
  font-size: 18px;
  font-weight: 300;
  color: var(--color-text-secondary);
  transition:
    color 0.2s ease,
    filter 0.2s ease;
}

.nav-item .nav-icon {
  width: 18px;
  height: 18px;
}

.nav-item .icon-svg {
  width: 20px;
  height: 20px;
  transition: all 0.2s ease;
  filter: var(--icon-filter);
}

.sharp-icon {
  image-rendering: -webkit-optimize-contrast;
  stroke: #464D5A;
}

.theme-dark .sharp-icon {
  stroke: #ffffff;
}

.nav-item.active .sharp-icon {
  stroke: currentColor;
  filter: none !important;
}

.message-center-entry .icon-svg {
  font-size: 20px;
}

.nav-item.active .icon-svg {
  filter: none;
}

/* 激活状态下图标颜色(深色主题) */
.theme-dark .nav-item.active .icon-svg {
  filter: brightness(0) saturate(100%) invert(1);
}

/* 激活状态下图标颜色(浅色主题) */
.theme-light .nav-item.active .icon-svg {
  filter: brightness(0) saturate(100%) invert(35%) sepia(94%) saturate(4612%) hue-rotate(215deg) brightness(101%) contrast(101%);
}

/* hover状态下根据主题调整 */
.theme-dark .nav-item:hover .icon-svg {
  filter: brightness(0) saturate(100%) invert(1);
}

.theme-light .nav-item:hover .icon-svg {
  filter: var(--icon-filter);
  opacity: 0.8;
}

.user-avatar {
  color: var(--color-text);
  position: relative;
}

.user-dropdown {
  width: 100%;
  display: flex;
  justify-content: center;
}

.nav-rail.expanded .user-dropdown {
  justify-content: flex-start;
}

.avatar-wrapper {
  position: relative;
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.is-expanded .avatar-wrapper {
  width: 32px;
  height: 32px;
}

.user-avatar .icon-svg {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 8px;
  /* 头像图片不应该应用 filter,保持原始颜色 */
  filter: none !important;
}

.user-avatar .icon-svg.is-default {
  width: 24px !important;
  height: 24px !important;
}

.user-avatar:hover {
  background: var(--color-hover, #37373d);
}

.user-avatar.gold-member .avatar-wrapper {
  border: 3px solid #fab80c;
  border-radius: 10px;
  box-shadow: 0 0 8px rgba(250, 184, 12, 0.4);
}

.user-avatar.gold-member .gold-badge {
  position: absolute;
  top: -10px;
  right: -8px;
  width: 18px;
  height: 18px;
  z-index: 10;
  pointer-events: none;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-avatar.gold-member .gold-badge svg {
  width: 100%;
  height: 100%;
  filter: none !important;
  -webkit-filter: none !important;
}

.user-avatar.gold-member .gold-badge path {
  fill: #fab80c !important;
}

/* 响应式设计 */
/* 平板端适配 (768px - 1024px) */
@media (min-width: 768px) and (max-width: 1024px) {
  .nav-rail {
    width: 54px;
    padding: 16px 0;
  }

  .logo-icon {
    width: 24px;
    height: 24px;
  }

  .nav-item {
    width: 38px;
    height: 38px;
  }

  .nav-item i {
    font-size: 16px;
  }
}

/* 小屏平板端适配 (600px - 768px) */
@media (min-width: 600px) and (max-width: 767px) {
  .nav-rail {
    width: 50px;
    padding: 12px 0;
  }

  .logo-icon {
    width: 22px;
    height: 22px;
  }

  .nav-item {
    width: 36px;
    height: 36px;
  }

  .nav-item i {
    font-size: 14px;
  }
}

/* 手机端适配 (小于600px) */
@media (max-width: 599px) {
  .nav-rail {
    width: 56px;
    padding: 12px 0;
  }

  .app-logo {
    margin-bottom: 16px;
  }

  .logo-icon {
    width: 28px;
    height: 24px;
  }

  .nav-group-top,
  .nav-group-bottom {
    gap: 8px;
  }

  .nav-item {
    width: 40px;
    height: 40px;
  }

  .nav-item i {
    font-size: 16px;
  }
}

/* 用户信息下拉菜单样式 */
:deep(.user-info-dropdown) {
  min-width: 280px;
  padding: 16px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-top: 2px solid #f56c6c;
  border-left: 2px solid #f56c6c;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.user-info-dropdown .el-dropdown-menu__item) {
  padding: 0;
  height: auto;
  line-height: normal;
}

:deep(.user-info-dropdown .el-dropdown-menu__item.user-info-item-wrapper) {
  padding: 8px 10px;
  cursor: default;
}

:deep(
  .user-info-dropdown .el-dropdown-menu__item.user-info-item-wrapper:hover
) {
  background-color: transparent;
}

:deep(.user-info-dropdown .el-dropdown-menu__item.is-divided) {
  border-top: 1px solid #e4e7ed;
  height: 1px;
  padding: 0;
}

.user-info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  font-size: 14px;
  column-gap: 22px;
}
.user-info-first-item {
  margin-top: 8px;
}

.info-label {
  color: #606266;
  font-weight: 500;
}

.info-value {
  color: #303133;
  font-weight: 400;
}

.status-uncertified,
.status-rejected {
  color: #f56c6c;
}

.status-certified {
  color: #67c23a;
}

.status-pending {
  color: #ff9800;
}

.status-go-auth {
  color: #409eff;
  margin-left: 4px;
}

.divider {
  height: 1px;
  background-color: #e4e7ed;
  margin: 8px 0;
  border: none;
  padding: 0;
}

/* 深色主题适配 */
.theme-dark :deep(.user-info-dropdown) {
  background: #2d2d2d;
  border-color: #4a4a4a;
  border-top-color: #f56c6c;
  border-left-color: #f56c6c;
}

.theme-dark .info-label {
  color: #b3b3b3;
}

.theme-dark .info-value {
  color: #e4e7ed;
}

.theme-dark :deep(.user-info-dropdown .el-dropdown-menu__item.is-divided) {
  border-top-color: #4a4a4a;
}

.theme-dark .divider {
  background-color: #4a4a4a;
}

.theme-dark
  :deep(
    .user-info-dropdown .el-dropdown-menu__item.user-info-item-wrapper:hover
  ) {
  background-color: transparent;
}

.theme-dark :deep(.user-info-dropdown .el-dropdown-menu__item:hover) {
  background-color: #37373d;
  color: #e4e7ed;
}

.logout-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 10px;
  cursor: pointer;
}

.logout-icon {
  width: 16px;
  height: 16px;
  flex-shrink: 0;
  margin-right: 4px;
}

:deep(.logout-item) {
  padding: 8px 10px;
}

:deep(.logout-item.active) {
  background-color: var(--tab-selected);
  color: var(--color-text);
}
</style>