wode-geren-ziliao.vue 16.6 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
<template>
  <view class="profile-page">
    <view class="avatar-section">
      <button class="avatar-edit-btn" open-type="chooseAvatar" @chooseavatar="handleChooseAvatar">
        <image
          :src="formData.avatar || 'https://fitness-hcxtec-bucket.oss-cn-shenzhen.aliyuncs.com/20260526/默认头像_1779779926983.png'"
          mode="aspectFill"
          class="avatar-image"
        ></image>
      </button>
    </view>

    <view class="info-list">
      <view class="list-item" @click="gotoEditNickname">
        <text class="item-title">昵称</text>
        <view class="item-value">{{ formData.nickname || '未设置' }}</view>
        <uni-icons type="right" color="#999" size="20" class="arrow-icon"></uni-icons>
      </view>

      <view class="list-item" @click="gotoSelectGender">
        <text class="item-title">性别</text>
        <view class="item-value">{{ formatGender(formData.sex) }}</view>
        <uni-icons
          v-if="formData.isAllowUpdSex"
          type="right"
          color="#999"
          size="20"
          class="arrow-icon"
        ></uni-icons>
      </view>

      <view class="list-item">
        <text class="item-title">地区</text>
        <picker
          mode="multiSelector"
          :range="multiArray"
          range-key="name"
          :value="multiIndex"
          @change="pickerChange"
          @columnchange="pickerColumnChange"
        >
          <view class="picker" :class="{ 'placeholder-txt': !selectedAddress }">
            {{ selectedAddress || '请选择省市区' }}
          </view>
        </picker>
      </view>

      <view class="list-item signature-item">
        <text class="item-title">个性签名</text>
        <view class="signature-input-wrapper">
          <textarea
            v-model="formData.signature"
            placeholder="请输入个性签名..."
            :maxlength="50"
            class="signature-input"
            auto-height
          />
          <text class="char-count">{{ formData.signature?.length || 0 }}/50</text>
        </view>
      </view>

      <view class="list-item">
        <text class="item-title">注册时间</text>
        <view class="item-value">{{ formatRegisterTime(formData.createTime) }}</view>
      </view>
    </view>

    <view class="button-section">
      <button class="save-btn" :loading="saveLoading" @click="saveProfile">保存修改</button>
    </view>

    <uni-popup ref="nicknamePopupRef" type="bottom" @change="onNicknamePopupChange">
      <view class="popup-container">
        <view class="popup-header">
          <text class="popup-title">编辑昵称</text>
        </view>
        <view class="popup-body">
          <view class="input-wrap">
            <input
              class="nickname-input"
              placeholder="请输入新昵称"
              type="nickname"
              v-model="editCacheData.nickname"
              maxlength="20"
            />
          </view>
        </view>
        <view class="popup-footer">
          <button class="confirm-btn" @click="confirmEditNickname">确认</button>
        </view>
      </view>
    </uni-popup>

    <uni-popup ref="genderPopupRef" type="bottom">
      <view class="popup-container gender-popup">
        <view class="popup-header">
          <view class="header-handle"></view>
          <text class="popup-title">选择性别</text>
          <view class="header-placeholder"></view>
        </view>
        <view class="popup-body">
          <view class="gender-options">
            <view
              class="gender-item"
              :class="{ selected: editCacheData.sex === 1 }"
              @click="selectGender(1)"
            >
              <text class="gender-text">男</text>
            </view>
            <view
              class="gender-item"
              :class="{ selected: editCacheData.sex === 2 }"
              @click="selectGender(2)"
            >
              <text class="gender-text">女</text>
            </view>
          </view>
        </view>
        <view class="popup-safe-area"></view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
  import { ref, reactive } from 'vue';
  import { onShow } from '@dcloudio/uni-app';
  import dayjs from 'dayjs';
  import UserApi from '@/sheep/api/member/user';
  import AreaApi from '@/sheep/api/system/area';
  import FileApi from '@/sheep/api/infra/file';
  import useUserStore from '@/sheep/store/user';

  const userStore = useUserStore();

  // 弹窗 DOM 引用声明
  const nicknamePopupRef = ref(null);
  const genderPopupRef = ref(null);

  // 状态防抖控制
  const saveLoading = ref(false);

  // 【核心改造】:业务独立表单响应式对象(阻断与 Store 的源数据直接浅拷贝)
  const formData = ref({
    avatar: '',
    nickname: '',
    sex: 0,
    province: '',
    city: '',
    region: '',
    signature: '',
    createTime: '',
    isAllowUpdSex: false,
  });

  // 【核心改造】:中间弹窗缓存态,避免点击“取消”或“划走弹窗”时篡改主表单
  const editCacheData = reactive({
    nickname: '',
    sex: 0,
  });

  // 级联选择器(Picker)状态流
  const addressTree = ref([]);
  const multiArray = ref([[], [], []]);
  const multiIndex = ref([0, 0, 0]);
  const selectedAddress = ref('');

  /**
   * 宿主生命周期钩子流
   */
  onShow(async () => {
    try {
      // 采用同步阻塞保证地域级联树先于回显执行
      await fetchAreaTree();

      // 深度解构 Store 核心数据,注入隔离的局部表单状态
      if (userStore.userInfo) {
        formData.value = JSON.parse(JSON.stringify(userStore.userInfo));
        initEchoAddress();
      }
    } catch (error) {
      console.error('[Init Error] 初始化个人信息流失败:', error);
    }
  });

  /**
   * 微信标准化:获取/上传微信特有开放头像能力
   */
  const handleChooseAvatar = async (e) => {
    const { avatarUrl } = e.detail;
    if (!avatarUrl) return;

    uni.showLoading({ title: '上传中...', mask: true });
    try {
      const res = await FileApi.uploadFile(avatarUrl);
      if (res?.data) {
        formData.value.avatar = res.data;
        uni.showToast({ title: '头像上传成功', icon: 'success' });
      }
    } catch (err) {
      console.error('[Upload Error] 头像转存失败:', err);
      uni.showToast({ title: '头像上传失败', icon: 'none' });
    } finally {
      uni.hideLoading();
    }
  };

  /**
   * 唤起并初始化昵称弹窗
   */
  const gotoEditNickname = () => {
    editCacheData.nickname = formData.value.nickname || '';
    nicknamePopupRef.value.open();
  };

  /**
   * 确认昵称逻辑修改
   */
  const confirmEditNickname = () => {
    const targetNickname = editCacheData.nickname.trim();
    if (!targetNickname) {
      uni.showToast({ title: '昵称不能为空', icon: 'none' });
      return;
    }
    formData.value.nickname = targetNickname;
    nicknamePopupRef.value.close();
  };

  /**
   * 唤起并初始化性别弹窗
   */
  const gotoSelectGender = () => {
    if (!formData.value.isAllowUpdSex) {
      uni.showToast({ title: '暂不支持修改性别', icon: 'none' });
      return;
    }
    editCacheData.sex = formData.value.sex || 0;
    genderPopupRef.value.open();
  };

  /**
   * 变更性别(直接变更缓存,延时关闭)
   */
  const selectGender = (sex) => {
    editCacheData.sex = sex;
    formData.value.sex = sex;
    setTimeout(() => {
      genderPopupRef.value.close();
    }, 200); // 200ms 延时留出点击涟漪视觉反馈
  };

  /**
   * 清理弹窗残留状态
   */
  const onNicknamePopupChange = (e) => {
    if (!e.show) editCacheData.nickname = '';
  };

  /**
   * 获取底层标准行政区域三级树
   */
  const fetchAreaTree = async () => {
    if (addressTree.value.length > 0) return;
    const res = await AreaApi.getAreaTree();
    addressTree.value = res?.data || [];
  };

  /**
   * 初始化级联选择器三列静态形态
   */
  const syncPickerColumnData = (pIdx = 0, cIdx = 0) => {
    if (!addressTree.value.length) return;

    const provinces = addressTree.value;
    const cities = provinces[pIdx]?.children || [];
    const regions = cities[cIdx]?.children || [];

    multiArray.value = [provinces, cities, regions];
  };

  /**
   * 【关键优化修复】:滚动 Picker 各列时防高频网络或逻辑同步阻塞引起的真机闪退抖动
   */
  const pickerColumnChange = (e) => {
    const { column, value } = e.detail;
    multiIndex.value[column] = value;

    if (column === 0) {
      // 变动第一列(省):重置城市与区域级联至首项,并刷新后两列数据数组
      multiIndex.value[1] = 0;
      multiIndex.value[2] = 0;
      syncPickerColumnData(value, 0);
    } else if (column === 1) {
      // 变动第二列(市):重置区域级联至首项,并刷新第三列数据数组
      multiIndex.value[2] = 0;
      syncPickerColumnData(multiIndex.value[0], value);
    }
  };

  /**
   * 确认选择省市区
   */
  const pickerChange = (e) => {
    const indices = e.detail.value;
    multiIndex.value = [...indices];

    const pObj = multiArray.value[0][indices[0]];
    const cObj = multiArray.value[1][indices[1]];
    const rObj = multiArray.value[2][indices[2]];

    formData.value.province = pObj?.id || '';
    formData.value.city = cObj?.id || '';
    formData.value.region = rObj?.id || '';

    selectedAddress.value = [pObj?.name, cObj?.name, rObj?.name].filter(Boolean).join(' ');
  };

  /**
   * 纯算法优化:实现省市区ID一键查找映射回显
   */
  const initEchoAddress = () => {
    const { province, city, region } = formData.value;
    if (!province || !addressTree.value.length) {
      // 若无历史资产,纯净初始化首行联动
      syncPickerColumnData(0, 0);
      return;
    }

    const pIdx = addressTree.value.findIndex((p) => p.id === province);
    if (pIdx === -1) return;

    const cities = addressTree.value[pIdx]?.children || [];
    const cIdx = cities.findIndex((c) => c.id === city);

    const regions = cIdx !== -1 ? cities[cIdx]?.children || [] : [];
    const rIdx = regions.findIndex((r) => r.id === region);

    // 安全赋值索引快照
    multiIndex.value = [pIdx, cIdx !== -1 ? cIdx : 0, rIdx !== -1 ? rIdx : 0];

    // 按照变动后的物理索引刷新 Picker 内部映射
    syncPickerColumnData(pIdx, cIdx !== -1 ? cIdx : 0);

    selectedAddress.value = [addressTree.value[pIdx]?.name, cities[cIdx]?.name, regions[rIdx]?.name]
      .filter(Boolean)
      .join(' ');
  };

  /**
   * 发送最终表单变更
   */
  const saveProfile = async () => {
    if (saveLoading.value) return;
    saveLoading.value = true;

    uni.showLoading({ title: '保存中...', mask: true });
    try {
      // 清洗掉无用或者只读的强脏字段
      const { createTime, isAllowUpdSex, ...payload } = formData.value;

      await UserApi.updateUser(payload);

      // 保存成功后同步刷新 Store 内全局状态快照
      if (userStore.getUserInfo) {
        await userStore.getUserInfo();
      }

      uni.showToast({ title: '保存修改成功', icon: 'success' });
      setTimeout(() => uni.navigateBack(), 1200);
    } catch (err) {
      console.error('[API Error] 保存个人资料失败:', err);
      uni.showToast({ title: '保存失败,请稍后重试', icon: 'none' });
    } finally {
      uni.hideLoading();
      saveLoading.value = false;
    }
  };

  // 数据转换原子层清洗工具
  const formatGender = (sex) => {
    if (sex === 1) return '男';
    if (sex === 2) return '女';
    return '保密';
  };

  const formatRegisterTime = (time) => {
    if (!time) return '--';
    return dayjs(time).format('YYYY-MM-DD');
  };
