ProfilePanel.vue 35.8 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 1371 1372 1373 1374 1375
<template>
  <div class="profile-panel">
    <div
      class="settings-content-header"
      :class="{
        'member-gold': memberCode === 'gold',
        'member-platinum': memberCode === 'platinum',
      }"
    >
      <div class="header-left">
        <h1>{{ $t("settings.profile.title") }}</h1>
        <p>{{ $t("settings.profile.desc") }}</p>
      </div>
      <div class="header-right" v-if="memberCode">
        <div class="member-type-wrapper">
          <img
            :src="memberTypeIcon"
            :alt="memberTypeDisplay"
            class="member-type-icon"
          />
          <div class="member-type-name" v-if="memberName">
            {{ memberTypeNameDisplay }}
          </div>
          <div class="member-expire-time" v-if="memberExpireTimeDisplay">
            有效期至{{ memberExpireTimeDisplay }}
          </div>
        </div>
      </div>
    </div>
    <div class="profile-list">
      <!-- 用户名 -->
      <div class="profile-item">
        <div class="item-content">
          <div class="item-title">
            {{ $t("settings.profile.username") }}
          </div>
          <div class="item-value">{{ username || "-" }}</div>
        </div>
        <el-button class="edit-btn" @click="editUsername" :disabled="loading">
          {{ $t("settings.profile.editUsername") }}
        </el-button>
      </div>

      <!-- 头像 -->
      <div class="profile-item">
        <div class="item-content">
          <div class="item-title">{{ $t("settings.profile.avatar") }}</div>
          <div class="item-avatar-wrapper">
            <img
              :src="displayAvatarUrl"
              class="item-avatar"
              @click="triggerUpload"
            />
            <div class="item-avatar-tip">
              {{ $t("settings.profile.avatarTip") }}
            </div>
          </div>
          <input
            ref="fileInputRef"
            type="file"
            accept="image/*"
            @change="onAvatarChange"
            style="display: none"
          />
        </div>
        <el-button class="edit-btn" @click="triggerUpload" :disabled="loading">
          {{ $t("settings.profile.editAvatar") }}
        </el-button>
      </div>

      <!-- 手机号 -->
      <div class="profile-item">
        <div class="item-content">
          <div class="item-title">{{ $t("settings.profile.phone") }}</div>
          <div class="item-value">{{ phone || "-" }}</div>
        </div>
        <el-button
          v-if="!phone"
          class="edit-btn"
          @click="editPhone"
          :disabled="loading"
        >
          <!-- {{
            phone
              ? $t("settings.profile.unbindPhone")
              : $t("settings.profile.bindPhone")
          }} -->
          {{ $t("settings.profile.bindPhone") }}
        </el-button>
      </div>

      <!-- 电子邮箱 -->
      <div class="profile-item">
        <div class="item-content">
          <div class="item-title">{{ $t("settings.profile.email") }}</div>
          <div class="item-desc" v-if="!email">
            {{ $t("settings.profile.emailDesc") }}
          </div>
          <div class="item-value">{{ email || "-" }}</div>
        </div>
        <el-button class="edit-btn" @click="editEmail" :disabled="loading">
          {{
            email
              ? $t("settings.profile.unbindEmail")
              : $t("settings.profile.bindEmail")
          }}
        </el-button>
      </div>

      <!-- 密码 -->
      <div class="profile-item">
        <div class="item-content">
          <div class="item-title">
            {{ $t("settings.profile.passwordTitle") }}
          </div>
          <div class="item-desc">
            {{ $t("settings.profile.passwordDesc") }}
          </div>
        </div>
        <el-button class="edit-btn" @click="setPassword" :disabled="loading">
          {{ $t("settings.profile.setPassword") }}
        </el-button>
      </div>

      <!-- 微信 -->
      <div class="profile-item">
        <div class="item-content">
          <div class="item-title">
            {{ $t("settings.profile.wechat") }}
            <img src="/weixin.svg" class="wechat-icon" />
          </div>
          <div class="item-desc">
            <template v-if="wechatBound">
              {{ $t("settings.profile.wechatDesc") }}
              <template v-if="wechatNickname"
                >({{ wechatNickname }})</template
              >
            </template>
            <template v-else>{{
              $t("settings.profile.wechatNotBound")
            }}</template>
          </div>
        </div>
        <el-button class="edit-btn" @click="unbindWechat">
          {{
            wechatBound
              ? $t("settings.profile.unbindWechat")
              : $t("settings.profile.bindWechat")
          }}
        </el-button>
      </div>

      <!-- 注销账号 -->
      <!-- <div class="profile-item">
        <div class="item-content">
          <div class="item-title">
            {{ $t("settings.profile.deactivateAccount") }}
          </div>
          <div class="item-desc">
            {{ $t("settings.profile.deactivateDesc") }}
            <el-link
              type="primary"
              class="deactivate-link"
              @click="viewDeactivateNotice"
            >
              {{ $t("settings.profile.deactivateNotice") }}
            </el-link>
          </div>
        </div>
        <el-button
          class="edit-btn danger-btn"
          @click="deactivateAccount"
          :disabled="loading"
        >
          {{ $t("settings.profile.deactivateAccount") }}
        </el-button>
      </div> -->
    </div>

    <!-- 编辑用户名弹窗 -->
    <el-dialog
      v-model="editUsernameDialogVisible"
      :title="$t('settings.profile.editUsername')"
      width="500px"
    >
      <el-form :model="editUsernameForm" label-width="100px">
        <el-form-item :label="$t('settings.profile.username')">
          <el-input
            v-model="editUsernameForm.name"
            :placeholder="$t('settings.profile.usernamePlaceholder')"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editUsernameDialogVisible = false">
            {{ $t("common.cancel") }}
          </el-button>
          <el-button
            type="primary"
            @click="submitEditUsername"
            :loading="loading"
          >
            {{ $t("common.confirm") }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 修改密码弹窗 -->
    <el-dialog
      v-model="changePasswordDialogVisible"
      :title="$t('settings.profile.setPassword')"
      width="500px"
    >
      <el-form
        :model="changePasswordForm"
        label-width="120px"
        class="change-password-form"
      >
        <el-form-item :label="$t('settings.profile.oldPassword')">
          <el-input
            v-model="changePasswordForm.oldPassword"
            type="password"
            :placeholder="$t('settings.profile.oldPasswordPlaceholder')"
            show-password
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item :label="$t('settings.profile.newPassword')">
          <el-input
            v-model="changePasswordForm.newPassword"
            type="password"
            :placeholder="$t('settings.profile.newPasswordPlaceholder')"
            show-password
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item :label="$t('settings.profile.confirmPassword')">
          <el-input
            v-model="changePasswordForm.confirmPassword"
            type="password"
            :placeholder="$t('settings.profile.confirmPasswordPlaceholder')"
            show-password
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="changePasswordDialogVisible = false">
            {{ $t("common.cancel") }}
          </el-button>
          <el-button
            type="primary"
            @click="submitChangePassword"
            :loading="loading"
          >
            {{ $t("common.confirm") }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 绑定手机号弹窗 -->
    <el-dialog
      v-model="bindPhoneDialogVisible"
      :title="$t('settings.profile.bindPhone')"
      width="500px"
    >
      <el-form :model="bindPhoneForm" label-width="100px">
        <el-form-item :label="$t('settings.profile.phone')">
          <el-input
            v-model="bindPhoneForm.phoneNumber"
            :placeholder="$t('settings.profile.phonePlaceholder')"
            maxlength="11"
            @input="
              bindPhoneForm.phoneNumber = bindPhoneForm.phoneNumber.replace(
                /\D/g,
                '',
              )
            "
          />
        </el-form-item>
        <el-form-item :label="$t('settings.profile.smsCode')">
          <div style="display: flex; gap: 10px">
            <el-input
              v-model="bindPhoneForm.smsCode"
              :placeholder="$t('settings.profile.smsCodePlaceholder')"
              maxlength="6"
              @input="
                bindPhoneForm.smsCode = bindPhoneForm.smsCode.replace(/\D/g, '')
              "
            />
            <el-button
              @click="sendBindSmsCode"
              :disabled="smsCodeCountdown > 0 || loading"
              :loading="loading"
            >
              {{
                smsCodeCountdown > 0
                  ? `${smsCodeCountdown}秒后重试`
                  : $t("settings.profile.sendSmsCode")
              }}
            </el-button>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bindPhoneDialogVisible = false">
            {{ $t("common.cancel") }}
          </el-button>
          <el-button type="primary" @click="submitBindPhone" :loading="loading">
            {{ $t("common.confirm") }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 绑定邮箱弹窗 -->
    <el-dialog
      v-model="bindEmailDialogVisible"
      :title="$t('settings.profile.bindEmail')"
      width="500px"
    >
      <el-form :model="bindEmailForm" label-width="100px">
        <el-form-item :label="$t('settings.profile.email')">
          <el-input
            v-model="bindEmailForm.email"
            type="email"
            :placeholder="$t('settings.profile.emailPlaceholder')"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bindEmailDialogVisible = false">
            {{ $t("common.cancel") }}
          </el-button>
          <el-button type="primary" @click="submitBindEmail" :loading="loading">
            {{ $t("common.confirm") }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 解绑邮箱弹窗 -->
    <el-dialog
      v-model="unbindEmailDialogVisible"
      :title="$t('settings.profile.unbindEmail')"
      width="500px"
    >
      <el-form :model="unbindEmailForm" label-width="100px">
        <el-form-item :label="$t('settings.profile.email')">
          <el-input
            v-model="unbindEmailForm.email"
            type="email"
            :placeholder="$t('settings.profile.emailPlaceholder')"
            disabled
          />
        </el-form-item>
        <el-form-item :label="$t('settings.profile.passwordTitle')">
          <el-input
            v-model="unbindEmailForm.password"
            type="password"
            :placeholder="$t('settings.profile.passwordPlaceholder')"
            show-password
            autocomplete="off"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="unbindEmailDialogVisible = false">
            {{ $t("common.cancel") }}
          </el-button>
          <el-button
            type="primary"
            @click="submitUnbindEmail"
            :loading="loading"
          >
            {{ $t("common.confirm") }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { ElMessage } from "element-plus";
import {
  getUserProfile,
  getMockUserProfile,
  apiGetUserAvatar,
  apiUpdateAvatar,
  apiUpdateProfile,
  apiChangePassword,
  apiBindPhone,
  apiSendBindSms,
  apiSendBindEmail,
  apiUnbindEmail,
} from "@/api/user";
import {
  getWechatBindStatus,
  unbindWechat as apiUnbindWechat,
} from "@/api/wechat";
import { useAuthStore } from "@/stores/auth";
import {
  getCurrentUserMemberType,
  getCurrentUserMemberExpireTime,
} from "@/api/pay";

const router = useRouter();
const { t } = useI18n();
const authStore = useAuthStore();

const avatarUrl = ref("");
const username = ref("");
const email = ref("");
const phone = ref("");
const userId = ref<number | null>(null);
const loading = ref(false);
const fileInputRef = ref<HTMLInputElement>();

// 会员类型
const memberCode = ref<string>("");
const memberName = ref<string>("");
const memberExpireTime = ref<string | null>(null);

// 微信绑定状态
const wechatBound = ref(false);
const wechatNickname = ref("");

// 编辑用户名弹窗相关
const editUsernameDialogVisible = ref(false);
const editUsernameForm = ref({
  name: "",
});

// 修改密码弹窗相关
const changePasswordDialogVisible = ref(false);
const changePasswordForm = ref({
  oldPassword: "",
  newPassword: "",
  confirmPassword: "",
});

// 绑定手机号弹窗相关
const bindPhoneDialogVisible = ref(false);
const bindPhoneForm = ref({
  phoneNumber: "",
  smsCode: "",
});
const smsCodeCountdown = ref(0);
const smsCodeTimer = ref<number | null>(null);

// 绑定邮箱弹窗相关
const bindEmailDialogVisible = ref(false);
const bindEmailForm = ref({
  email: "",
});

// 解绑邮箱弹窗相关
const unbindEmailDialogVisible = ref(false);
const unbindEmailForm = ref({
  email: "",
  password: "",
});

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

// 计算属性:会员类型显示文本
const memberTypeDisplay = computed(() => {
  if (!memberCode.value) return "";
  const code = memberCode.value.toLowerCase();
  if (code === "gold") {
    return t("settingsSidebar.memberTypeGold");
  } else if (code === "platinum") {
    return t("settingsSidebar.memberTypePlatinum");
  }
  return "";
});

// 计算属性:会员类型图标
const memberTypeIcon = computed(() => {
  if (!memberCode.value) return "";
  const code = memberCode.value.toLowerCase();
  if (code === "gold") {
    return "/huiyuan3.png";
  } else if (code === "platinum") {
    return "/baijingkahuiyuan1.svg";
  }
  return "";
});

// 计算属性:会员类型名称(国际化处理)
const memberTypeNameDisplay = computed(() => {
  if (!memberName.value) return "";

  // 将后端返回的中文名称映射到国际化键
  const nameMap: Record<string, string> = {
    金卡: "settingsSidebar.memberTypeGold",
    白金卡: "settingsSidebar.memberTypePlatinum",
  };

  const i18nKey = nameMap[memberName.value];
  if (i18nKey) {
    return t(i18nKey);
  }

  // 如果没有匹配到,直接返回原值
  return memberName.value;
});

// 计算属性:会员有效期展示(格式:YYYY/MM/DD)
const memberExpireTimeDisplay = computed(() => {
  if (!memberExpireTime.value) return "";
  const date = new Date(memberExpireTime.value);
  if (Number.isNaN(date.getTime())) return "";
  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}`;
});

const loadUserProfile = async () => {
  loading.value = true;
  try {
    // 尝试获取真实用户信息,如果失败则使用模拟数据
    let userData;
    try {
      userData = await getUserProfile();
    } catch (error) {
      console.warn("⚠️ 获取真实用户信息失败,使用模拟数据:", error);
      userData = getMockUserProfile();
    }

    username.value = userData.name || "";
    email.value = userData.email || "";
    phone.value = userData.phoneNumber?.toString() || "";
    userId.value = userData.id || null;

    // 获取用户头像
    if (userData.id) {
      try {
        const response = await apiGetUserAvatar(userData.id);
        // 如果返回的是 blob 数据,转换为 URL
        if (response.data instanceof Blob) {
          // 检查 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.error("Failed to load user profile:", error);
    ElMessage.error("Failed to load user profile");
  } finally {
    loading.value = false;
  }
};

const triggerUpload = () => {
  fileInputRef.value?.click();
};

const onAvatarChange = async (e: Event) => {
  const target = e.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) return;

  if (!file.type.startsWith("image/")) {
    ElMessage.error("请选择图片文件");
    return;
  }

  if (file.size > 2 * 1024 * 1024) {
    ElMessage.error("图片大小不能超过2MB");
    return;
  }

  try {
    loading.value = true;

    // 先预览图片
    const reader = new FileReader();
    reader.onload = (e2) => {
      if (e2.target?.result) {
        avatarUrl.value = e2.target.result as string;
      }
    };
    reader.readAsDataURL(file);

    // 上传头像到服务器
    await apiUpdateAvatar(file);

    // 上传成功后,重新获取头像 URL
    if (userId.value) {
      try {
        const response = await apiGetUserAvatar(userId.value);
        // 如果返回的是 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 {
            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) {
          console.warn("获取更新后的头像失败:", error);
        }
        avatarUrl.value = "";
      }
    }

    ElMessage.success("头像更新成功");

    // 触发自定义事件,通知其他组件头像已更新
    window.dispatchEvent(
      new CustomEvent("avatar-updated", {
        detail: { userId: userId.value },
      }),
    );
  } catch (error) {
    console.error("上传头像失败:", error);
    ElMessage.error("上传头像失败,请重试");
    // 上传失败,恢复默认头像
    avatarUrl.value = "";
  } finally {
    loading.value = false;
  }
};

// 编辑用户名
const editUsername = () => {
  editUsernameForm.value.name = username.value;
  editUsernameDialogVisible.value = true;
};

// 提交编辑用户名
const submitEditUsername = async () => {
  if (!editUsernameForm.value.name?.trim()) {
    ElMessage.warning("请输入用户名");
    return;
  }

  try {
    loading.value = true;
    const { data } = await apiUpdateProfile({
      name: editUsernameForm.value.name.trim(),
    });

    // 更新本地显示的用户名
    username.value = data.name || editUsernameForm.value.name.trim();

    ElMessage.success("用户名更新成功");
    editUsernameDialogVisible.value = false;
  } catch (error) {
    console.error("更新用户名失败:", error);
    ElMessage.error("更新用户名失败,请重试");
  } finally {
    loading.value = false;
  }
};

// 编辑手机号
const editPhone = () => {
  if (phone.value) {
    // 已绑定,执行解绑操作
    // handleUnbindPhone();
  } else {
    // 未绑定,打开绑定弹窗
    bindPhoneForm.value = {
      phoneNumber: "",
      smsCode: "",
    };
    bindPhoneDialogVisible.value = true;
  }
};

// 发送绑定验证码
const sendBindSmsCode = async () => {
  if (!bindPhoneForm.value.phoneNumber?.trim()) {
    ElMessage.warning("请输入手机号");
    return;
  }

  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(bindPhoneForm.value.phoneNumber.trim())) {
    ElMessage.warning("请输入正确的手机号");
    return;
  }

  try {
    loading.value = true;
    await apiSendBindSms(bindPhoneForm.value.phoneNumber.trim());
    ElMessage.success("验证码已发送");

    // 开始倒计时
    smsCodeCountdown.value = 60;
    if (smsCodeTimer.value) {
      clearInterval(smsCodeTimer.value);
    }
    smsCodeTimer.value = window.setInterval(() => {
      smsCodeCountdown.value--;
      if (smsCodeCountdown.value <= 0) {
        if (smsCodeTimer.value) {
          clearInterval(smsCodeTimer.value);
          smsCodeTimer.value = null;
        }
      }
    }, 1000);
  } catch (error: any) {
    console.error("发送验证码失败:", error);
    const errorMessage =
      error?.response?.data?.message ||
      error?.message ||
      "发送验证码失败,请重试";
    ElMessage.error(errorMessage);
  } finally {
    loading.value = false;
  }
};

// 提交绑定手机号
const submitBindPhone = async () => {
  if (!bindPhoneForm.value.phoneNumber?.trim()) {
    ElMessage.warning("请输入手机号");
    return;
  }

  // 验证手机号格式
  const phoneRegex = /^1[3-9]\d{9}$/;
  if (!phoneRegex.test(bindPhoneForm.value.phoneNumber.trim())) {
    ElMessage.warning("请输入正确的手机号");
    return;
  }

  if (!bindPhoneForm.value.smsCode?.trim()) {
    ElMessage.warning("请输入验证码");
    return;
  }

  try {
    loading.value = true;
    const { data } = await apiBindPhone({
      phoneNumber: bindPhoneForm.value.phoneNumber.trim(),
      smsCode: bindPhoneForm.value.smsCode.trim(),
      userId: userId.value || undefined,
    });

    // 更新本地显示的手机号
    phone.value = data.phoneNumber?.toString() || "";

    ElMessage.success("手机号绑定成功");
    bindPhoneDialogVisible.value = false;

    // 重置表单
    bindPhoneForm.value = {
      phoneNumber: "",
      smsCode: "",
    };

    // 清除倒计时
    if (smsCodeTimer.value) {
      clearInterval(smsCodeTimer.value);
      smsCodeTimer.value = null;
    }
    smsCodeCountdown.value = 0;
  } catch (error: any) {
    console.error("绑定手机号失败:", error);
  } finally {
    loading.value = false;
  }
};

// 解绑手机号
// const handleUnbindPhone = async () => {
//   if (!phone.value) {
//     ElMessage.warning("当前未绑定手机号");
//     return;
//   }

//   try {
//     // 显示确认提示
//     await ElMessageBox.confirm(
//       t("settings.profile.unbindPhoneConfirmMessage"),
//       t("settings.profile.unbindPhoneConfirm"),
//       {
//         confirmButtonText: t("common.confirm"),
//         cancelButtonText: t("common.cancel"),
//         type: "warning",
//       },
//     );

//     loading.value = true;
//     await apiUnbindPhone({
//       phoneNumber: phone.value,
//       userId: userId.value || undefined,
//     });

//     // 更新本地显示的手机号
//     phone.value = "";

//     ElMessage.success(t("settings.profile.unbindPhoneSuccess"));

//     // 检查是否有邮箱,如果没有则跳转到登录首页
//     if (!email.value || email.value.trim() === "") {
//       ElMessage.warning(t("settings.profile.unbindPhoneNoEmailWarning"));
//       // 跳转到登录首页
//       try {
//         // 先导航到登录页,避免路由守卫冲突
//         await router.replace("/auth");
//         // 然后清除认证状态
//         await authStore.logout();
//       } catch (error) {
//         console.error("登出失败:", error);
//         // 即使出错也要确保跳转到登录页
//         router.replace("/auth");
//       }
//     }
//   } catch (error: any) {
//     // 如果用户取消,不显示错误
//     if (error === "cancel" || error === "close") {
//       return;
//     }
//     console.error("解绑手机号失败:", error);
//     const errorMessage =
//       error?.response?.data?.message ||
//       error?.message ||
//       "解绑手机号失败,请重试";
//     ElMessage.error(errorMessage);
//   } finally {
//     loading.value = false;
//   }
// };

// 编辑邮箱
const editEmail = () => {
  if (email.value) {
    // 已绑定邮箱,打开解绑弹窗
    unbindEmailForm.value = {
      email: email.value,
      password: "",
    };
    unbindEmailDialogVisible.value = true;
  } else {
    // 未绑定邮箱,打开绑定弹窗
    bindEmailForm.value = {
      email: "",
    };
    bindEmailDialogVisible.value = true;
  }
};

// 提交绑定邮箱
const submitBindEmail = async () => {
  if (!bindEmailForm.value.email?.trim()) {
    ElMessage.warning("请输入邮箱地址");
    return;
  }

  // 验证邮箱格式
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(bindEmailForm.value.email.trim())) {
    ElMessage.warning("请输入正确的邮箱地址");
    return;
  }

  try {
    loading.value = true;
    await apiSendBindEmail(bindEmailForm.value.email.trim());
    ElMessage.success("绑定邮件已发送,请查收邮箱并完成绑定");
    bindEmailDialogVisible.value = false;
    // 重置表单
    bindEmailForm.value = {
      email: "",
    };
  } catch (error: any) {
    console.error("发送绑定邮件失败:", error);
    const errorMessage =
      error?.response?.data?.message ||
      error?.message ||
      "发送绑定邮件失败,请重试";
    ElMessage.error(errorMessage);
  } finally {
    loading.value = false;
  }
};

// 提交解绑邮箱
const submitUnbindEmail = async () => {
  if (!unbindEmailForm.value.email?.trim()) {
    ElMessage.warning("邮箱地址不能为空");
    return;
  }

  if (!unbindEmailForm.value.password?.trim()) {
    ElMessage.warning("请输入密码");
    return;
  }

  try {
    loading.value = true;
    await apiUnbindEmail({
      email: unbindEmailForm.value.email.trim(),
      password: unbindEmailForm.value.password.trim(),
    });

    // 更新本地显示的邮箱
    email.value = "";

    ElMessage.success("邮箱解绑成功");
    unbindEmailDialogVisible.value = false;

    // 重置表单
    unbindEmailForm.value = {
      email: "",
      password: "",
    };

    // 检查是否有手机号,如果没有则跳转到登录页
    if (!phone.value || phone.value.trim() === "") {
      ElMessage.warning("您已解绑邮箱,且未绑定手机号,请重新登录");
      try {
        // 先导航到登录页,避免路由守卫冲突
        await router.replace("/auth");
        // 然后清除认证状态
        await authStore.logout();
      } catch (error) {
        console.error("登出失败:", error);
        // 即使出错也要确保跳转到登录页
        router.replace("/auth");
      }
    }
  } catch (error: any) {
    console.error("解绑邮箱失败:", error);
    const errorMessage =
      error?.response?.data?.message ||
      error?.message ||
      "解绑邮箱失败,请重试";
    ElMessage.error(errorMessage);
  } finally {
    loading.value = false;
  }
};

// 设置密码
const setPassword = () => {
  // 重置表单
  changePasswordForm.value = {
    oldPassword: "",
    newPassword: "",
    confirmPassword: "",
  };
  changePasswordDialogVisible.value = true;
};

// 提交修改密码
const submitChangePassword = async () => {
  // 验证输入
  if (!changePasswordForm.value.oldPassword?.trim()) {
    ElMessage.warning("请输入旧密码");
    return;
  }

  if (!changePasswordForm.value.newPassword?.trim()) {
    ElMessage.warning("请输入新密码");
    return;
  }

  if (changePasswordForm.value.newPassword.length < 6) {
    ElMessage.warning("新密码长度不能少于6位");
    return;
  }

  if (
    changePasswordForm.value.newPassword !==
    changePasswordForm.value.confirmPassword
  ) {
    ElMessage.warning("两次输入的新密码不一致");
    return;
  }

  if (
    changePasswordForm.value.oldPassword ===
    changePasswordForm.value.newPassword
  ) {
    ElMessage.warning("新密码不能与旧密码相同");
    return;
  }

  try {
    loading.value = true;
    await apiChangePassword({
      oldPassword: changePasswordForm.value.oldPassword.trim(),
      newPassword: changePasswordForm.value.newPassword.trim(),
    });

    ElMessage.success("密码修改成功");
    changePasswordDialogVisible.value = false;
    // 重置表单
    changePasswordForm.value = {
      oldPassword: "",
      newPassword: "",
      confirmPassword: "",
    };
  } catch (error: any) {
    console.error("修改密码失败:", error);
    const errorMessage =
      error?.response?.data?.message ||
      error?.message ||
      "修改密码失败,请重试";
    ElMessage.error(errorMessage);
  } finally {
    loading.value = false;
  }
};

// 获取微信绑定状态
const refreshWechatBindStatus = async () => {
  try {
    const { data } = await getWechatBindStatus();
    wechatBound.value = !!data.bound;
    wechatNickname.value = data.wechatNickname || "";
  } catch (error) {
    console.warn("获取微信绑定状态失败:", error);
    // 静默失败,不影响其他功能
  }
};

// 解除/绑定微信
const unbindWechat = async () => {
  if (wechatBound.value) {
    // 已绑定,执行解绑操作
    try {
      loading.value = true;
      await apiUnbindWechat();
      ElMessage.success("微信解绑成功");
      await refreshWechatBindStatus();
    } catch (error: any) {
      console.error("解绑微信失败:", error);
      const errorMessage =
        error?.response?.data?.message ||
        error?.message ||
        "解绑微信失败,请重试";
      ElMessage.error(errorMessage);
    } finally {
      loading.value = false;
    }
  } else {
    // 未绑定,跳转到绑定页面
    router.push({ path: "/wechat-login", query: { mode: "bind" } });
  }
};

onMounted(() => {
  loadUserProfile();
  refreshWechatBindStatus();

  // 获取当前用户会员类型
  getCurrentUserMemberType()
    .then((response) => {
      console.log("当前用户会员类型:", response.data);
      if (response.data?.memberCode) {
        memberCode.value = response.data.memberCode;
      }
      if (response.data?.memberName) {
        memberName.value = response.data.memberName;
      }
    })
    .catch((error) => {
      console.error("获取当前用户会员类型失败:", error);
    });

  // 获取当前用户会员过期时间
  getCurrentUserMemberExpireTime()
    .then((response) => {
      memberExpireTime.value = response.data;
      console.log("当前用户会员过期时间:", memberExpireTime.value);
    })
    .catch((error) => {
      console.error("获取当前用户会员过期时间失败:", error);
    });
});

// 组件卸载时清理 blob URL 和定时器,避免内存泄漏
onUnmounted(() => {
  if (avatarUrl.value && avatarUrl.value.startsWith("blob:")) {
    URL.revokeObjectURL(avatarUrl.value);
  }
  // 清理验证码倒计时定时器
  if (smsCodeTimer.value) {
    clearInterval(smsCodeTimer.value);
    smsCodeTimer.value = null;
  }
});
</script>

<style scoped lang="scss">
.profile-panel {
  color: var(--color-text);
  background: var(--color-bg);
  width: 100%;
  max-width: 800px;
  margin: 0 auto;
}

.settings-content-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 20px;
  padding: 18px;
  border-radius: 12px;
  position: relative;
  overflow: hidden;

  // 默认背景(无会员)
  background: var(--color-bg);

  // 金卡会员渐变背景
  &.member-gold {
    background: linear-gradient(135deg, #fff8e8 0%, #ffe8b8 50%, #ffd89c 100%);
  }

  // 白金卡会员渐变背景
  &.member-platinum {
    background: linear-gradient(135deg, #f0f3ec 0%, #e0e6d8 50%, #d0d9c4 100%);
  }

  .header-left {
    flex: 1;
    text-align: left;
    position: relative;
    z-index: 1;
  }

  .header-right {
    flex-shrink: 0;
    display: flex;
    align-items: center;
    position: relative;
    z-index: 1;
  }

  h1 {
    font-size: 28px;
    font-weight: 800;
    color: var(--color-text);
    margin-bottom: 10px;
  }

  p {
    font-size: 16px;
    color: var(--color-secondary);
    font-weight: 400;
  }
}

.member-type-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.member-type-icon {
  width: 70px;
  height: auto;
  object-fit: contain;
  filter: drop-shadow(0 2px 8px rgba(0, 0, 0, 0.1));
}

.member-type-name {
  font-size: 14px;
  font-weight: 600;
  color: #ffffff;
  text-align: center;
}
.member-expire-time {
  font-size: 14px;
  font-weight: 400;
  color: var(--color-secondary);
  text-align: center;
}

.profile-list {
  display: flex;
  flex-direction: column;
  gap: 0;
  background: var(--color-bg);
  border-radius: 8px;
  overflow: hidden;
}

.profile-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px 24px;
  border-bottom: 1px solid var(--color-border);
  transition: background-color 0.2s;

  &:last-child {
    border-bottom: none;
  }

  &:hover {
    background-color: var(--color-card);
  }
}

.item-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.item-title {
  font-size: 15px;
  font-weight: 600;
  color: var(--color-text);
  display: flex;
  align-items: center;
  gap: 8px;
}

.item-value {
  font-size: 14px;
  color: var(--color-text);
  margin-top: 4px;
}

.item-desc {
  font-size: 13px;
  color: var(--color-secondary);
  line-height: 1.5;
}

.item-avatar-wrapper {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-top: 8px;
}

.item-avatar {
  width: 48px;
  height: 48px;
  border-radius: 8px;
  object-fit: cover;
  background: var(--color-card);
  border: 1px solid var(--color-border);
  cursor: pointer;
  transition: transform 0.2s;

  &:hover {
    transform: scale(1.05);
  }
}

.item-avatar-tip {
  font-size: 12px;
  color: var(--color-secondary);
}

.wechat-icon {
  width: 16px;
  height: 16px;
}

.edit-btn {
  background: var(--color-card);
  color: var(--color-text);
  border: 1px solid var(--color-border);
  padding: 8px 16px;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.2s;

  &:hover:not(:disabled) {
    background: var(--color-bag-hover);
    border-color: var(--color-primary);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }
}

.danger-btn {
  color: #f56c6c;
  border-color: #f56c6c;

  &:hover:not(:disabled) {
    background: rgba(245, 108, 108, 0.1);
  }
}

.deactivate-link {
  font-size: 13px;
  margin-left: 4px;
}

// 修改密码表单样式
:deep(.change-password-form) {
  .el-form-item__label {
    line-height: 32px;
  }
}

@media (max-width: 1024px) {
  .profile-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
    padding: 16px;
  }

  .edit-btn {
    width: 100%;
    justify-content: center;
  }
}
</style>