</script>

<style scoped lang="scss">
  $color-bg: #f5f5f5;
  $color-white: #ffffff;
  $color-text-dark: #333;
  $color-text-middle: #666;
  $color-text-light: #999;
  $color-primary: #fdd511;
  $color-border: #eee;
  $radius: 12rpx;
  $radius-lg: 24rpx;
  $shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  $spacing-sm: 20rpx;
  $spacing-md: 24rpx;
  $spacing-lg: 32rpx;
  $spacing-xl: 60rpx;

  .profile-page {
    background-color: $color-bg;
    min-height: 100vh;
    padding-bottom: env(safe-area-inset-bottom);

    .avatar-section {
      display: flex;
      justify-content: center;
      align-items: center;
      padding: $spacing-xl 0 $spacing-lg;

      .avatar-edit-btn {
        background-color: transparent;
        border: none;
        padding: 0;
        line-height: 0;
        border-radius: 50%;
        &::after {
          content: none;
        }
      }

      .avatar-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 50%;
        background-color: #e1e1e1;
      }
    }

    .info-list {
      padding: 0 $spacing-sm;
    }

    .list-item {
      display: flex;
      align-items: center;
      justify-content: space-between;
      background-color: $color-white;
      border-radius: $radius;
      padding: $spacing-md $spacing-sm;
      margin-bottom: $spacing-sm;
      box-shadow: $shadow;

      .item-title {
        font-size: 28rpx;
        color: $color-text-dark;
        flex-shrink: 0;
        width: 140rpx;
      }

      .item-value {
        font-size: 26rpx;
        color: $color-text-middle;
        margin-right: $spacing-sm;
        text-align: right;
        flex: 1;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .picker {
        font-size: 26rpx;
        color: $color-text-middle;
        text-align: right;
        flex: 1;
        padding-right: 10rpx;

        &.placeholder-txt {
          color: $color-text-light;
        }
      }

      .arrow-icon {
        flex-shrink: 0;
      }

      &.signature-item {
        flex-direction: column;
        align-items: flex-start;
        gap: 16rpx;

        .signature-input-wrapper {
          width: 100%;
          position: relative;

          .signature-input {
            width: 100%;
            min-height: 120rpx;
            max-height: 200rpx;
            padding: 16rpx 20rpx 40rpx;
            font-size: 26rpx;
            color: $color-text-dark;
            background-color: #f9f9f9;
            border-radius: $radius;
            border: 1rpx solid $color-border;
            box-sizing: border-box;
            line-height: 1.5;
          }

          .char-count {
            position: absolute;
            right: 20rpx;
            bottom: 12rpx;
            font-size: 22rpx;
            color: $color-text-light;
          }
        }
      }
    }
  }

  // 弹出层统一样式
  .popup-container {
    background-color: $color-white;
    border-radius: $radius-lg $radius-lg 0 0;
    padding-bottom: calc(30rpx + env(safe-area-inset-bottom));

    .popup-header {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: $spacing-md $spacing-sm;
      border-bottom: 1rpx solid #fcfcfc;
      .popup-title {
        font-size: 32rpx;
        color: $color-text-dark;
        font-weight: 600;
      }
    }

    .popup-body {
      padding: 30rpx $spacing-sm;

      .input-wrap {
        .nickname-input {
          width: 100%;
          height: 90rpx;
          background-color: #f9f9f9;
          border: 1rpx solid $color-border;
          border-radius: $radius;
          padding: 0 $spacing-sm;
          font-size: 28rpx;
          box-sizing: border-box;
        }
      }

      .gender-options {
        display: flex;
        flex-direction: column;
        gap: $spacing-md;

        .gender-item {
          position: relative;
          display: flex;
          align-items: center;
          justify-content: center;
          height: 96rpx;
          font-size: 30rpx;
          color: $color-text-middle;
          border-radius: $radius;
          background-color: #fafafa;
          border: 2rpx solid $color-border;
          box-sizing: border-box;

          &.selected {
            background-color: rgba($color-primary, 0.15);
            color: #333;
            border-color: $color-primary;
            font-weight: bold;
          }
        }
      }
    }

    .popup-footer {
      padding: 0 $spacing-sm;
      .confirm-btn {
        width: 100%;
        height: 88rpx;
        line-height: 88rpx;
        background-color: $color-primary;
        color: #333;
        font-size: 28rpx;
        font-weight: 500;
        border-radius: $radius;
        &::after {
          content: none;
        }
      }
    }
  }

  .button-section {
    padding: $spacing-lg $spacing-sm;
    .save-btn {
      width: 100%;
      height: 88rpx;
      line-height: 88rpx;
      background-color: $color-primary;
      color: #333;
      font-size: 28rpx;
      font-weight: 500;
      border-radius: $radius;
      &::after {
        content: none;
      }
    }
  }
</style>